Sub topic 12
Rate limiting and throttling
This chapter assumes you know the pipeline from the earlier chapters: producers publish events, workers consume them from queues, and workers call third-party providers. You should also be comfortable with token counters and reading short Python snippets.
Why a notification system needs limits
A notification system sends traffic to people and to providers. Both can be overwhelmed.
- Users. A buggy producer or a busy day can send one person 40 pushes in an hour. Users respond by muting the app or uninstalling it.
- Providers. Push, SMS, and email providers enforce their own quotas. If you exceed them, they return HTTP 429 (Too Many Requests) or suspend your account.
- Your own systems. A marketing campaign to ten million users can fill the queues and delay password-reset messages.
The terms differ slightly. Rate limiting rejects or drops work above a threshold. Throttling slows work down so it still gets done, just later. A notification system uses both: it drops or merges extra messages to a user, and it throttles delivery toward a provider.
Where limits sit in the pipeline
Limits belong at three points, each with a different goal and a different action when the limit is hit.
| Layer | Protects | Typical key | Action when exceeded |
|---|---|---|---|
| Ingestion | Your API | Producer or API key | Reject with 429 |
| Per-user cap | The user's attention | User, type, and channel | Drop, merge, or defer |
| Provider throttle | Provider quota | Provider and account | Delay in the queue |
The per-user cap runs at routing time, before the message is queued. The provider throttle runs in the worker, because it depends on how fast workers are actually sending. Section "Checking in the right order" explains why they are kept separate.
The token bucket
The token bucket is the most common algorithm for this job. A bucket holds up to capacity tokens and refills at rate tokens per second. Each send takes one token. If the bucket is empty, the request is over the limit.
The capacity sets how large a burst is allowed. The rate sets the long-run average. A bucket with rate 1 and capacity 3 allows three sends at once, then one per second.
import time
class TokenBucket:
def __init__(self, rate, capacity, clock=time.monotonic):
self.rate = rate
self.capacity = capacity
self._clock = clock
self._tokens = float(capacity)
self._last = clock()
def _refill(self):
now = self._clock()
elapsed = now - self._last
self._tokens = min(self.capacity, self._tokens + elapsed * self.rate)
self._last = now
def try_acquire(self, n=1):
self._refill()
if self._tokens >= n:
self._tokens -= n
return True
return False
def wait_time(self, n=1):
"""Seconds until n tokens will be available."""
self._refill()
deficit = n - self._tokens
return max(0.0, deficit / self.rate)
class FakeClock:
def __init__(self):
self.t = 0.0
def __call__(self):
return self.t
clock = FakeClock()
bucket = TokenBucket(rate=1, capacity=3, clock=clock)
print([bucket.try_acquire() for _ in range(4)]) # [True, True, True, False]
print(bucket.wait_time()) # 1.0
clock.t += 2
print(bucket.try_acquire(2)) # TrueThe clock is a parameter so tests can control time. Use a monotonic clock in production, because wall-clock time can jump backwards when the system clock is adjusted.
Per-user caps
A per-user cap keeps one person from receiving too much. Key it by user and notification type, and often by channel too. Ten "new follower" pushes in a minute should be limited. A password-reset code sent right after them should not be affected.
class UserCaps:
def __init__(self, rate, capacity, clock=time.monotonic):
self._rate = rate
self._capacity = capacity
self._clock = clock
self._buckets = {}
def admit(self, user_id, type_, channel, priority="normal"):
if priority == "critical":
return True
key = (user_id, type_, channel)
if key not in self._buckets:
self._buckets[key] = TokenBucket(
self._rate, self._capacity, self._clock
)
return self._buckets[key].try_acquire()
caps = UserCaps(rate=1 / 60, capacity=3) # 3 burst, then 1 per minute
results = [caps.admit("user-42", "new_follower", "push") for _ in range(5)]
print(results) # [True, True, True, False, False]This version keeps buckets in process memory. With many workers, each one would see only part of a user's traffic, so the effective limit would be several times too high. In production, keep the counters in a shared store such as Redis and update them atomically, for example with INCR plus an expiry for a fixed window, or a short Lua script for a full bucket. Evict idle buckets so memory does not grow without bound.
What to do with a capped message depends on its type:
- Drop it when it is only informational and stale quickly, such as "someone liked your post."
- Merge it into a digest ("12 people liked your post") when the information still matters.
- Defer it to the next allowed window when it matters but is not urgent.
Throttling toward providers
Providers publish limits, for example a number of requests per second per account. Workers should stay under them on purpose instead of discovering the limit through errors.
def worker_step(provider_bucket, send, requeue):
"""Send one message, or put it back with a delay if over quota."""
if provider_bucket.try_acquire():
send()
return "sent"
requeue(delay=provider_bucket.wait_time())
return "delayed"Delaying through the queue frees the worker to handle other work. A worker that sleeps in place wastes capacity.
Local throttling cannot be perfect. With 20 workers, either they share one bucket in a shared store, or each gets one twentieth of the quota. The second option is simple but wastes quota when load is uneven.
If the provider still returns 429, treat it as a signal to slow down. Read the Retry-After header when present and delay the whole channel, not just the failed message. Otherwise the retry logic from the earlier chapter keeps sending into a provider that has already said no.
Checking in the right order
A common mistake is to take a per-user token and then discover the provider throttle is full. The message is delayed and later checked again, which spends a second user token for one send. The user may then be capped even though nothing was delivered.
Keep the checks separate:
- Check the per-user cap once, at routing time, and queue the message only if it is admitted.
- Check the provider throttle in the worker, as many times as needed. It never touches the user's budget.
Priority and limits
Limits should respect the priority field on the event. Critical messages such as security alerts and one-time codes skip the per-user cap, as UserCaps.admit does above. They still count against the provider throttle, because the provider's quota is real. Give critical traffic its own queue and a reserved share of provider capacity so a bulk campaign cannot starve it.
Common errors
- Limiting only at ingestion. One user can still receive a flood, because the limit counts requests and not recipients.
- No burst allowance. A strict one-per-second rule rejects a legitimate pair of messages sent together, such as an order confirmation and a receipt.
- Per-process counters. Limits multiply by the number of workers, as described above.
- Dropping silently. Count every drop by reason and layer, so the delivery metrics can explain why a message never arrived.
- Synchronized retries. Deferred messages that all become due at the same second hit the provider together. Add jitter to the delay.
Exercise
A worker takes a per-user token, then finds the provider throttle is full and requeues the message. When the message comes back, the worker takes a per-user token again. What goes wrong, and how do you fix it?
Show answer
One send spends two user tokens, so the user can reach their cap early and have later messages dropped even though few were delivered. Fix it by checking the per-user cap once at routing time, before the message is queued, and checking only the provider throttle in the worker. The requeue then never touches the user's budget.
Exercise
A token bucket has rate 2 tokens per second and capacity 10. It starts full. How many messages can be sent in the first 5 seconds if the sender tries as fast as possible?
Show answer
20. The 10 stored tokens are used at once, and 5 seconds of refill at 2 per second adds 10 more, so 10 + 10 = 20.