Slow the producer when the consumer is behind
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.
Basic solution
Bound buffers and make the producer wait, drop, or sample when they fill (backpressure).
Bounded buffers passing the signal upstream
Each stage has a capacity. When the Kafka producer buffer fills, the gateway stops accepting at full rate and tells the driver app to send less often.
How it works
- Every buffer between a producer and a consumer gets a fixed capacity: an in-memory channel of 1,000 items, a thread pool queue of 100, a Kafka consumer prefetch of 500 records. Nothing is allowed to grow without limit.
- The consumer pulls items at its own rate. The buffer fills only when the producer is putting items in faster than the consumer takes them out.
- When the buffer is full, the producer gets a signal instead of a silent success: a blocking send that does not return, a rejected submit, an HTTP 429 from the server, or a TCP receive window of zero.
- The producer reacts to the signal in one of four ways: block, which slows its own upstream; drop the item and count the drop; sample, keeping one item in N; or degrade, such as sending coarser updates less often.
- The signal travels upstream hop by hop, each stage slowing or shedding, until it reaches something that can safely wait or discard, such as a client that can retry later or a phone that can send positions less often.
Pull beats push for backpressure
- A consumer that pulls when it is ready can never be overwhelmed, because it decides when to take the next item. A producer that pushes has no idea whether the consumer is keeping up unless there is explicit feedback telling it to stop.
Worked example
Driver location ingestion
- 1M drivers × 1 update per 4 s = 250K updates/s normal. A New Year surge plus a reconnect storm after a gateway restart produces 1.2M/s for two minutes.
- Driver gateway → Kafka: the producer buffer is 32 MB per gateway. At 100 B per update that is 320K updates before send blocks. With 50 gateways and Kafka accepting 400K/s, the buffers absorb the excess for (1.2M − 0.4M) / 50 = 16K updates/s per gateway, so 20 s until they fill.
- When full, the gateway returns 429 with a hint to the driver app: increase the update interval to 10 s. 1M drivers at one update per 10 s is 100K/s, well under capacity. Positions are slightly staler; matching still works.
- Without backpressure: an unbounded in-memory queue in each gateway grows at 16K/s × 100 B = 1.6 MB/s; a 2 GB heap is gone in 20 minutes and the gateway crashes, dropping every connected driver at once, which triggers the next reconnect storm.
- Consumer side: the location service reads with a prefetch of 1,000 per partition; consumer lag is the backpressure metric, alerting at 30 s.
Variants and when each wins
Blocking (wait)
- The producer stops until there is room in the buffer. It wins when nothing may be lost and the producer can afford to wait; it is dangerous when the producer is a request thread, because then the API itself stops answering.
Drop or reject
- The producer returns 429 or discards the item and increments a counter. It wins for data that goes stale on its own, such as positions, metrics and heartbeats, where a newer item will arrive soon anyway.
Sample or coalesce
- Keep one item in N, or keep only the latest value per key (conflate). It wins when the newest value supersedes the old one, as with driver locations: coalescing by driver id loses nothing useful.
Buffer to disk
- Spill the backlog to a local log file and drain it later. It wins for long bursts of data that must not be lost, at the cost of latency while draining and disk to hold the spill.
Protocol-level flow control (TCP windows, HTTP/2, Reactive Streams request(n))
- The consumer tells the producer how many items it can take, and the transport enforces it. It wins wherever the transport already provides it, because it is more reliable than anything you invent yourself.
Default to bounded buffers with blocking for must-not-lose data, and drop or coalesce for data that expires on its own.
Failure modes
Unbounded queue
- Memory climbs for twenty minutes, then the process dies. It happens because a queue with no capacity limit silently absorbed an overload until the heap ran out. Give every queue a capacity and alert when it is more than, say, 80% full.
Backpressure stops at the wrong layer
- The gateway blocks, every driver app times out, reconnects, and the surge gets worse. It happens because the signal stopped at the gateway and never reached the client as an instruction it could act on. Return 429 with a Retry-After or a suggested interval, and make clients honour it.
Slow consumer stalls the whole pipeline
- One slow analytics consumer makes the live location path lag. It happens because both consumers share one buffer or one consumer group, so the slow one holds back the fast one. Give each consumer its own buffer and consumer group, so the slow one lags alone.
Dropping the wrong items
- Trip-end events are lost while idle heartbeats get through. It happens because a single mixed queue drops the newest items when full, regardless of what they are. Separate queues by importance and drop only from the low-priority one.
No visibility
- Nobody knows backpressure is engaged until users complain. It happens because buffer occupancy and drop counts are not measured. Export fill percentage, time producers spent blocked, and drops per second, and alert on sustained values.
Interviewer follow-ups
Answer out loud before you open each one.
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.
What should a client do when it receives backpressure?
Slow down in a way that preserves the most valuable data: lengthen its interval, send only deltas, batch, and retry with backoff. The server should say how, for example a header with a suggested interval, rather than leaving the client to guess.
Where do you measure it?
Buffer occupancy at every bounded queue, time spent blocked by producers, items dropped, and consumer lag on logs. The first one to climb tells you which stage is the bottleneck.
Can Kafka give you backpressure?
Toward consumers, yes: they pull, so they are never overwhelmed, and lag shows how far behind they are. Toward producers, the client library blocks or errors when its buffer is full, which is the signal you then propagate to whatever is calling you.
Connections
- In study paths
- Staying up under load
- Built on
- Ring buffer
- Pairs with
- Drop load before you fall over · Admit only what you can finish · Decouple producer from consumer · Limit requests per client · Ingest millions of position updates
- Pulls against
- Keep events as a replayable log
- Used in
- Ride Matching (Uber / Lyft) · Notification System
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 EC2 Auto Scaling | Driver gateway, Location service | Compute Engine managed instance groups | Virtual Machine Scale Sets | Kubernetes Deployment with a HorizontalPodAutoscaler, Nomad |
| Amazon MSK (Kafka) | Kafka: locations | Managed Service for Apache Kafka | Event Hubs (Kafka API) | Confluent Cloud, Redpanda |