Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
The limiter, as written, will force all consumers to sleep on average
time_between_slots
seconds, regardless of all other parameters and number of workers.Problem
The first time the script is called, it sets the next available slot to "now + time_between_slots" due to the line
slot = now + time_between_slots
. This immediately schedules the next "available" token a fulltime_between_slots
into the future, regardless of the amount of tokens that exist.Then, when the script is called again, if tokens have been used or the time has passed, it still returns the incorrectly advanced "next slot" time, continuously enforcing a delay of, at a minimum,
time_between_slots
into the future, again ignoring the actual amount of tokens available.Solution
The updated script correctly calculates the amount of slots that have passed since the last token was added and refills tokens accordingly. It also advanses slots according to slots passed and only tells the consumer to wait when the bucket is empty.
Demo
Before: Adding 3 items
After: Adding 60 items
Simulating a worker pool
Before:
After: