Resonata pulls artist metrics from an external music API both on demand, when a user searches, and on a schedule when Celery beat refreshes every tracked artist. The total multi-process traffic has to stay under a quota the provider enforces on the whole service. This is a breakdown of the rate limiter that makes that work, how some of the design decisions were made, and how it composes with the two resilience layers around it.
The problem: per-process limiters leak quota
The default reach for rate limiting in Python is a module-level object holding a counter. It works beautifully until you deploy. Resonata runs:
- Several Gunicorn workers serving the Django REST API — user-triggered artist searches.
- A Celery worker running the daily snapshot task, which walks the full list of tracked artists.
- A Celery beat process scheduling that task.
Each of those is a separate OS process with its own memory. A module-level limiter configured for 60 requests per minute doesn't give you 60 requests per minute — it gives each process 60 requests per minute. With four Gunicorn workers and a Celery worker, the real ceiling is 300 req/min. The quota is liable to get blown through during a traffic spike, or more active users than expected during the nightly batch job running.
The fix is to move the bucket out of process memory and into somewhere all five processes can see it. Redis is already in the stack as the Celery broker, so it costs nothing extra to run.
Why token bucket
Some common candidates for a rate limiter algorithm include fixed window counter, sliding window counter, sliding window log, leaking bucket and token bucket.
Two things narrow that list. The limiter fronts two call paths with opposite needs: a user search that must not wait, and the Celery snapshot task, which is a bare loop with no pacing of its own, so the limiter is its throttle. The other thing is that a caller who can't get a token waits for one instead of being turned away, and it only waits ten seconds before giving up. A window counter doesn't trickle its budget back, it resets at the window edge, so once the minute's allowance is gone a caller sits there until the clock rolls over. That can be most of a minute, and the batch job would spend its run collecting timeouts instead of being paced.
- Fixed window counter is the cheapest to build, but it allows a burst of twice the limit across a window boundary, which would be unkind to the provider.
- Sliding window log is the most accurate, but it stores a timestamp per request to buy precision I don't need against a limit I set myself.
- Sliding window counter fixes the boundary burst cheaply, but it assumes requests arrive evenly across the window, and mine arrive in clumps.
- Leaking bucket gives the smoothest outbound rate, but it refuses bursts on principle, so an idle hour earns a user's search nothing. It's also just a token bucket with a capacity of one, so I keep it as a config change.
A token bucket is the one with two knobs instead of one. The bucket holds up to capacity tokens and refills continuously at refill_rate tokens per second. A request consumes one token; if the bucket is empty, the caller waits. The two parameters decouple two things I wanted to tune separately:
- Steady-state throughput is the refill rate.
- Burst tolerance is the capacity. An idle system can absorb N requests immediately before throttling kicks in.
That matches what I expected traffic might look like. Long quiet stretches, interactive calls that shouldn't wait, and a batch job that's ok to be slow. And because tokens trickle back continuously rather than all at once, anyone who does have to wait never waits more than about a second, which is what makes that short, bounded wait workable in the first place.
Lazy refill
Nothing runs on a timer to add tokens. Instead the bucket stores two values: the token count and the timestamp of the last refill. Every call computes the refill it missed.
elapsed = now - last_refill
tokens = min(capacity, tokens + elapsed * refill_rate)
No background process, no clock skew between a refiller and its consumers, and the state is two keys instead of a sliding log of every request timestamp.
The race condition
Redis fixes visibility but introduces a race condition. Checking and consuming a token is a read-modify-write: read the count and the last-refill timestamp, add whatever the elapsed time earned, then write back the count minus one.
Two processes can both finish the read before either reaches the write. Both see one token, both take it, and two requests get served on one token. The drift compounds under load, performing the worst when the service is at its busiest.
Redis runs a Lua script atomically — no other command touches that instance while the script is in flight. Putting the whole read-modify-write inside the script makes it one indivisible operation, with no locks to acquire, and turns three round trips into one.
local tokens_key = KEYS[1]
local last_key = KEYS[2]
local capacity = tonumber(ARGV[1])
local refill_rate = tonumber(ARGV[2])
local now = tonumber(ARGV[3])
local tokens = tonumber(redis.call('GET', tokens_key))
local last = tonumber(redis.call('GET', last_key))
if not tokens then tokens = capacity end
if not last then last = now end
local elapsed = math.max(0, now - last)
tokens = math.min(capacity, tokens + elapsed * refill_rate)
redis.call('SET', last_key, now)
if tokens >= 1 then
redis.call('SET', tokens_key, tokens - 1)
return 1
else
redis.call('SET', tokens_key, tokens)
return 0
end
Most of the defensive work in there is about the two ways this script can be handed bad state. Missing keys default to capacity rather than zero, so a fresh or flushed Redis doesn't stall every worker for 30 seconds while the bucket fills from empty. And because each caller passes its own time.time(), a host whose clock lags can produce a negative interval, which without the math.max(0, now - last) clamp would remove tokens — a badly skewed machine could drain the bucket for everyone.
The rest is bookkeeping. The count stays a float so partial refills aren't rounded away and the long-run rate holds. The timestamp advances on every call including rejections, which is safe because the refill is already folded into tokens by that point, so no credit is lost. The script is registered once via register_script, which uses EVALSHA and sends the body only if Redis hasn't cached it.
The client side: blocking with a deadline
The script answers, "did I get a token". The caller's job is to wait it's turn.
def acquire(self, timeout: float = 10.0) -> None:
deadline = time.monotonic() + timeout
poll_interval = 0.1
while True:
acquired = self._script(
keys=[self.KEY_TOKENS, self.KEY_LAST],
args=[self._capacity, self._refill_rate, time.time()],
)
if acquired:
return
remaining = deadline - time.monotonic()
if remaining <= 0:
raise SpotifyRateLimitTimeout(...)
time.sleep(min(poll_interval, remaining))
poll_interval = min(poll_interval * 1.5, 1.0)
The poll interval backs off. It starts at 100ms so a request arriving just before a token refills isn't punished with a full second of latency, then grows by 1.5× up to a one-second ceiling. A fixed tight poll would have every blocked worker hammering Redis; a fixed slow one would add latency to the common case.
The two clocks are deliberate. The deadline uses time.monotonic(), which can't jump backwards from an NTP correction, so the timeout is trustworthy. The refill has to use time.time(), because it compares timestamps written by different processes and monotonic clocks aren't comparable across them. Wall-clock time is the only option there, and the skew clamp in the Lua script is what pays for it.
Either way the blocking is bounded. Waiting forever on a quota turns a throttled dependency into exhausted Gunicorn workers and an unresponsive site, so after ten seconds acquire raises SpotifyRateLimitTimeout and the request fails cleanly instead of hanging.
How it composes
The limiter is the middle of three layers every outbound call passes through in SpotifyService._call: a circuit breaker that fast-fails if the provider is already considered down, then the rate limiter, then a Tenacity retry with exponential backoff and jitter. The order is the interesting part.
The breaker goes first because it's the cheapest check and the only one that can avoid the wait entirely. There's no sense spending ten seconds queueing for a token to call a service that five consecutive failures say is unavailable. It's Redis-backed for the same reason the limiter is — a per-process breaker would need every worker to independently rediscover the same outage.
Retry goes last, innermost, wrapping only the HTTP call, and that placement is a constraint rather than an accident. It's scoped to requests.Timeout and requests.ConnectionError and nothing else. A 429 or a 5xx is not retried there, because retrying a response that means "you are sending too much" is how a rate limit problem becomes an outage. Those failures belong to the breaker instead, which is what the two bypass exceptions are drawing the line around.
except (SpotifyCircuitOpenError, SpotifyRateLimitTimeout):
raise
except Exception:
self.circuit_breaker.record_failure()
raise
A rate-limit timeout and an open circuit are our states, not evidence about the provider's health. Counting them as failures would let a local traffic spike trip the breaker and manufacture an outage out of the thing meant to prevent one. Only genuine call failures feed the breaker.
The short version: if a rate limiter's state lives in process memory, its configured limit is a lie multiplied by your worker count. Move the state somewhere shared, make the refill-and-consume atomic so concurrency can't double-spend a token, bound the blocking so a throttled dependency can't exhaust your workers, and keep your own backpressure out of the signal you use to judge somebody else's health.