Prev Next

Integration / Backpressure in Distributed Systems Interview questions

Last updated

1. What is backpressure in distributed systems? 2. What problem does backpressure solve? 3. What are the common backpressure strategies? 4. What is a bounded queue? 5. What is graceful degradation? 6. What is bounded concurrency? 7. What is load shedding? 8. What is overload protection? 9. What is a bulkhead? 10. What is the purpose of a bounded thread pool queue? 11. What are the types of queue overflow policies? 12. What is the purpose of HTTP 429 and 503 with Retry-After? 13. Define credit-based flow control? 14. Describe how request(n) works in Reactive Streams? 15. What is the TCP receive window? 16. What is queue depth and why track it? 17. What is the purpose of a circuit breaker in overload protection? 18. What is deadline propagation? 19. What is admission control? 20. List the metrics that show a system is overloaded? 21. What is the difference between backpressure and rate limiting? 22. What is the difference between load shedding and backpressure? 23. Why are unbounded queues dangerous in production? 24. Why do we use bounded concurrency for downstream calls? 25. How do you size a bounded queue? 26. How does Little's Law help set concurrency limits? 27. When should you block versus reject on a full queue? 28. When would you choose drop-oldest over drop-newest? 29. What happens when a queue fills up and producers keep sending? 30. How does adaptive concurrency limiting work? 31. What is the difference between static and adaptive concurrency limits? 32. How do you implement priority-based load shedding? 33. Why should you shed load at the edge instead of deep in the stack? 34. How does CoDel manage queue delay? 35. Why is LIFO sometimes better than FIFO under overload? 36. What happens when retries amplify overload? 37. How do retry budgets prevent retry storms? 38. Why should clients use exponential backoff with jitter? 39. How do you apply backpressure in Kafka consumers? 40. How does HTTP/2 and gRPC flow control provide backpressure? 41. How do you propagate backpressure across microservices? 42. Explain the lifecycle of a request during overload with load shedding? 43. How does a circuit breaker differ from a bulkhead? 44. Why is p99 latency a better overload signal than CPU? 45. How can you optimize throughput under bounded concurrency? 46. How do you troubleshoot a growing queue with flat CPU? 47. What is a metastable failure in overloaded systems? 48. How do you test backpressure behavior before production? 49. Which is better for backpressure: pull-based or push-based consumers? 50. How would you design overload protection for a multi-tenant API?

1. What is backpressure in distributed systems?

Backpressure is a feedback mechanism where a slow or saturated consumer tells upstream producers to slow down, pause or stop, so work arrives no faster than it can be processed.

Without it, the surplus has to go somewhere. It piles up in queues, buffers and memory until something gives, usually latency first and then the process itself.

The signal can be explicit (a full bounded queue, a request(n) credit, an HTTP 429) or implicit (a shrinking TCP window, rising response time). The defining idea is that pressure travels backwards, against the direction of data flow.

Take quiz
In which direction does a backpressure signal travel?
From the producer forward to the consumer
From the database to the end user's browser only
From the consumer back toward the producer
What is the main goal of backpressure?
Keep the arrival rate of work close to what the consumer can actually process
Increase buffer size until nothing is ever rejected
Make producers emit faster than consumers can read

2. What problem does backpressure solve?

It solves the rate mismatch between a producer and a consumer. When work arrives faster than it is served, the gap has to be absorbed somewhere, and every place that absorbs it eventually fails.

The usual chain of events looks like this:

  1. Arrival rate exceeds service rate.
  2. Queues and buffers grow, so each request waits longer.
  3. Latency passes client timeouts, so clients retry and add even more load.
  4. Memory, threads or connections run out and the node crashes or stalls.
  5. Callers of that node now see failures and the problem spreads upstream.

Backpressure breaks the chain at step 2 by refusing to let the queue grow without limit.

Take quiz
A producer sends 5,000 msg/s to a consumer that handles 3,000 msg/s through an unbounded buffer. What happens first?
The buffer grows by about 2,000 messages every second and latency climbs
The consumer automatically speeds up to match
Excess messages are silently deduplicated
What is a typical end state of unmanaged overload?
Out-of-memory crashes or mass timeouts that cascade to callers
Lower CPU usage across the cluster
Shorter queue wait times for every request
A permanently empty queue

3. What are the common backpressure strategies?

There is no single technique. Most systems combine several, each acting at a different layer:

Strategy How it slows the producer Trade-off
Bounded queue Producer blocks or gets an error when the queue is full Simple, but capacity must be sized well
Credit-based / pull Consumer grants permits or asks for items when ready Needs protocol support on both sides
Throttling Caps the rate a client may send Fixed limit can be wrong when capacity changes
Load shedding Rejects excess work early Some requests fail on purpose
Adaptive concurrency Limit rises and falls with observed latency More moving parts to tune and monitor

Take quiz
Which strategy lets the consumer state exactly how many items it can accept next?
Drop-oldest eviction
Credit-based flow control
Random early shedding
Which approach deliberately gives up some requests to protect the latency of the rest?
Blocking producers indefinitely
Load shedding
Growing the buffer without a limit
Retrying every failed call immediately

4. What is a bounded queue?

A bounded queue has a fixed maximum capacity. Once it is full, a new item cannot just be appended, so the producer has to wait, fail fast, or wait for a limited time.

That capacity is the backpressure threshold. It also caps waiting time: if workers drain 400 items per second and the queue holds 100, nobody waits much longer than 250 ms.

BlockingQueue<Task> queue = new ArrayBlockingQueue<>(100);

if (!queue.offer(task)) {
    // queue is full: reject, shed or ask the caller to retry later
    throw new RejectedExecutionException("queue full");
}

put() blocks, offer(item) returns false immediately, and offer(item, timeout, unit) waits up to a deadline.

Whichever call you pick, count the rejections. A steady stream of full-queue events is the earliest sign that capacity or the arrival rate needs attention.

Take quiz
What does offer(task) return on a full ArrayBlockingQueue?
It blocks until space is free
false, without blocking the caller
It silently overwrites the oldest element
It throws an OutOfMemoryError
Why does a bounded queue help latency?
Maximum wait time is limited by capacity divided by the service rate
It makes each individual task run faster
It removes the need for any consumers

5. What is graceful degradation?

Graceful degradation means a system keeps serving a reduced but useful response under stress instead of failing outright. It is the softer partner of load shedding.

Typical moves when load is high:

  • Skip optional work such as recommendations or personalization.
  • Serve cached or slightly stale data.
  • Return fewer results per page or lower-resolution media.
  • Turn off expensive features behind a flag.

The trigger is usually a load signal like in-flight count or queue age, so the switch happens before the node falls over. The goal is that the core user journey, such as checkout, still works.

