Video in progress

Strong Middle 📨 Kafka and messaging

`kafkaTemplate.send()` is supposed to be asynchronous, but on prod HTTP requests hung on it for 60 seconds. How can that happen?

send() blocks the calling thread in two cases: when the topic metadata isn't available yet, and when the producer buffer (buffer.memory) is full. In both, the wait is capped by max.block.ms (60 s by default), after which a TimeoutException is thrown.

📖 Answer

send() only puts the message into the buffer and returns; that part is true. But before putting it in the buffer, the producer has to know which partition the message goes to, and for that it needs the topic metadata. If the metadata isn't there, send() waits until it has fetched it from the broker.

Cases I've seen a lot on prod:

  • The topic doesn't exist. The broker has auto.create.topics.enable=false and someone made a typo in the topic name. Every send() waits 60 seconds and fails with Topic orders-v2 not present in metadata after 60000 ms. The Tomcat threads run out and the whole service "dies".
  • The brokers are unreachable. The first send() can't get the metadata, and again you get those 60 seconds.
  • The buffer is full. The broker slowed down, messages piled up in the RecordAccumulator, and the 32 MB buffer.memory filled up. Now every send() waits for space to free up.

What I do:

spring:
  kafka:
    producer:
      properties:
        max.block.ms: 3000      # a user request shouldn't wait 60 s

This doesn't make the problem go away, but you get a fast, clear error, which you can catch and write to an outbox or answer with a 503. Checking that the required topics exist when the application starts (or NewTopic beans) also helps a lot.

Producer metrics to monitor: buffer-available-bytes, bufferpool-wait-time-total, record-error-rate. If the buffer wait time starts growing, there's a problem on the broker or network side.