On a normal day your system handles 1,000 requests a second. On Black Friday, 100,000 arrive. In the last article, the load balancer spread requests across servers. But if all your servers together can handle 10,000 a second, spreading 100,000 around doesn’t help. Every server drowns.
Without traffic control, a system accepts everything that arrives. Connections run out, memory fills up, responses slow down, timeouts pile up, and then everything falls over. Good users suffer because of a spike, a bug in someone’s script, or an attacker.
“Serving some users well beats serving every user badly, or no one at all.”
Think of a concert hall with one door. The organisers have five tricks, and each one has a name in software:
Let’s go through them one by one.
1. Rate limiting: a quota per client
Rate limiting caps how many requests each client can make in a period: say, 100 requests a minute per user or per API key. Requests over the limit are rejected straight away with 429 Too Many Requests and a Retry-After header telling the client when to try again.
It’s the first line of defence, and it does three jobs:
- Protects your servers from runaway scripts and bots.
- Keeps things fair. One noisy customer can’t use up capacity that belongs to everyone.
- Supports pricing tiers. Free users get 50 requests a minute, paying users get 1,000.
There are several ways to count:
| Algorithm | How it counts | Good | Weak |
|---|---|---|---|
| Fixed window | counter per minute, reset on the minute | simplest | a burst at 0:59 and 1:00 gets double the limit |
| Sliding window log | stores the time of every request | exact | memory per request |
| Sliding window counter | blends this window and the last one | accurate and cheap | an estimate, not exact |
| Token bucket | tokens refill at a steady rate; each request spends one | allows short bursts; the industry favourite | two settings to tune |
| Leaky bucket | requests drain out at a fixed rate | perfectly smooth output | bursts wait or get dropped |
We covered how these work, and how to share a limit across many servers with Redis, in designing a rate limiter. In Java, a library like Bucket4j gives you a token bucket in a few lines:
// Java · Bucket4j token bucket: 100 requests per minute, refilled smoothly
Bucket bucket = Bucket.builder()
.addLimit(limit -> limit.capacity(100).refillGreedy(100, Duration.ofMinutes(1)))
.build();
if (!bucket.tryConsume(1)) {
return ResponseEntity.status(429).header("Retry-After", "60").build();
}
A tip: limit by cost, not just by count. A search that scans a million rows and a request for a profile picture aren’t equal. Make expensive endpoints spend more tokens.
2. Throttling: slow down instead of saying no
Rate limiting says “no”. Throttling says “wait”. Extra requests aren’t rejected; they’re delayed so they go through at a steady pace.
Imagine a nightly batch job that fires 1,000 requests a second at an API that only allows 100. With rate limiting, 900 of every 1,000 fail and the job crashes. With throttling, the job slows itself to 100 a second, takes ten times longer, and finishes.
// Java · Guava RateLimiter on the CALLER side: never send more than 100 per second
RateLimiter limiter = RateLimiter.create(100.0);
for (Order order : ordersToSync) {
limiter.acquire(); // waits here if we're going too fast
partnerApi.send(order);
}
Throttling works best on the caller’s side, or with work in a queue. On a web server, making a request wait means holding a thread for it, and a server full of waiting threads is a server that can’t take anything new. So servers usually reject (rate limit), and well-behaved clients throttle themselves.
3. Backpressure: “slow down, I can’t keep up”
Backpressure is when a slow part of the system tells the fast part feeding it to slow down. Instead of piling up work it can’t finish, the busy service pushes the pressure back upstream.
You’ve probably used backpressure without noticing:
- TCP does it for every connection: if the receiver’s buffer is full, the sender has to wait.
- Kafka consumers pull messages when they’re ready, so a slow consumer simply falls behind instead of being flooded. On the sending side, the Kafka producer blocks when its buffer fills up.
- Bounded queues in Java, like
ArrayBlockingQueue, make the producer wait when the queue is full. - Reactive streams (Spring WebFlux, Project Reactor) let a subscriber ask for exactly n more items at a time.
When the buffer is full, you must choose what happens: wait (block the sender), drop new items, keep only the latest item (fine for live prices), or fail with an error. What you must not do is buffer forever.
4. Load shedding: drop some to save all
When a system is truly overloaded, trying to serve everyone means serving no one: every request gets slower until they all time out. Load shedding means deliberately rejecting some requests so the rest succeed.
Say capacity is 1,000 requests a second and 5,000 arrive. Try to handle all 5,000, and the servers crash: 0 served. Shed 4,000 fast with 503 Service Unavailable, and 1,000 are served properly.
The smart version doesn’t shed at random. It sheds the least important work first:
- Critical: checkout, payments, login. Shed last.
- High: logged-in users browsing and searching.
- Medium: free-tier and anonymous traffic.
- Low: analytics, recommendations, prefetching. Shed first.
How do you know you’re overloaded? CPU is a rough signal. Better ones are requests in progress and time spent waiting in a queue: if a request has already waited longer than the client will wait for it, it’s pointless to start it. Libraries like Netflix’s concurrency-limits adjust the limit automatically by watching latency.
A rule worth remembering: use 429 when one client is over its limit, and 503 when the whole system is overloaded. Both should carry a Retry-After header.
5. Queues as buffers
Traffic comes in bursts. Your workers run at a steady pace. A queue sits between them, soaks up the burst, and lets workers catch up.
If 1,000 orders arrive in one second and your workers process 100 a second, a queue holds the extra 900 and they’re all done ten seconds later. Nothing is lost, and the order page answers instantly with “We’ve got your order”. Message brokers like RabbitMQ, Kafka and Amazon SQS do this job.
Two rules keep a queue from becoming a time bomb:
- Bound it. Set a maximum size, and decide what happens when it’s full: reject new work, or shed the oldest.
- Consumers must keep up on average. A queue can absorb a spike, but if work arrives faster than it’s processed all day long, the queue grows forever. Watch queue depth, and add consumers when it climbs.
Queues also add latency (work happens later, not now) and they’re one more thing to run. We’ll go deep on them in the next part of the notebook, on asynchronous systems.
Which tool, when
| Tool | What it does | Use it when | The cost |
|---|---|---|---|
| Rate limiting | rejects a client over its quota | protecting public APIs, fairness, pricing tiers | real users can be blocked |
| Throttling | slows requests to a steady pace | batch jobs, calling partner APIs | everything takes longer |
| Backpressure | a slow service tells its sender to slow down | pipelines, streams, service-to-service calls | delays spread upstream |
| Load shedding | drops low-priority work under overload | emergencies, sudden spikes | some users get errors |
| Queues | holds bursts for steady processing | work that doesn’t need an instant answer | added latency; queues can grow |
They work best together: rate limits at the edge, queues for slow work, backpressure between services, and load shedding as the emergency brake.
What breaks, and how to fix it
| What breaks | What you see | The fix |
|---|---|---|
| The rate limiter’s Redis goes down | Every request fails, or no request is limited | Choose on purpose: fail open (allow traffic; fine for most consumer apps) or fail closed (reject; for sensitive endpoints like login or payments) |
| The rate limiter is the bottleneck | Every request makes a Redis call, and Redis maxes out | Count locally on each server, and sync with Redis less often. Slightly less exact, far cheaper |
| Everyone retries at the same moment | The limit window resets at 11:01:00, and every blocked client retries at once | Clients use exponential backoff with jitter: wait 1 s, 2 s, 4 s… plus a random extra |
| Slow clients hold every connection | An attacker opens thousands of connections and sends 1 byte a second (a Slowloris attack). Request limits never trigger | Short connection and header timeouts (in Spring Boot, server.tomcat.connection-timeout), a reverse proxy like Nginx in front, and per-IP connection limits |
Puzzle 1: the retry storm
The client now sends more traffic, not less. Every rejection becomes another instant request, so a client that was sending 100 requests a second might now send 1,000. Multiply that by every client running the same code, and the limit you set to protect the system is what overloads it. This is a retry storm.
Fixes on both sides:
- Server: always send
Retry-After, and reject as cheaply as possible. - Client: respect
Retry-After; otherwise use exponential backoff with jitter; cap the number of retries; and stop calling altogether for a while when failures pile up (a circuit breaker).
// Java · exponential backoff with jitter: 1 s, 2 s, 4 s… plus a random extra
for (int attempt = 0; attempt < 5; attempt++) {
try {
return callApi();
} catch (TooManyRequestsException e) {
long backoff = 1000L << attempt;
Thread.sleep(backoff + ThreadLocalRandom.current().nextLong(backoff));
}
}
throw new ServiceBusyException("Gave up after 5 attempts");
Puzzle 2: the attack that passed every limit
That’s 10 million requests a minute, and no single IP broke the rule. A per-client limit can’t stop a distributed attack (a DDoS).
You need layers:
- a global limit on total traffic, backed by load shedding, so the system never accepts more than it can serve;
- a DDoS protection service at the edge, like Cloudflare or AWS Shield, that absorbs floods before they reach you;
- pattern detection: lots of new IPs hitting the same endpoint with the same user agent is suspicious;
- challenges (like a CAPTCHA) for traffic that looks automated.
Puzzle 3: the queue that never emptied
The queue grows by one message a second. That’s 3,600 an hour, 86,400 a day, 600,000 a week. Nothing looks wrong on any single day, and then memory runs out.
A queue smooths bursts. It can’t fix a system where work always arrives faster than it’s done. Fixes: a bounded queue, an alert on queue depth (and on the age of the oldest message), auto-scaling consumers, and shedding low-priority messages when the queue gets too deep.
Key takeaways
- Traffic control protects a system when there’s more traffic than capacity. Serving some users well beats serving everyone badly.
- Rate limiting rejects clients over their quota with
429. The token bucket is the usual choice. Limit by cost where you can. - Throttling slows requests instead of rejecting them. It’s best on the caller’s side.
- Backpressure lets a slow service tell its sender to slow down. Never buffer without a limit.
- Load shedding drops the least important work first, with
503, so critical requests still succeed. - Queues absorb bursts, but must be bounded and watched. And every client needs backoff with jitter, or your own limits can cause a retry storm.
That completes the Load, traffic & protection thread: spreading traffic, and controlling it when there’s too much. Next comes Part 9, asynchronous systems, starting with messaging: queues, pub/sub and streams.
Comments