Take quiz
A product page skips recommendations when the service is overloaded. This is an example of:
Graceful degradation
A cache stampede
Head-of-line blocking
What usually triggers a degraded mode?
The calendar date changing
A new deployment finishing
A user clearing their cookies
A load signal such as queue age or in-flight request count

6. What is bounded concurrency?

Bounded concurrency caps the number of operations that may be in flight at once against a resource, for example 20 simultaneous calls to a payment service. Extra callers wait briefly or get rejected.

It is typically built with a semaphore, a fixed-size worker pool, or a connection pool. Without a cap, a slow dependency lets requests pile up until threads or sockets run out.

Semaphore permits = new Semaphore(20);

if (!permits.tryAcquire(50, TimeUnit.MILLISECONDS)) {
    return Response.status(503).build();   // fail fast
}
try {
    return callDownstream();
} finally {
    permits.release();
}

Note the short wait on tryAcquire. Waiting forever just moves the queue into your threads.

Take quiz
What does a semaphore with 20 permits enforce?
At most 20 requests per second
At most 20 operations running at the same time
At most 20 retries per request
Why use tryAcquire with a short timeout instead of acquire ?
So callers fail fast instead of piling up behind the limit
So permits are never released
So the downstream call runs twice as fast
So the limit becomes unlimited

7. What is load shedding?

Load shedding is the deliberate rejection of some incoming work when demand exceeds capacity, so the requests you do accept still finish within an acceptable time.

The point is goodput, not throughput. A node that tries to serve everything can end up completing almost nothing on time. A node that rejects 20% quickly can serve the other 80% well.

What to shed is a policy choice: the newest arrivals, requests that already waited too long, low-priority traffic, or a single noisy tenant. The rejection should be cheap and fast, typically an HTTP 503 or 429 returned before any heavy work starts.

Take quiz
What is the main benefit of load shedding?
Every request is guaranteed to succeed
The system never needs monitoring
Accepted requests still complete within acceptable latency
Where should a shed decision ideally be made?
After the database query has finished
As early as possible, before expensive processing begins
Only after the response is serialized
Only inside the client's retry loop

8. What is overload protection?

Overload protection is the set of controls that keep a service healthy when demand exceeds capacity. It is not one feature but layers, from the edge down to each dependency call.

  1. Admission control at the edge: rate limits and in-flight caps.
  2. Bounded queues so waiting time has a ceiling.
  3. Concurrency limits per dependency.
  4. Timeouts and deadlines so abandoned work stops.
  5. Circuit breakers to stop calling a failing dependency.
  6. Load shedding and degradation as the last resort.

Autoscaling helps with sustained growth, but it reacts in minutes. These controls act in milliseconds.

Take quiz
Why is autoscaling alone not enough for overload protection?
It reacts in minutes, while overload builds in seconds or less
It always scales the wrong service
It cannot add more instances
Which of these is an overload protection control?
Increasing log verbosity
Disabling all timeouts
A per-dependency concurrency limit
Making the request queue unbounded

9. What is a bulkhead?

A bulkhead isolates resources into separate compartments, named after the watertight sections of a ship. A leak in one compartment does not sink the whole vessel.

In services this usually means separate thread pools, connection pools or semaphores per dependency or per tenant. If the recommendation service hangs, it can exhaust only its own 10 slots instead of every worker thread.

Pool Slots
payments 20
search 30
recommendations 10

The cost is some unused capacity, since one pool cannot borrow from another. That is usually a fair price for containing a failure.

Take quiz
What does a bulkhead protect against?
Network packets arriving out of order
One slow dependency consuming all shared threads or connections
Expired TLS certificates
What is the main cost of bulkheads?
Requests become unordered
Every call must be retried three times
They require a distributed lock
Idle capacity in one pool cannot be borrowed by another

10. What is the purpose of a bounded thread pool queue?

It decides how much work may wait before the pool pushes back. Core threads take work first, extra tasks go to the queue, and only a full queue triggers extra threads up to the maximum, then rejection.

new ThreadPoolExecutor(
    8, 16, 60, TimeUnit.SECONDS,
    new ArrayBlockingQueue<>(200),
    new ThreadPoolExecutor.CallerRunsPolicy());

Here the pool handles 8 tasks, queues 200, grows to 16 threads, and after that the calling thread runs the task itself. CallerRunsPolicy is a natural brake because the producer is busy and cannot submit more.

A common trap is Executors.newFixedThreadPool, which uses an unbounded queue. The maximum pool size is never reached and overload becomes silent memory growth.

Take quiz
In a ThreadPoolExecutor, when are threads above the core size created?
As soon as the first task arrives
Whenever the CPU drops below 50%
Only after the work queue is full
Why is CallerRunsPolicy a form of backpressure?
The submitting thread is busy running the task, so it submits less
It discards the oldest task silently
It doubles the queue size
It retries the task on another JVM

11. What are the types of queue overflow policies?

When a bounded queue is full, the overflow policy decides who pays. The common options:

  • Block - the producer waits until space frees up. Pushes pressure upstream.
  • Block with timeout - wait briefly, then fail. Avoids unbounded waiting.
  • Reject - throw or return an error immediately.
  • Drop newest (tail drop) - discard the incoming item.
  • Drop oldest - evict the head to make room for fresh data.
  • Caller runs - the producer does the work itself.
  • Spill to disk - overflow to durable storage, trading latency for capacity.

The right choice depends on whether the data is transactional, replaceable or time-sensitive.

Take quiz
Which overflow policy evicts the head of the queue to make room for the new item?
Drop oldest
Drop newest
Caller runs
Block with timeout
Which policy makes the producer do the work itself?
Spill to disk
Caller runs
Tail drop

12. What is the purpose of HTTP 429 and 503 with Retry-After?

They are the explicit rejection signals of HTTP. 429 Too Many Requests says this caller is sending too much. 503 Service Unavailable says the server cannot take the request right now, regardless of who sent it.

Retry-After tells the client when to try again, either as seconds or as a date. That turns a rejection into a usable backpressure signal.

HTTP/1.1 503 Service Unavailable
Retry-After: 5
Content-Type: application/json

Clients should honor the header and add jitter so a thousand of them do not return at the same second. The server should send the response fast, ideally before parsing the body.

Take quiz
Which status code means this particular client is exceeding its allowance?
404 Not Found
429 Too Many Requests
301 Moved Permanently
What does Retry-After communicate?
Which server replica to use next
The size of the request body allowed
How long the client should wait before trying again
The TLS version to negotiate

13. Define credit-based flow control?

In credit-based flow control the receiver grants permits and the sender may transmit only as many items as it holds credits. Each send spends a credit. No credit means no send.

Because credits come from the consumer, the sender can never outrun the receiver's buffer. The pattern shows up in Reactive Streams request(n), HTTP/2 WINDOW_UPDATE frames and RabbitMQ prefetch counts.

The receiver controls throughput by how quickly it hands credits back, usually as it finishes work. A slow consumer simply issues fewer credits, which is backpressure with no guessing involved.

Take quiz
In credit-based flow control, who decides how much the sender may send?
The sender, based on its own CPU load
The load balancer, using round robin
The receiver, by granting credits
What happens when a sender has zero credits?
It sends anyway and relies on retries
It doubles its send rate
It deletes its local buffer
It must wait until the receiver grants more

14. Describe how request(n) works in Reactive Streams?

In Reactive Streams the subscriber pulls data by calling request(n) on its Subscription. The publisher may emit at most n items through onNext and must then wait for more demand.

Flux.range(1, 1000)
    .subscribe(new BaseSubscriber<Integer>() {
        @Override protected void hookOnSubscribe(Subscription s) {
            request(10);                 // initial demand
        }
        @Override protected void hookOnNext(Integer v) {
            process(v);
            request(1);                  // ask for one more when done
        }
    });

The contract has three parts. A Publisher produces items, a Subscriber consumes them, and the Subscription links the two and carries demand and cancellation. The publisher must never emit more than the outstanding demand, so a slow subscriber simply requests less and upstream slows down with no extra code.

Demand is cumulative. Calling request(Long.MAX_VALUE) means unbounded demand, which disables backpressure, so treat it with care. Operators such as limitRate and onBackpressureBuffer in Reactor adjust how demand is batched or what happens when it is exceeded.

Take quiz
What does request(5) allow the publisher to do?
Emit up to 5 more items
Emit exactly one item per second
Cancel the subscription
What does request(Long.MAX_VALUE) effectively signal?
Unbounded demand, so backpressure is switched off
Demand for zero more items
A request to reduce the buffer size
A request to retry from the beginning

15. What is the TCP receive window?

The TCP receive window is the amount of data a receiver says it can still buffer. It is carried in every ACK, and the sender may have no more unacknowledged bytes in flight than that window.

If the application stops reading from the socket, the kernel buffer fills and the advertised window shrinks. At zero the sender pauses and probes occasionally. That is backpressure built into the transport, with no application code involved.

It has limits. The window counts bytes per connection, not units of work, so a server can happily accept bytes and still be hopelessly behind on processing them. Application-level limits are still needed.

Take quiz
What happens when a TCP receiver advertises a window of zero?
The sender doubles its rate
The sender stops transmitting new data until the window reopens
The connection is closed immediately
Why is the TCP window not enough for overload protection by itself?
It only works on UDP
It measures buffered bytes, not how much real work is pending
It cannot be changed at runtime
It is disabled when TLS is used

16. What is queue depth and why track it?

Queue depth is the number of items waiting to be processed. It is the most direct picture of how far behind a consumer is.

Depth alone can mislead. A thousand items drain in 100 ms at 10,000 per second but take 20 seconds at 50 per second. Pair it with queue age, the time the oldest item has been waiting, which maps straight to what users feel.

Alert on sustained growth rather than a momentary spike, because healthy queues absorb bursts by design. A queue that never reaches zero over several minutes is a standing queue and a sign of real overload.

Take quiz
Why is queue age often more useful than queue depth alone?
It uses less memory to compute
It is always smaller than depth
It reflects actual waiting time regardless of drain speed
Which pattern suggests real overload rather than a healthy burst?
A queue that briefly hits 50 items then empties
A queue that is empty at night
A queue that never drains back to zero
A queue with exactly one consumer

17. What is the purpose of a circuit breaker in overload protection?

A circuit breaker stops calls to a dependency that is failing or too slow, giving it room to recover and keeping callers from wasting threads on hopeless requests.

It has three states:

  1. Closed - calls pass through while failures are counted.
  2. Open - the failure or slow-call rate crossed a threshold, so calls fail immediately.
  3. Half-open - after a cool-down, a few trial calls test whether the dependency has recovered.

It complements concurrency limits. A limit caps how many calls are in flight, while a breaker removes the calls entirely during a known bad period.

Take quiz
What does an open circuit breaker do with new calls?
Fails them immediately without calling the dependency
Queues them for a later retry forever
Sends them twice for safety
What is the half-open state for?
Permanently disabling the dependency
Doubling the timeout
Switching to a different region
Testing with a few trial calls whether the dependency has recovered

18. What is deadline propagation?

Deadline propagation passes the remaining time budget along every hop of a request, so downstream services know when the caller will have given up and can stop working on it.

A client sets a 2-second deadline. The gateway spends 150 ms and forwards 1.85 seconds. Each service subtracts its own time. If a request reaches a worker with no time left, or sits in a queue until its deadline passes, it is dropped instead of processed.

gRPC carries this natively through its deadline mechanism. In plain HTTP it is usually a custom header. Without it, services keep doing work whose answer nobody is waiting for, which wastes exactly the capacity you are short of during overload.

Take quiz
What does deadline propagation let a downstream service do?
Extend the caller's timeout automatically
Skip work whose caller has already given up
Retry the request on the client's behalf
What should happen to a queued request whose deadline has already passed?
It should be dropped when dequeued
It should be processed first
It should be duplicated in another queue
It should be given a fresh deadline

19. What is admission control?

Admission control decides, at the entrance, whether a request is accepted, before any real resources are spent on it. It answers a yes or no question based on current load.

Common mechanisms are a cap on in-flight requests, a token bucket, a latency-based limit and a cost-based limit where a heavy query counts as more than a light one. Rejected requests get a quick 429 or 503.

The aim is that every admitted request can finish within its target time. A queue only delays the decision, while admission control makes it up front, which is why it works better when the right answer is often no.

Take quiz
When does admission control make its decision?
After the response is fully written
Only during nightly maintenance
Before significant resources are spent on the request
What is the goal for requests that are admitted?
They should wait in a queue as long as needed
They should finish within their target latency
They should be retried at least twice
They should be encrypted twice

20. List the metrics that show a system is overloaded?

No single number is enough. Watch these together:

  • In-flight requests vs limit - how close you are to the cap.
  • Queue wait time - how long admitted work sits before starting.
  • p95 / p99 latency of successful requests.
  • Rejection or shed rate - how often protection is kicking in.
  • Retry rate - extra load created by clients.
  • Pool saturation - threads, connections, file descriptors.
  • GC pause time and memory growth - frequent early signs on the JVM.

A rising rejection rate with stable p99 means protection is working. A rising p99 with no rejections means it is not.

