Video in progress

Strong Middle 📨 Kafka and messaging

In a batch listener, what happens if record 237 out of 500 fails?

If you throw a plain exception, Spring doesn't know which record failed and resends the whole batch. If you point to the index with BatchListenerFailedException, the earlier ones are committed and only that record goes to retry or the DLT.

📖 Answer

@KafkaListener(topics = "events", batch = "true")
void on(List<ConsumerRecord<String, Event>> records) {
    for (int i = 0; i < records.size(); i++) {
        try {
            handle(records.get(i).value());
        } catch (Exception ex) {
            throw new BatchListenerFailedException("yiqildi", ex, i);
        }
    }
}

With this exception, DefaultErrorHandler:

  1. commits offsets 0..236;
  2. seeks back, starting from 237;
  3. when retries run out, hands 237 to the recoverer (a DLT, for example) and continues from 238.

If you throw a plain RuntimeException, the handler retries the whole batch, and when the attempts run out, all the records in the batch go to the recoverer: 499 healthy messages in the DLT. This was expensive for me on one project: we had to replay the DLT.

One more subtle point: if you write the batch to the DB in a single transaction, when record 237 fails, 0..236 are rolled back too. Then "commit the earlier ones" doesn't make sense. Either save each record separately, or treat the whole batch as one unit and separate the invalid record up front with validation.