Rate limiting, backpressure and load shedding

Lesson 5.2 · 12 min read · by Vinay C

We'll cover the following

Visual summary

Infographic summarizing Rate limiting, backpressure and load shedding: A script starts hitting your login endpoint 5,000 times a second, trying passwords. Real users get slow logins, the…

Download imageFree to share, please link back to this lesson.

The problem: one client goes wild

A script starts hitting your login endpoint 5,000 times a second, trying passwords. Real users get slow logins, the servers burn CPU on checking passwords, and the attacker may eventually guess one. Nothing is "broken": every request is valid. What you need is a rule that says how many requests one caller may make in a given time. That rule is rate limiting.

This lesson has two parts. Part 1 is rate limiting: capping ONE caller. Part 2 is backpressure and load shedding: what to do when ALL callers together are more than the system can handle, even though nobody broke a limit.

Part 1: Rate limiting. Why limit?

  • Overload and attacks (DoS): protect the system from floods.
  • Fairness: one noisy customer cannot starve the others.
  • Cost control for expensive calls (LLM, SMS APIs).
  • Abuse prevention: scraping, brute-forcing logins.
  • Business tiers: free plan 100 req/min, paid plan 10,000.

Four algorithms

AlgorithmHowNote
Fixed windowCount requests per minute, reset the count at :00.Simple, but has a boundary spike (see below).
Sliding windowCount requests in the last N seconds, measured from now.Accurate, costs more memory.
Token bucketA bucket refills at a steady rate up to a max size. Each request takes one token. Empty bucket means reject.Allows short bursts with a steady average. The most common answer.
Leaky bucketRequests drain out at a constant rate.Smooths traffic, no bursts.

Worked example: token bucket

Bucket size (capacity) 10 tokens, refill 2 tokens per second, starts full. Think of it as: "on average 2 requests per second, but a burst of up to 10 is fine."

t=0.0s  bucket 10   10 requests arrive -> all allowed, bucket 0
t=0.1s  bucket 0.2  1 request arrives   -> rejected (429), needs 1 full token
t=1.0s  bucket 2    5 requests arrive   -> 2 allowed, 3 rejected, bucket 0
t=6.0s  bucket 10   5 idle seconds would give 10 tokens; capped at 10

The burst of 10 went through, then the caller was held to about 2 per second. The cap matters: a client that stays quiet for an hour still gets only 10 in a burst, not 7,200.

A common mix-up: in a token bucket, tokens are not returned when a request finishes. They only come back through the refill over time. A scheme where the token returns on completion is a concurrency limiter (max N requests in flight at once). It is valid, but it is a different tool (it reappears in Part 2).

The fixed-window boundary spike

Say the limit is 100 per minute with the count reset at each minute boundary.

12:00:59  100 requests -> window 12:00 count = 100, all allowed
12:01:00  counter resets to 0
12:01:01  100 requests -> window 12:01 count = 100, all allowed

200 requests in 2 seconds, yet each window saw only 100.

The caller got double the intended rate. A sliding window or a token bucket does not have this hole.

How to choose

  • Default to token bucket. Cheap (one counter and a timestamp per caller), and bursts are usually what real users do (a page loads 8 API calls at once).
  • Sliding window when you need a strict, accurate "no more than N in any 60 seconds" and can pay the memory.
  • Leaky bucket when the thing behind it needs a perfectly steady flow and bursts would hurt it.
  • Fixed window only when simple matters more than accuracy, and a 2x spike at the boundary is acceptable.

Where to enforce, what to key on, what to return

  • Where: the gateway by default (cheap, central). Add a second layer on expensive endpoints inside services as defense in depth. Client-side limiting is politeness only, because a bad client just ignores it.
  • Key on: user ID, API key or IP. (For the login attack, the account name and the IP are both worth limiting.)
  • Return: HTTP 429 (Too Many Requests) with a Retry-After header, so well-behaved clients know when to come back.

The distributed problem: 50 gateways, 100 req/min per user