Take quiz
Rising rejections with a flat p99 for admitted requests most likely means:
The system has silently failed
Protection is working and latency of served requests is held
The queue is unbounded
The clients are not retrying
Which metric shows load that clients are generating on top of the original traffic?
Disk free space
Number of deployments
Retry rate
Build duration

21. What is the difference between backpressure and rate limiting?

Both reduce load, but they react to different things. Rate limiting enforces a preset policy per client. Backpressure reacts to the actual state of the consumer right now.

Aspect Rate limiting Backpressure
Trigger Configured quota, e.g. 100 req/s per key Real consumer state: full queue, no credits, high latency
Scope Usually per client or tenant Whole path from consumer back to producer
Adapts to capacity? No, unless the limit is changed Yes, automatically
Typical response 429 Too Many Requests Block, pause, reject or slow down

A client can stay under its rate limit and still overload a server that is slow today. Real systems use both: rate limits for fairness and abuse, backpressure for protection.

Take quiz
A client is within its quota, but the server's queue is full. Which mechanism reacts to the full queue?
Rate limiting
Backpressure
DNS caching
What mainly drives a rate limiter's decision?
The current length of the consumer's queue
The size of the response body
The server's disk usage
A preconfigured quota per client

22. What is the difference between load shedding and backpressure?

Backpressure asks producers to slow down. Load shedding drops work on the server side. They solve the same problem for different kinds of senders.

Backpressure only works when the sender cooperates and can wait: an internal worker, a stream publisher, a well-behaved client. Public internet users cannot be told to pause, and a flood of them will not slow because a header asked nicely.

  • Backpressure - nothing is lost, the producer waits or retries later.
  • Shedding - some requests are refused and are gone unless the client retries.

Typical layering is backpressure between internal components and shedding at the boundary facing untrusted traffic.

Take quiz
Which technique works even when the sender will not cooperate?
Credit-based flow control
Reactive Streams demand
Load shedding
In pure backpressure, what happens to the work that cannot be accepted yet?
The producer holds it and waits or retries later
It is permanently deleted by the server
It is sent to a random other service

23. Why are unbounded queues dangerous in production?

An unbounded queue does not remove overload. It hides it until the process dies, and it makes recovery slow.

  1. Memory grows with no limit, ending in an out-of-memory crash.
  2. Latency grows with queue length, so users wait minutes for answers they no longer need.
  3. Stale work is processed, wasting capacity on requests whose callers have timed out.
  4. No early warning - there are no errors until the crash.
  5. Recovery is slow, because the backlog drains only at spare capacity.

Example: arrivals of 3,000/s against 2,000/s capacity for 10 minutes leaves a 600,000 item backlog. If traffic then falls to 1,500/s, spare capacity is 500/s and the drain takes 20 minutes, long after the spike ended.

Take quiz
Arrivals fall to 1,500/s and capacity is 2,000/s with a backlog of 600,000. About how long to drain?
About 20 minutes
About 30 seconds
About 5 hours
It never drains
What is a key reason unbounded queues are risky?
They make consumers faster
They hide overload until memory runs out
They guarantee message ordering across restarts

24. Why do we use bounded concurrency for downstream calls?

A slow dependency is more dangerous than a dead one, because calls to it hold threads and connections for a long time. A cap stops that from spreading into your own service.

Take a dependency that stalls until a 30-second timeout while you receive 100 requests per second. Within a short time you hold 3,000 waiting calls. Threads, sockets and memory are gone, and healthy endpoints that never touch that dependency stop responding too.

With a limit of, say, 30 concurrent calls, the 31st gets an immediate error or a fallback. Your service stays alive, other endpoints keep working, and the dependency sees bounded pressure instead of a pile-on while it tries to recover.

Take quiz
A dependency stalls for 30 s while you get 100 req/s with no cap. Roughly how many calls are waiting?
About 30
About 3,000
About 100
None, they are dropped by TCP
What does a concurrency limit give healthy endpoints?
They automatically get faster hardware
They are routed to a different database
They keep working because the slow dependency cannot take every thread

25. How do you size a bounded queue?

Start from the wait time you can tolerate, not from a round number. A queue longer than that only holds requests that will time out anyway.

queue_size ~= service_rate x max_acceptable_wait

8 workers x (1 / 0.020 s) = 400 req/s
400 req/s x 0.25 s        = 100 slots

Then adjust for the real system. Bursts you want to absorb push the number up. A tight latency target or a client timeout shorter than the computed wait pushes it down.

Check the result in a load test: at 2x capacity, the wait of admitted requests should stay near your target and the excess should be rejected quickly. Keep the queue small. For overload, a short queue is almost always better than a long one.

Take quiz
Workers handle 400 req/s and the maximum acceptable wait is 250 ms. A reasonable queue size is about:
10,000
1
100
400,000
What should drive queue size most directly?
The amount of free RAM on the host
The number of developers on the team
The size of the largest request
The waiting time clients can tolerate

26. How does Little's Law help set concurrency limits?

Little's Law states L = lambda x W: the average number of requests in the system equals arrival rate times time spent in the system. It links throughput, latency and concurrency.

To serve 500 req/s at 80 ms latency you need about 500 x 0.08 = 40 requests in flight. Add some headroom and 50 is a sensible limit.

It also shows what happens when latency degrades. If the dependency slows to 400 ms and your limit stays at 50, the most you can complete is 50 / 0.4 = 125 req/s. The rest must be rejected or they pile up as waiting time. That is the reason a fixed limit protects the service so well: the in-flight count simply cannot exceed it.

Take quiz
A service must handle 500 req/s with 80 ms latency. About how many requests are in flight?
About 4
About 400
About 6,250
About 40
With a limit of 50 and latency rising to 400 ms, the maximum throughput becomes about:
125 req/s
500 req/s
20 req/s
2,000 req/s

27. When should you block versus reject on a full queue?

Block when the producer can afford to wait and nobody is watching a clock. Reject when a caller is waiting and a fast error is more useful than a slow answer.

flowchart TD
  A["Queue is full"] --> B{Is a user or client waiting on the response?}
  B -- Yes --> C["Reject fast: 429 or 503"]
  B -- No --> D{Can the data be replaced by newer data?}
  D -- Yes --> E["Drop oldest or newest"]
  D -- No --> F["Block with a timeout"]

Batch jobs and internal pipelines are good candidates for blocking, since a slower job costs nothing. A web handler that blocks for 30 seconds just holds a thread for a client that has already left.

Whichever you choose, put a timeout on any blocking. An unbounded wait just relocates the queue into your threads.

There is a middle path for flows that must not lose data but cannot wait long: reject the request with a clear retry hint and let the caller hold the work. That keeps the data safe in the producer, where it belongs, instead of in a queue that is already overloaded.

