Skip to content

Instantly share code, notes, and snippets.

@codemartial
Created February 14, 2018 11:53
Show Gist options
  • Save codemartial/0ea7ee06ac115add7c58c61c3d6a7b5d to your computer and use it in GitHub Desktop.
Save codemartial/0ea7ee06ac115add7c58c61c3d6a7b5d to your computer and use it in GitHub Desktop.
Binary Exponential Back-Off Scheduler in Go
// BEBOSchedule computes a Binary Exponential Back-Off schedule given the following:
// retries: maximum number of retry attempts
// waittime: maximum number of seconds from the first attempt after which the operation is permanently failed
//
// The schedule is returned as a list of seconds since first attempt at which a retry must be made
// The schedule will have as many entries as the maximum number of attempts given
func BEBOSchedule(retries, waittime int) ([]uint, error) {
if retries <= 0 || waittime <= 0 || waittime < 1<<uint(retries)-1 {
return []uint{}, fmt.Errorf("Invalid retries or waittime")
}
r, t := uint(retries), uint(waittime)
i := t / (1<<r - 1)
if i == 0 {
return []uint{}, fmt.Errorf("Too many retries in too little time")
}
c := i
sched := []uint{}
for c <= t {
sched = append(sched, c)
i *= 2
c += i
}
return sched, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment