Staying up under load
The layered defence that keeps a service answering when traffic exceeds capacity.
When you finish, you should be able to say
Order the defences from the edge inward and say what each one rejects and why.
The route
6 blocks (2 fundamental, 3 senior, 1 staff), then the practice problem.
- Limit requests per clientFundamental
- Drop load before you fall overSenior
- Admit only what you can finishStaff
- Slow the producer when the consumer is behindSenior
- Isolate failuresSenior
- Degrade instead of failingFundamental
- Distributed Rate Limiter
Next, step 1 adds Redis cluster, API gateway (outlined). A box fills in when you tick “I can explain this” on the block that introduces it; plain boxes come from the problem itself.
The first gate: cap each client so one cannot crowd out the rest.
One client (or a bot) floods the API and degrades it for everyone.
Say it like this: I need a per-client cap that is accurate across the fleet, so I count in Redis with a token bucket in one atomic Lua script and return 429 with Retry-After when the bucket is empty.
Adds to the design: Redis cluster, API gateway
Check yourself: Walk through the token bucket maths for 100 requests per minute.
Capacity 100 tokens, refill 1.667 per second. On each request compute tokens = min(100, tokens + (now − last) × 1.667). If tokens ≥ 1, subtract one and allow; otherwise deny and Retry-After = (1 − tokens) / 1.667 seconds. Store tokens and last as two fields, updated atomically.
When total load is still too high, reject early so the rest succeed fast.
Traffic exceeds capacity and every request slows until all time out.
Say it like this: When demand exceeds capacity the worst outcome is every request timing out, so I shed load early: the gateway rejects the least valuable traffic with a 429 when queue depth or latency crosses a line, and the requests we keep finish fast.
Adds to the design: API gateway
Check yourself: What is the difference between load shedding and rate limiting?
Rate limiting is per client and enforces a contract regardless of load. Load shedding is per server and reacts to actual saturation regardless of who is calling. You need both: limits stop one client from being unfair, shedding stops the sum of fair clients from sinking the server.
Bounding in-flight work per service, and adapting the bound from latency.
Accepting every request means all of them slow down together once the queue grows past what can be served within the deadline.
Say it like this: Queueing more work than we can finish inside the deadline only makes every request late, so each service caps its in-flight requests at a limit learned from latency, rejects beyond it immediately, and drops any request whose deadline has already passed.
Adds to the design: Backend services
Check yourself: How is this different from a rate limiter?
A rate limiter enforces a per-client contract in requests per second, independent of how healthy the server is. Admission control bounds the server’s own in-flight work based on how fast it is finishing, independent of who is calling. One protects fairness, the other protects latency.
Inside the system: how a slow consumer slows the producer instead of running out of memory.
A fast producer fills memory or queues faster than consumers drain them.
Say it like this: The producer is faster than the consumer, so I bound every buffer and make the fast side wait, drop or sample when the buffer is full; otherwise an overload becomes an out-of-memory crash ten minutes later.
Adds to the design: Metrics and rejection stream
Check yourself: How is backpressure different from rate limiting?
Rate limiting enforces a policy decided in advance per client. Backpressure is a dynamic signal from the actual consumer’s capacity right now. You usually want both: limits keep one client from hogging, backpressure keeps the system alive when everyone is within their limits but the sum is too much.
Isolating one tenant or dependency so its failure stays contained.
One slow tenant or one slow endpoint consumes all threads and starves the rest.
Say it like this: One slow provider should not stall every other channel, so I give each dependency and each priority its own worker pool and queue: a bulkhead so a Twilio outage fills the SMS compartment and leaves push untouched.
Adds to the design: Per-backend pools
Check yourself: How do you size each compartment?
Concurrency needed is rate times latency: 870 SMS/s at 50 ms is 44 concurrent calls, so 60 threads with headroom. Measure p99 latency, not average, and re-check after a provider changes. Leave the sum of compartments within what the host can run.
When something must give, decide in advance what the user loses.
A non-critical part (recommendations, ads, analytics) is down and takes the page with it.
Say it like this: The feed must load even if ranking is down, so every non-critical call has a timeout and a default: I serve the chronological timeline from cache rather than a blank page, and a flag lets me switch ranking off without a deploy.
Adds to the design: Local fallback limiter, Degraded response
Check yourself: How do you pick the timeout for an optional call?
Start from the page budget and subtract the critical path. If the page must return in 300 ms and critical work takes 50 ms, optional calls in parallel can have up to about 150 ms, leaving headroom. Then tighten to the call’s normal p99 plus a margin, so a slow dependency is cut off before it costs much.
Putting it together
How the blocks above combine into one design for Distributed Rate Limiter. The numbers on the boxes are the steps that introduce each part.
The rate-limited API gateway, assembled from the path Each number is a step of this path; a box with two numbers is shaped by both blocks. The ring colour is the block's category, as on the route map. Boxes without a number come from the problem itself. Point at a step below, or at a bubble, to see where it appears.
The gateway checks each client against a Redis token bucket, sheds low-priority traffic when it is saturated, and passes the rest into separate pools for each backend. Backends cap their in-flight work, and when Redis or an optional dependency is slow the system answers with an approximate limit or a default instead of failing.
How each block shows up in the design
- 1. Limit requests per client: the gateway sends one atomic Lua script to Redis per request, so a token bucket per API key or user is exact across the fleet at about 1 ms, inside the p99 under 2 ms target; a client already over its limit gets 429 with Retry-After from a locally cached rejection until its reset time.
- 2. Drop load before you fall over: when the gateway's in-flight requests or queue time cross a threshold, it rejects the least valuable traffic first, such as lower client tiers and batch endpoints, with an immediate Retry-After, so the requests it keeps still finish fast.
- 3. Admit only what you can finish: each backend caps its concurrent requests at a limit learned from its own latency and drops any request whose deadline has already passed, so a burst that slips past the limiter cannot push every request into a timeout.
- 4. Slow the producer when the consumer is behind: allow and 429 events leave the gateway through a bounded buffer to the metrics stream, and when that buffer fills the gateway samples events rather than growing memory until it crashes.
- 5. Isolate failures: each backend gets its own pool and queue behind the gateway, so one slow service fills its own compartment and leaves the others answering.
- 6. Degrade instead of failing: if Redis is slower than the 5 ms timeout, a circuit breaker opens and each gateway falls back to a local token bucket sized at limit divided by the number of servers, failing open for public APIs and closed for auth-sensitive ones; inside the backends, optional calls time out to a default.
- ★
Distributed Rate Limiter
Now run the timed practice. The blocks above should appear in your answer without prompting; if one does not, that is the one to reread.
The same parts on other clouds
The diagrams above name AWS services as one concrete example. Every part has a close equivalent elsewhere. In an interview, name the role first, such as “a managed Redis cache”, then the product you would pick.
| AWS | Used here as | Google Cloud | Microsoft Azure | Open source and others |
|---|---|---|---|---|
| Amazon ElastiCache | Redis cluster, Redis, Timeline cache | Memorystore | Azure Managed Redis | Redis, Valkey, Memcached |
| Amazon API Gateway | API gateway, Gateway shedder | API Gateway, Apigee | API Management | Kong, Tyk |
| Amazon EC2 Auto Scaling | Backend services, Backend, Matcher, Render and send, Driver gateway, Location service, Router, Push pool: 100, SMS pool: 60, Email pool: 40, Feed service | Compute Engine managed instance groups | Virtual Machine Scale Sets | Kubernetes Deployment with a HorizontalPodAutoscaler, Nomad |
| Amazon Kinesis Data Streams | Metrics and rejection stream | Pub/Sub | Event Hubs | Apache Kafka, Redpanda, Apache Pulsar |
| Amazon Aurora | Trip store, Post store | AlloyDB for PostgreSQL, Cloud SQL | Azure Database for PostgreSQL or MySQL | PostgreSQL, MySQL, CockroachDB |
| Amazon SQS | Marketing queue, Transactional queue, push queue, sms queue, email queue | Pub/Sub, Cloud Tasks | Service Bus queues, Queue Storage | RabbitMQ, ActiveMQ |
| Amazon MSK (Kafka) | Kafka: locations | Managed Service for Apache Kafka | Event Hubs (Kafka API) | Confluent Cloud, Redpanda |
| Amazon SES | SES | No first-party service; SendGrid via Marketplace | Azure Communication Services Email | SendGrid, Mailgun, Postmark |
| Amazon SageMaker | Ranking | Vertex AI | Azure Machine Learning | KServe, Ray Serve, NVIDIA Triton |