Take quiz
An interactive API request finds the queue full. The best default is to:
Block the thread indefinitely
Reject fast so the caller can retry or fall back
Silently drop the request without telling the caller
A nightly batch loader hits a full queue. What is a sensible policy?
Return a 503 and abandon the whole job
Block with a timeout so the pipeline simply runs slower
Delete the oldest completed rows
Restart the cluster

28. When would you choose drop-oldest over drop-newest?

Choose drop-oldest when the freshest value matters most and old items lose their meaning. Choose drop-newest when earlier items must be preserved or when you want to protect work already queued.

  • Drop-oldest - sensor positions, UI state updates, live metrics, price ticks. A newer reading replaces an older one anyway.
  • Drop-newest (tail drop) - ordered event logs, or jobs where earlier items have dependencies. Also the simplest to implement and fair to those already waiting.
  • Neither - payments and orders, where losing any item is not acceptable. Reject with an error instead so the caller knows.

Dropping silently is the risk. Count every drop in a metric, otherwise data loss is invisible.

Take quiz
Which workload suits drop-oldest?
Bank transfers
Live price ticks where only the latest value matters
Ordered audit logs
Payment confirmations
What should you always do when dropping items?
Hide them from monitoring
Retry them forever
Count the drops in a metric
Rename them as successes

29. What happens when a queue fills up and producers keep sending?

It depends entirely on the overflow policy, and that is the point of choosing one on purpose.

  • Blocking - producer threads stall. If the producer is itself a consumer of another queue, that queue fills next, and the pressure moves upstream hop by hop. This is backpressure working.
  • Rejecting - callers receive errors. If they retry immediately, they add more load, so they must back off.
  • Dropping - data is lost, silently unless counted.
  • Unbounded - there is no full state, so memory just keeps growing until the process dies.

A full bounded queue is not a failure. It is the system telling you that the incoming rate exceeds the outgoing rate. The failure is when nothing upstream is built to understand that message.

Take quiz
In a chain of blocking queues, what happens when the last queue is full?
Pressure moves upstream as each earlier stage fills in turn
All earlier queues are emptied automatically
Messages are duplicated to avoid loss
Why must clients back off when they receive rejections?
Rejections only occur on the first request
Retries are always free
Backoff makes the server faster
Immediate retries add even more load to an overloaded system

30. How does adaptive concurrency limiting work?

Instead of a hand-picked number, the limit moves with the observed health of the dependency. It rises while latency stays near its baseline and drops when latency, timeouts or rejections climb.

Many implementations borrow from TCP congestion control and use AIMD: additive increase, multiplicative decrease.

  1. Track the minimum or typical latency as the no-queue baseline.
  2. On each healthy response, raise the limit slowly, for example by 1.
  3. When latency exceeds the baseline by a set ratio, or a call times out, cut the limit by a factor such as 0.9 or 0.5.
  4. Reject callers when in-flight count reaches the current limit.

Netflix's open-source concurrency-limits library, with its Vegas and Gradient algorithms, popularized this in the JVM world. The benefit is that the limit finds real capacity by itself as hardware, data size or dependencies change. The cost is another feedback loop that needs good metrics and testing.

Take quiz
What does AIMD stand for?
Automatic index, manual deployment
Adaptive isolation of memory data
Asynchronous input, multiplexed delivery
Additive increase, multiplicative decrease
What typically causes an adaptive limit to shrink?
Rising latency or timeouts compared with the baseline
A successful health check
More available disk space
A faster CPU clock

31. What is the difference between static and adaptive concurrency limits?

Aspect Static limit Adaptive limit
Value Fixed number chosen by an engineer Computed continuously from latency and errors
Setup effort Low: one config value Higher: algorithm, metrics, tuning
When capacity changes Goes stale and needs manual retuning Follows the change automatically
Predictability Very predictable Harder to reason about
Best for Stable dependencies with known capacity Shared or elastic dependencies, mixed workloads

A static limit set from a load test is a fine starting point and easy to explain in an incident. It starts to fail when the world drifts: a new dependency version, a bigger dataset, a noisy neighbor on the same host.

Many teams start static, add alerts on rejection rate, and move to adaptive only where retuning keeps hurting.

Take quiz
Which limit type follows capacity changes without manual retuning?
Static
Neither can follow changes
Adaptive
A stable dependency has well-known capacity. What is a sensible choice?
Removing the limit entirely
A static limit derived from a load test
A random limit changed each hour
An unbounded thread pool

32. How do you implement priority-based load shedding?

Classify every request by importance, then give each class its own shed threshold. Less important traffic is refused first as load rises.

  1. Classify at the edge, for example critical (checkout, health checks), normal, best-effort (prefetch, analytics).
  2. Propagate the priority in a header so inner services apply the same decision.
  3. Compare current load with a threshold per class.
int load = inFlight.get() * 100 / maxInFlight;

if (priority == BEST_EFFORT && load > 70) return reject();
if (priority == NORMAL      && load > 85) return reject();
if (load >= 100)                          return reject();

Keep the number of classes small, three or four. Do not let clients choose their own priority without checks, because every client will say critical. Track shed counts per class to confirm that best-effort really goes first.

Thresholds should leave real headroom for the top class. If critical traffic is only allowed in above 99% load, a sudden burst of it can still arrive faster than the check can react, so many teams reserve a slice of capacity for it.

Take quiz
In priority-based shedding, which traffic is refused first as load rises?
The lowest-priority class
The highest-priority class
Whichever request arrived most recently, ignoring class
Why is it risky to let clients set their own priority freely?
It makes requests larger
It disables TLS
Every client may claim critical and defeat the scheme
It breaks HTTP caching

33. Why should you shed load at the edge instead of deep in the stack?

The earlier you refuse a request, the less you have spent on it. A rejection at the gateway costs microseconds. The same rejection after authentication, parsing, a cache lookup and a database call wastes all of that work.

Deep rejection also hurts twice. The inner service is already saturated, so even telling the caller no takes time, and every upstream hop has already done its share of the work.

There is a trade-off. The edge usually does not know how loaded an inner service is. So combine both: coarse admission control and per-client limits at the edge, and local concurrency limits plus a fast reject signal propagated outward from each inner service. The edge then learns from those signals, and shedding moves toward where the load enters.

Take quiz
Why is rejecting at the edge cheaper than rejecting deep in the stack?
Edge servers have infinite capacity
Deep services cannot send errors
Less work has been spent on the request by that point
The edge has more RAM per request
What limitation does edge-only shedding have?
It can only reject POST requests
It cannot use HTTP status codes
It requires a database transaction
The edge may not know how loaded an inner service is

34. How does CoDel manage queue delay?

