← Study paths

Staying up under load

The layered defence that keeps a service answering when traffic exceeds capacity.

6 blocks · about 31 min of reading · ends with Distributed Rate Limiter

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.

  1. Limit requests per clientFundamental
  2. Drop load before you fall overSenior
  3. Admit only what you can finishStaff
  4. Slow the producer when the consumer is behindSenior
  5. Isolate failuresSenior
  6. Degrade instead of failingFundamental
  7. Distributed Rate Limiter
Reliability & failure handlingSecurity & abuseFundamentalSeniorStaff
Read each block, then tick “I can explain this”: the path remembers where you are.Start with step 1
Your Distributed Rate Limiter so far0 of 6 blocks in
Redis clusterAmazon ElastiCachetoken bucket per key,one Lua callLocal fallback limiterlimit ÷ N per server ifRedis is downClientAPI key, user id or IPAPI gatewayAmazon API Gateway429 with Retry-After;sheds low priorityPer-backend poolsown threads and queueper backendBackend servicesAmazon EC2 Auto Scalingin-flight cap learnedfrom latencyMetrics and rejection streamAmazon Kinesis Data Streamsbounded buffer, sampled whenfullDegraded responseoptional calls timeout to a defaultStep 1: Limit requests per client1Step 6: Degrade instead of failing6Step 1: Limit requests per client1Step 2: Drop load before you fall over2Step 5: Isolate failures5Step 3: Admit only what you can finish3Step 4: Slow the producer when the consumer is behind4Step 6: Degrade instead of failing6requestEVALSHA checkbreaker openadmittedbounded queueallow and 429 eventsoptional call slow

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.

Each block has a diagram. Open one beside its step, or all of them at once.
  1. Limit requests per client

    Security & abusefundamental~5 min

    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.

    Read this block →

  2. Drop load before you fall over

    Reliability & failure handlingsenior~5 min

    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.

    Read this block →

  3. Admit only what you can finish

    Reliability & failure handlingstaff~6 min

    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.

    Read this block →

  4. Slow the producer when the consumer is behind

    Reliability & failure handlingsenior~5 min

    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.

    Read this block →

  5. Isolate failures

    Reliability & failure handlingsenior~5 min

    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.

    Read this block →

  6. Degrade instead of failing

    Reliability & failure handlingfundamental~5 min

    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.

    Read this block →

  7. 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
    Redis clusterAmazon ElastiCachetoken bucket per key,one Lua callLocal fallback limiterlimit ÷ N per server ifRedis is downClientAPI key, user id or IPAPI gatewayAmazon API Gateway429 with Retry-After;sheds low priorityPer-backend poolsown threads and queueper backendBackend servicesAmazon EC2 Auto Scalingin-flight cap learnedfrom latencyMetrics and rejection streamAmazon Kinesis Data Streamsbounded buffer, sampled whenfullDegraded responseoptional calls timeout to a defaultStep 1: Limit requests per client1Step 6: Degrade instead of failing6Step 1: Limit requests per client1Step 2: Drop load before you fall over2Step 5: Isolate failures5Step 3: Admit only what you can finish3Step 4: Slow the producer when the consumer is behind4Step 6: Degrade instead of failing6requestEVALSHA checkbreaker openadmittedbounded queueallow and 429 eventsoptional call slow

    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.

    1. Limit requests per client
    2. Drop load before you fall over
    3. Admit only what you can finish
    4. Slow the producer when the consumer is behind
    5. Isolate failures
    6. Degrade instead of failing

    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.
  8. ★

    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.

AWSUsed here asGoogle CloudMicrosoft AzureOpen source and others
Amazon ElastiCacheRedis cluster, Redis, Timeline cacheMemorystoreAzure Managed RedisRedis, Valkey, Memcached
Amazon API GatewayAPI gateway, Gateway shedderAPI Gateway, ApigeeAPI ManagementKong, Tyk
Amazon EC2 Auto ScalingBackend services, Backend, Matcher, Render and send, Driver gateway, Location service, Router, Push pool: 100, SMS pool: 60, Email pool: 40, Feed serviceCompute Engine managed instance groupsVirtual Machine Scale SetsKubernetes Deployment with a HorizontalPodAutoscaler, Nomad
Amazon Kinesis Data StreamsMetrics and rejection streamPub/SubEvent HubsApache Kafka, Redpanda, Apache Pulsar
Amazon AuroraTrip store, Post storeAlloyDB for PostgreSQL, Cloud SQLAzure Database for PostgreSQL or MySQLPostgreSQL, MySQL, CockroachDB
Amazon SQSMarketing queue, Transactional queue, push queue, sms queue, email queuePub/Sub, Cloud TasksService Bus queues, Queue StorageRabbitMQ, ActiveMQ
Amazon MSK (Kafka)Kafka: locationsManaged Service for Apache KafkaEvent Hubs (Kafka API)Confluent Cloud, Redpanda
Amazon SESSESNo first-party service; SendGrid via MarketplaceAzure Communication Services EmailSendGrid, Mailgun, Postmark
Amazon SageMakerRankingVertex AIAzure Machine LearningKServe, Ray Serve, NVIDIA Triton