backoff
backoff copied to clipboard
Add API `backoff:exp/1`/`backoff:exp/2`
In my usage I count the number of retries R. I want to process an exponential backoff delay directly from this number R.
Why not offer an API such as:
1> backoff:increment(1).
2
2> backoff:increment(2).
4
3> backoff:increment(3).
8
This is the same as doing the recursive calls, but is more direct to use when working with a state tracking the number of retries.
The same with the jitter API: backop:exp_rand/1
and backop:exp_rand/2
.
I could do a PR if this makes sense.
backoff:increment(1)
already exists. It just does it by a bitshift rather than exponentiation since the default exponentiation function in Erlang works on floats and handling for timers is probably a lot slower. You could probably define one with N*N
if you wanted. You can cheat and use the non-exponent based form by using retry numbers:
1> backoff:increment(1 bsl 0).
2
2> backoff:increment(1 bsl 1).
4
3> backoff:increment(1 bsl 2).
8
4> backoff:increment(1 bsl 3).
16
so if you feed 1 bsl FailCount
you do get the behaviour you'd like with the current API, and similarly for backoff:rand_increment(1)
.
I probably have no problem adding a shortcut like:
exp(N) -> increment(1 bsl N).
exp_rand(N) -> rand_increment(1 bsl N).
Since those are pretty straightforward.
Sorry I just see I put backoff:increment/1
in my examples. There were intended to be:
1> backoff:exp(1).
2
2> backoff:exp(2).
4
3> backoff:exp(3).
8
The backoff:increment(1 bsl FailCount)
is indeed what I needed.
The shortcut may be useful. It lets the user get its result without thinking at all. :) ahah