CoDel (Controlled Delay) is a queue management algorithm from networking that watches how long items sit in the queue, called sojourn time, instead of how many are in it.

A burst can create a long queue that clears quickly, and that is harmless. A standing queue, where delay stays high for a while, is the real problem. CoDel's rule: if the minimum sojourn time stays above a small target (5 ms in the original design) for a full interval (100 ms), start dropping, and drop more often the longer it persists.

The idea transfers to services. Instead of fixing a queue length, set a target wait such as 50 ms and drop or reject requests whose wait exceeds it for a sustained period. That lets short bursts through and acts only when the queue is no longer draining.

Take quiz
What does CoDel measure?
The number of items in the queue
The CPU temperature of the host
How long items wait in the queue
Which situation does CoDel treat as harmful?
A standing queue where delay stays high for a sustained interval
A short burst that clears quickly
An empty queue
A queue with one item

35. Why is LIFO sometimes better than FIFO under overload?

Under heavy load, a FIFO queue serves the oldest requests first, which are the ones most likely to have already timed out on the client. You spend scarce capacity producing answers nobody will read.

A LIFO queue serves the newest requests first, whose callers are still waiting. Fewer requests are completed late, and the ones you do finish are useful.

The cost is fairness: the oldest requests may starve. Some large services therefore use adaptive LIFO, which stays FIFO while the queue is short and switches to LIFO only when a backlog builds. Pair it with an age limit so requests older than their deadline are discarded rather than starved forever.

Take quiz
Under overload, why can LIFO yield more useful responses than FIFO?
It serves requests whose callers are probably still waiting
It processes requests in a random order
It makes each request run faster
It increases queue capacity
What is the main downside of LIFO?
It uses more memory than FIFO
The oldest requests can starve
It prevents any ordering from ever being used
It requires a distributed lock

36. What happens when retries amplify overload?

Retries multiply traffic exactly when the system can least afford it. This is a retry storm, and it often turns a brief slowdown into a long outage.

The multiplication compounds across layers. If a client, a gateway and a service each make up to 3 attempts, one user action can generate 3 x 3 x 3 = 27 calls against the database at the bottom.

  1. A dependency slows down and some calls time out.
  2. Callers retry, so offered load goes up while capacity stays flat.
  3. More calls time out, which triggers more retries.
  4. The loop sustains itself even after the original trigger is gone.

Fixes: retry at one layer only, use exponential backoff with jitter, cap retries with a budget, and honor Retry-After. Shedding must also be fast, because a slow rejection just invites another attempt.

Take quiz
Three layers each try up to 3 attempts. How many calls can reach the bottom service per user action?
9
27
6
3
Which change best reduces retry amplification across a call chain?
Retrying at every layer with no delay
Increasing every timeout to 10 minutes
Retrying at only one layer
Removing all error handling

37. How do retry budgets prevent retry storms?

A retry budget limits retries to a fraction of normal traffic, for example 10% of requests over a rolling window. When the budget is spent, failures are returned instead of retried.

It is more effective than a per-request cap. With a cap of 3 attempts, a total outage still triples your traffic. With a 10% budget, it rises by at most about 10%, however bad the failure is.

// token bucket: each success adds 0.1 token, each retry costs 1
if (failed && retryTokens >= 1) {
    retryTokens -= 1;
    retry();
} else {
    return error();      // budget exhausted, do not retry
}

gRPC's retry throttling and Envoy's retry budget work on this idea. During a real outage the budget runs dry within seconds, which is exactly what you want.

The budget is tracked per client process or per upstream cluster, and it refills as normal requests succeed. That means a healthy system can still retry the occasional transient failure, while a failing one cannot be hammered by its own callers.

Take quiz
A 10% retry budget during a total outage increases traffic by roughly:
200%
At least 300%
At most about 10%
Exactly zero, no matter what
What happens once the retry budget is exhausted?
Retries continue with no delay
The service restarts automatically
The budget is doubled
Failures are returned to the caller instead of retried

38. Why should clients use exponential backoff with jitter?

Exponential backoff spaces retries further apart on each attempt, giving a struggling server time to recover. Jitter adds randomness so clients do not all come back at the same instant.

Backoff alone is not enough. A thousand clients that failed together will also retry together at 1 s, 2 s, 4 s, producing synchronized waves. Random delay spreads those waves out into a roughly steady stream.

delay = random(0, min(cap, base * 2 ** attempt))   # full jitter
sleep(delay)

Full jitter, a random value between zero and the exponential ceiling, generally spreads load best. Always set a maximum delay and a maximum number of attempts, and respect Retry-After when the server sends it.

Only retry operations that are safe to repeat. Idempotent reads and writes carrying an idempotency key are fine. Blindly retrying a non-idempotent payment can turn a slow response into a double charge.

Take quiz
What problem does jitter solve?
Slow DNS lookups
Expired passwords
Large response payloads
Many clients retrying at the same moments in synchronized waves
In the full jitter formula, the delay is chosen as:
A random value between 0 and the exponential ceiling
Always exactly the ceiling
Always zero
The previous delay minus one

39. How do you apply backpressure in Kafka consumers?

Kafka consumers already pull records, so the broker keeps the backlog durably and the consumer decides how fast to read. Backpressure is about keeping the consumer's own memory and processing queue bounded.

  • max.poll.records limits how many records one poll() returns.
  • Processing hands records to a bounded internal queue or worker pool.
  • pause() stops fetching from assigned partitions when that queue is nearly full, and resume() restarts it.
if (workQueue.size() > HIGH_WATER) {
    consumer.pause(consumer.assignment());
}
if (workQueue.size() < LOW_WATER) {
    consumer.resume(consumer.paused());
}
consumer.poll(Duration.ofMillis(100));   // keep polling to stay in the group

Choose the high and low water marks with a gap between them. Pausing at 800 and resuming at 200, for example, avoids flapping between the two states on every record, and sizes the internal queue to what the workers can finish within the poll interval.

Keep calling poll() even while paused. If you stop for longer than max.poll.interval.ms, the consumer is considered dead and a rebalance starts. Rising consumer lag is then the visible symptom that you need more consumers or faster processing, not a failure.

Take quiz
What does consumer.pause() do in Kafka?
Stops fetching records for the given partitions while the consumer stays in the group
Deletes the partitions
Leaves the consumer group permanently
Doubles the poll size
Why keep calling poll() while paused?
To fetch more records than allowed
To avoid exceeding max.poll.interval.ms and triggering a rebalance
To commit offsets automatically to zero
To disable backpressure

40. How does HTTP/2 and gRPC flow control provide backpressure?

HTTP/2 has built-in window-based flow control at two levels: each stream and the whole connection. A receiver advertises how many bytes it will accept, and the sender cannot exceed that.

