Video in progress

The external service your consumer calls slowed down or went down. How do you handle backpressure in a Kafka consumer?

Kafka works on a pull model, so the simplest backpressure is polling less. When the downstream fails, I pause() the partitions, keep polling, and resume() when it recovers; in Spring that's done by pausing the container or with a circuit breaker.

📖 Answer

The wrong approach is a Thread.sleep or endless retry inside the listener. Polling stops, max.poll.interval.ms is exceeded, a rebalance starts and the load moves to another pod, which hits the same external service.

A better scheme:

@Component
class PartnerOutageHandler {
    PartnerOutageHandler(CircuitBreakerRegistry breakers, KafkaListenerEndpointRegistry registry) {
        // Resilience4j events aren't Spring events: you subscribe to them through the breaker's own publisher
        breakers.circuitBreaker("partner").getEventPublisher().onStateTransition(e -> {
            var container = registry.getListenerContainer("partner-sync");  // @KafkaListener(id = "partner-sync")
            var to = e.getStateTransition().getToState();
            if (to == CircuitBreaker.State.OPEN) {
                container.pause();       // polling continues, but no records arrive
            } else if (to == CircuitBreaker.State.HALF_OPEN) {
                container.resume();
            }
        });
    }
}

After pause() the consumer stays in the group, keeps sending heartbeats, and keeps its partitions. The lag grows, but nothing is lost and messages don't go to the DLT either; once the downstream is back, it catches up naturally.

Additional levers:

  • short timeouts and a rate limiter on external calls: if the downstream can take 100 req/s, all the consumers together shouldn't exceed that;
  • reducing concurrency: fewer parallel requests;
  • being careful with autoscaling on lag: if the bottleneck is the downstream, more pods only add to the damage.

And you have to agree with the business on how many minutes of delay are acceptable. I set the alert threshold accordingly.