4/17
Part 2 of 7 · The token bucketLearn and do
Say no with 429, and say when to come back
RFC 6585 defines 429 Too Many Requests: the user has sent too many requests in a given amount of time. RFC 9110's Retry-After header holds a date or a number of seconds to wait, and Anthropic's docs tell clients to wait that many seconds before retrying. The bucket knows the answer: the missing tokens divided by the refill rate.
# the bucket's tokens at 10.5 s, after the refill
tokens = min(bucket.capacity, bucket.tokens + (10.5 - bucket.last) * bucket.rate)
wait = (1 - tokens) / bucket.rate
print(round(wait, 2), "seconds, so the header says", retry_after_header(tokens, bucket.rate, 1, bucket.capacity))
Retry-After takes whole seconds, and the bucket says 2.5. What goes in the header?
Pick one to see what it prints.
Pick an answer above to see the rest