As the application reads data, the receiver sends WINDOW_UPDATE frames to give credit back. If the application reads slowly, it stops sending updates, the window reaches zero, and the sender must pause. gRPC exposes this to code through readiness callbacks such as isReady() and onReady() for streaming calls.

  • Stream window - protects one call's buffer.
  • Connection window - protects the total across all streams.
  • MAX_CONCURRENT_STREAMS - caps parallel calls per connection.

As with TCP, windows count bytes, not work. A server can accept a small message and still need a second to process it, so concurrency and queue limits are still required at the application level.

Take quiz
What do HTTP/2 WINDOW_UPDATE frames do?
Close the connection
Give the sender more credit to transmit data
Encrypt the stream
Reset the server's queue
What does MAX_CONCURRENT_STREAMS limit?
The size of each response body
The number of servers in a cluster
How many streams can be open in parallel on one connection
The TLS key length

41. How do you propagate backpressure across microservices?

Each hop needs its own local limit and a way to pass a refusal backward. Pressure then moves from the slowest component step by step toward the edge.

flowchart LR
  C[Client] --> G["Gateway: admission control"]
  G --> S["Service: concurrency limit"]
  S --> Q["Bounded queue"]
  Q --> W[Workers]
  W --> D[(Database)]
  D -. slow .-> W
  W -. queue fills .-> Q
  Q -. reject .-> S
  S -. 503 + Retry-After .-> G
  G -. 429 or shed .-> C
  1. Give every service a bounded queue and an in-flight cap.
  2. Return a fast 503 or 429 with Retry-After when either is full.
  3. Make callers treat that response as a signal, backing off or tripping a breaker instead of retrying blindly.
  4. Pass deadlines so waiting work is dropped when it expires.
  5. For asynchronous paths, let consumers pause or stop granting credit so the broker holds the backlog.

The weak link is any hop that buffers without limit or retries without a budget. One such hop absorbs the signal and the pressure never reaches the producer.

Take quiz
What breaks the propagation of backpressure along a call chain?
A hop with a bounded queue
A hop that returns 503 quickly
A hop with an unbounded buffer or unlimited retries
A hop that propagates deadlines
What should a caller do on receiving a 503 with Retry-After?
Retry immediately in a tight loop
Duplicate the request to every replica
Increase its own queue size to infinity
Back off and retry later, or use a fallback

42. Explain the lifecycle of a request during overload with load shedding?

Here is what happens to one request when the service is at its limit, from arrival to the client's next move.

sequenceDiagram
  participant C as Client
  participant G as Gateway
  participant S as Service
  participant Q as Bounded Queue
  C->>G: request (deadline 2s)
  G->>G: admission check
  G->>S: forward with remaining deadline
  S->>Q: try to enqueue
  alt queue has room and wait is short
    Q-->>S: accepted
    S-->>C: 200 OK
  else queue full or wait too long
    S-->>G: 503 + Retry-After
    G-->>C: 503 fast
    C->>C: backoff with jitter, retry once
  end
  1. The gateway checks admission and rejects at once if the global limit is reached.
  2. The service tries to enqueue. A full queue, or a predicted wait longer than the remaining deadline, means rejection.
  3. A rejected request returns in milliseconds with Retry-After.
  4. An accepted request waits briefly, runs, and returns before its deadline.
  5. The client backs off with jitter and respects its retry budget.

Notice what is missing: no long waiting and no hidden pile-up. Admitted requests meet their latency target, and rejected ones learn the answer quickly.

The deadline matters at every step. If the predicted queue wait is already longer than the time the caller has left, rejecting immediately is better than accepting work that will finish after the client has gone.

Take quiz
What does the service do if the queue is full when a request arrives?
Holds the connection open for minutes
Silently discards it without a reply
Doubles the queue size on the fly
Returns a fast 503 with Retry-After
Why is a fast rejection valuable during overload?
It frees the client to back off and costs the server almost nothing
It increases the load on the database
It guarantees the request later succeeds
It prevents the client from ever retrying

43. How does a circuit breaker differ from a bulkhead?

Aspect Circuit breaker Bulkhead
Purpose Stop calling a failing dependency Limit resources one dependency can use
Mechanism State machine: closed, open, half-open Separate pools, semaphores or queues
Trigger Error rate or slow-call rate crosses a threshold Always active, regardless of health
Protects The dependency (time to recover) and caller threads Other dependencies sharing your resources
Reaction time After failures are observed Immediate, by construction

They are complementary. A bulkhead guarantees a slow payments service can use at most its 20 slots. A circuit breaker notices that those slots are all timing out and stops sending calls for a while, so the slots are not wasted either.

Using only a breaker still lets a slow dependency drain every shared thread before the threshold trips. Using only a bulkhead still keeps calling a service that is clearly down.

Take quiz
Which mechanism is always active as a fixed resource boundary?
Circuit breaker
Retry with jitter
Bulkhead
What is the weakness of using only a circuit breaker?
It cannot fail fast
A slow dependency may drain shared threads before the breaker trips
It requires a separate database
It needs no thresholds

44. Why is p99 latency a better overload signal than CPU?

CPU only shows one kind of saturation. A service can be badly overloaded at 20% CPU if its threads are all blocked on a slow database, a lock, or a full connection pool.

Latency, especially at the tail, reflects waiting for any resource. When queues form anywhere, the slowest requests get slower first, so p99 moves before averages and long before CPU.

  • CPU - misses I/O-bound and lock-bound overload.
  • Average latency - hides the tail where the pain starts.
  • p99 latency and queue age - react early and match what users experience.

Use CPU as a secondary signal, not the main one. The most useful controllers combine in-flight count, queue wait time and tail latency of successful requests.

Measure latency of successful requests separately from rejections. Fast 503 responses would otherwise pull the percentile down and make an overloaded service look healthy.

Take quiz
A service has 20% CPU but its threads are all blocked on the database. Which signal reveals the overload best?
CPU utilization
p99 latency or queue wait time
Free disk space
Number of log files
Why does p99 react earlier than the average?
It is computed from CPU samples
It ignores slow requests
Slowest requests degrade first when queues begin to form
It is always equal to the median

45. How can you optimize throughput under bounded concurrency?

With a fixed limit, throughput is roughly limit divided by service time. So you improve it either by finding the right limit or by making each request cheaper.

  1. Find the knee. Raise the limit in a load test until throughput stops growing and latency starts to jump. Run slightly below that point.
  2. Cut service time. Add timeouts to slow calls, cache hot reads, remove redundant calls and serialize less.
  3. Batch. Group small operations so overhead is paid once.
  4. Separate classes of work. Give slow and fast operations different pools so one cannot block the other (head-of-line blocking).
  5. Reject early. Refuse excess work before parsing or authentication so no capacity is spent on it.