With only local counters, a user's requests spread across the 50 gateways, so no gateway knows the real count. A user could send 100 to each and get 5,000 through. Three options:

  • Shared counter in Redis (the standard). Use an atomic operation, such as INCR user:42:minute plus EXPIRE, or a Lua script, so gateways cannot race each other. Add replicas. Costs about a 1 ms network hop per request. Choose this by default.
  • Sticky routing by user. The load balancer sends the same user to the same gateway, so local counters work and are fast. Downsides: uneven load, counters lost when a gateway dies, and a reshuffle when gateways change (consistent hashing limits that to 1/N of users). Choose it when you already route by user for other reasons.
  • Approximate local counters that sync every second or so. Slight overshoot (105 instead of 100) but no Redis call on the hot path. Choose it for massive scale where the 1 ms hop or Redis load is the bottleneck and a small overshoot is fine.

If Redis dies: fail open or fail closed?

  • Fail open: let traffic through unlimited. The usual choice for general APIs, because blocking everyone is worse than briefly having no limit.
  • Fail closed: block requests. For sensitive things like login attempts, where the limit is the security.

Part 2: Backpressure and load shedding. When everyone together is too much

Rate limiting caps what one caller may send. Backpressure and load shedding decide what the system does when total demand is above capacity, even though no single caller broke a limit. Typical causes: a viral post, a retry storm, a slow dependency. Here are the tools.

TechniqueHowNote
Bounded queues + backpressureGive every queue a maximum size. When it is full, tell the producer to slow down: block it, reject with an error, or let the consumer pull at its own pace (Kafka consumers pull, TCP uses a receive window).An unbounded queue hides the overload, then turns it into huge latency and out-of-memory crashes.
Load sheddingWhen saturated, reject work early and cheaply: return 503 + Retry-After. Drop the least important first (recommendations before checkout; background sync before user clicks).Failing 20% fast beats making 100% of requests slow.
Timeouts and deadlinesEvery call has a timeout, and the remaining deadline is passed downstream so a service never works on a request whose caller already gave up.Without them, threads pile up waiting on a slow dependency and the failure spreads upstream.
Retries with backoff and jitterWait 1s, 2s, 4s... plus random jitter, with a cap and a retry budget (e.g. at most 10% extra traffic from retries).Naive retries multiply load exactly when the system is weakest (retry storm). Retrying only makes sense for idempotent calls.
Concurrency limitsCap in-flight requests per instance (a concurrency limiter, see the token bucket correction above). Adaptive versions lower the limit when latency rises.Protects a service from itself when a downstream slows down.

These techniques work as layers. Timeouts, retries with backoff and the other failure-isolation tools are covered further in the microservices lesson.

Why "just queue it all" fails

It sounds kind: accept everything, process it when we can. But waiting time in a queue is latency = queue length / service rate. Say you serve 100 requests per second and a spike leaves 1,000 requests waiting. The last one waits 1,000 / 100 = 10 seconds. If clients give up after 2 seconds, then almost everything you now process is for callers who have already left. The system is busy, yet nobody gets a useful answer.

  • Clients that time out retry, adding more load. The backlog can keep the system down even after traffic returns to normal (a metastable failure).
  • Queues are right for work that can wait (emails, reports). They are wrong in front of a synchronous user request.
Check yourselfTraffic is 3x capacity for ten minutes. Do you queue everything or reject some?

Reject some. Shed the lowest-priority requests early with 503 + Retry-After, keep a small bounded queue for the rest, and have clients back off with jitter. An unbounded queue turns overload into latency beyond every timeout, so you serve nobody, and the backlog keeps the system down after the spike ends.

Check yourselfYour API limit is 100 req/min per user, but each of your 50 gateways keeps its own counter. What goes wrong and what do you do?

A user whose requests spread over the gateways can get far more than 100 through, because no gateway sees the true count. Use a shared Redis counter with atomic increments (INCR + EXPIRE or a Lua script). If the 1 ms hop becomes a bottleneck, use local counters with periodic sync and accept slight overshoot. Decide fail open (general APIs) or fail closed (login) for when Redis is down.

Summary: say it in the interview

  • "Redis with atomic increments, accepting a 1 ms hop. If that becomes a bottleneck, local counters with periodic sync and accept slight overshoot."
  • "Rate limiting protects me from one caller; backpressure and load shedding protect me from all callers at once. I would rather fail 20% fast than 100% slowly."