Sub topic 12
Rate limiting and throttling
This chapter assumes you know the pipeline from earlier chapters: events enter through an API, preferences filter them, and queues feed channel workers that call providers. It also assumes you can read short Python snippets.
Why limit notifications
Rate limiting caps how many notifications flow through a part of the system in a period of time. Throttling slows traffic down instead of rejecting it. A notification system needs both, for two different reasons:
- Protecting users. A buggy producer or a busy day can send one person twenty pushes in a minute. Users respond by disabling notifications or uninstalling the app.
- Protecting providers. Email, SMS and push providers enforce their own quotas. If you exceed them, they return errors such as HTTP 429 or suspend your account.
Where to apply limits
Limits sit at several layers, and each layer guards against a different problem.
| Layer | What it limits | Typical action when exceeded |
|---|---|---|
| Producer (ingestion API) | Events per service per second | Reject with 429 |
| Per user | Notifications per user per hour or day | Drop, merge or delay |
| Per channel worker | Calls per second to a provider | Slow the worker down |
Per-user limits should depend on the notification type. Security codes and payment alerts usually bypass them. Marketing messages get the strictest caps.
A token bucket
The token bucket is a common algorithm. A bucket holds up to capacity tokens and refills at a steady rate. Each send takes one token. An empty bucket means the send must wait or be refused. Because the bucket can be full, short bursts are allowed, but the long-run average stays at the refill rate.
import time
class TokenBucket:
def __init__(self, rate, capacity):
self.rate = rate # tokens added per second
self.capacity = capacity # maximum stored tokens
self.tokens = capacity
self.updated = time.monotonic()
def allow(self):
now = time.monotonic()
elapsed = now - self.updated
self.updated = now
self.tokens = min(self.capacity, self.tokens + elapsed * self.rate)
if self.tokens >= 1:
self.tokens -= 1
return True
return False
# One bucket per user: bursts of up to 3, then about 1 per minute.
bucket = TokenBucket(rate=1 / 60, capacity=3)
results = [bucket.allow() for _ in range(5)]
print(results) # [True, True, True, False, False]This version lives in one process. With many workers, keep the counters in a shared store such as Redis and update them atomically, for example with a Lua script. Otherwise each worker enforces its own limit and the real limit is multiplied by the number of workers.
What to do when a limit is hit
Choose the action by type. A shipping update can wait, so requeue it. Ten "new like" alerts can become one digest. A one-time offer that expires in minutes may simply be dropped.
Common errors
- Dropping silently. Record every dropped or delayed notification with a reason, or you cannot explain a missing message later.
- Blocking the worker. Sleeping inside a worker stalls everything behind it. Requeue with a delay instead.
- Ignoring provider 429 responses. Treat them as a signal to reduce your sending rate, and honor any
Retry-Afterheader. Retrying at full speed makes it worse. - One shared limit for all priorities. Bulk campaigns then starve urgent messages.
Exercise
A worker fleet of 10 machines each runs its own in-memory token bucket allowing 100 SMS per second. The provider allows 300 per second in total. What goes wrong, and how do you fix it?
Show answer
Each machine enforces its own limit, so the fleet can send up to 1,000 per second, well above the provider's 300 per second, which leads to 429 errors. Fix it by sharing one counter across workers in an atomic store such as Redis, or by giving each worker an explicit share of 30 per second.