Video in progress

Strong Middle 🧩 Microservices

How does a service protect itself when it can't handle the load? Talk about load shedding and backpressure.

Load shedding means rejecting requests beyond capacity early and cheaply (503/429), and backpressure means slowing the producer down. The goal: serve the requests within capacity normally, instead of serving everyone slowly and badly.

📖 Answer

Under load, queues grow. In Tomcat, requests wait in the acceptCount queue, then in the internal executor. A request reaches the server after 8 seconds, but the client gave up at 5. The server executes this "dead" request anyway, wasting CPU, and the following requests get delayed again. Even after the system returns to normal load, it takes a long time to recover.

Load shedding techniques:

  • limit the number of parallel requests (a bulkhead or semaphore filter) and immediately return 503 for anything over the limit;
  • drop a request that has waited too long in the queue without executing it (by arrival time or a deadline header);
  • separate by importance: health checks and payments are rejected last, reports and recommendations first.
if (!inFlight.tryAcquire()) {
    response.setStatus(503);
    response.setHeader("Retry-After", "2");
    return;
}

Backpressure is natural in asynchronous flows: a Kafka consumer does its own poll, and if it can't keep up the lag grows, but it doesn't fall over. In Reactor it's through request(n). A mistake people make is when the consumer takes messages into an unbounded in-memory queue and processes them in a separate pool: backpressure disappears and an OutOfMemoryError comes.

Autoscaling helps, but it takes a few minutes. Load shedding keeps the service alive during those minutes.