Beyond the knee, more concurrency does not add throughput. It only adds contention and waiting, so a higher limit can make things worse.

Take quiz
With a limit of 40 and a service time of 100 ms, throughput is about:
40 requests per second
4,000 requests per second
400 requests per second
100 requests per second
Why can raising the concurrency limit past the knee hurt?
It disables timeouts
It reduces the size of responses
It switches the protocol to UDP
It adds contention and waiting without adding throughput

46. How do you troubleshoot a growing queue with flat CPU?

Flat CPU with a growing queue means the consumers are waiting, not working. Find out what they are waiting on.

  1. Compare in-flight count to the limit. If it is pinned at the cap, workers are stuck, not idle.
  2. Take thread dumps and look for many threads blocked on the same call, lock or connection pool.
  3. Check downstream latency. A slow database or API explains most cases.
  4. Look at connection pool metrics for exhausted or timing-out checkouts.
  5. Check for GC pauses and for a poison message being retried in a loop.
  6. Look for partition or key skew, where one consumer is overloaded and others are idle.
  7. Check whether a rebalance or restart loop is repeatedly interrupting consumers.

Once you find the stalled resource, limit concurrency to it, add a timeout, and let the queue push back instead of growing.

Take quiz
A queue grows while CPU stays low. What is the most likely general cause?
The CPU is too fast
The queue is too short
Producers have stopped sending
Consumers are blocked waiting on a slow resource
Which finding points to key skew?
One consumer is saturated while others are idle
All consumers equally busy
No messages in any partition
Every consumer restarting

47. What is a metastable failure in overloaded systems?

A metastable failure is a state where a system stays broken after the original trigger has gone, because an internal feedback loop sustains the overload.

A short traffic spike or slow dependency pushes the system over the edge. Then retries, a growing backlog, cache misses or timeouts keep the load above capacity, even though incoming traffic is back to normal. Throughput collapses while the system looks busy.

  • Retry loops - failed work is resubmitted.
  • Backlog - old work crowds out new work, and most of it is stale.
  • Cold caches - misses push more load onto the database.

Recovery usually means reducing load below normal for a while: shed aggressively, disable retries, drop stale queued work, then restore traffic gradually. Prevention is the toolkit from this topic: bounded queues, retry budgets, short timeouts, deadlines, fast shedding and LIFO or age-based dropping for stale work.

Take quiz
What defines a metastable failure?
The system stays degraded after the trigger ends because of a sustaining feedback loop
It only occurs during deployments
It resolves itself when the spike ends
It affects only the database
What is a typical recovery step?
Immediately restore all traffic at once
Reduce load below normal and drop stale work before restoring traffic
Increase retries on every client
Make all queues unbounded

48. How do you test backpressure behavior before production?

Test past capacity, not just at it. The question is not how fast the system goes, but what it does when it is asked for more than it can give.

  1. Use an open-loop load generator that keeps sending at a fixed rate. A closed-loop tool waits for responses, slows down with the server and hides the overload (coordinated omission).
  2. Ramp to 2x or 3x capacity and hold.
  3. Inject a slow dependency, such as 2 s of added latency or a stalled database.
  4. Watch the right outcomes: latency of admitted requests stays near target, rejections are fast, memory stays flat, no crash.
  5. Drop the load back to normal and measure recovery time. It should be seconds, not tens of minutes.

Also verify that clients behave: backoff, retry budgets and honoring Retry-After. A server that sheds perfectly can still be flattened by clients that retry without limit.

Take quiz
Why prefer an open-loop load generator for overload tests?
It uses less CPU on the test machine
It keeps sending at a fixed rate even when the server slows
It always produces zero errors
It waits for each response before sending the next
What should recovery look like after load returns to normal?
Latency stays high for hours
The service must always be restarted
Latency returns to normal within seconds
The queue must be manually deleted

49. Which is better for backpressure: pull-based or push-based consumers?

For most work-processing systems, pull-based is the safer default, because the consumer asks only when it is ready. Push can be just as safe if it is paired with explicit flow control.

Aspect Pull-based Push-based
Who controls rate Consumer Producer, unless credits are used
Backpressure Natural: no poll, no data Needs prefetch limits or credits
Latency Poll interval adds a little delay Lowest, delivered immediately
Examples Kafka, SQS polling, Reactive pull RabbitMQ push, WebSocket, server-sent events

Push brokers solve the gap with a limit on unacknowledged messages. RabbitMQ's basic.qos prefetch count, for example, caps how many deliveries a consumer holds at once, which is credit-based control in disguise.

Choose pull for throughput-oriented queues and long jobs. Choose push with credits when low latency matters and consumers are quick.

Take quiz
What does RabbitMQ's prefetch count do?
Sets the number of queues per exchange
Encrypts messages in transit
Limits how many unacknowledged messages a consumer can hold
Deletes messages after 1 second
Why is pull-based consumption naturally resistant to overload?
The broker deletes messages that are too old
Producers always send slowly
It disables all queues
The consumer only receives data when it asks for it

50. How would you design overload protection for a multi-tenant API?

The core problem is fairness: one tenant's spike must not degrade everybody else. Protection must be layered per tenant as well as global.

  1. Per-tenant rate limits sized to the plan, enforced at the gateway with 429 and Retry-After.
  2. Per-tenant concurrency quotas so one tenant cannot hold all in-flight slots.
  3. Fair queuing: weighted fair queuing or round-robin across tenant queues, so a busy tenant waits behind itself, not behind others.
  4. Priority classes: shed free or best-effort tiers first and protect critical tenants and internal health checks.
  5. Reserved capacity for the highest tiers, with spare capacity shared as a burst allowance.
  6. Isolation for noisy neighbors: separate pools or shuffle sharding, which maps each tenant to a small random subset of workers so a bad tenant affects few others.
  7. Global admission control as a final safety net for the whole system.

Return clear per-tenant signals: the specific limit hit, remaining quota and reset time. This lets well-behaved clients adapt without guessing.

Measure per tenant: rate, rejections, queue wait and p99. A single global dashboard hides exactly the unfairness you are designing against. Test with one tenant at 10x its quota and confirm that others see no change in latency.

Take quiz
What does shuffle sharding achieve in a multi-tenant system?
Encrypts every tenant's data differently
Sends all tenants to the same worker
Removes the need for rate limits
Limits the blast radius of a bad tenant to a small subset of workers
Why is a single global dashboard insufficient for multi-tenant overload?
It can hide one tenant being starved while the global average looks healthy
It cannot show latency
It always shows errors twice
It is only available in staging
«
»

Comments & Discussions