Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exponential backoff: time.sleep with random.randint(0, 1000) / 1000

Tags:

python

In many google api's code samples i have seen this line of code.

time.sleep((2 ** n) + (random.randint(0, 1000) / 1000))

random.randint(0, 1000) / 1000 always return random milliseconds.

Whats is the use of this random milliseconds ?

like image 785
Nijin Narayanan Avatar asked Dec 12 '14 06:12

Nijin Narayanan


2 Answers

Having a bit of randomness in situations like this is good. For example, if you have a large number of clients hitting the same server, having them use the same deterministic backoff could result in them hitting the server in perfect lockstep, which isn't desirable.

like image 59
NPE Avatar answered Oct 13 '22 10:10

NPE


The reason is explained the API documentation:

In the above flow, random_number_milliseconds is a random number of milliseconds less than or equal to 1000. This is necessary to avoid certain lock errors in some concurrent implementations. The value of random_number_milliseconds must be redefined after each wait.

This is a common technique to "fuzz" the timing of APIs accesses to avoid thrashing caused by falling into recurring patterns of resource lock acquisition and release.

like image 20
Raymond Hettinger Avatar answered Oct 13 '22 12:10

Raymond Hettinger