NewWork mode: your Claude Code or Codex on work calls, answering from your project's codeSkip to content
Senior0 views

What issues with message ordering or duplication did you encounter on the Kafka consumer side, and how did you address them?

Practice

AI answer

In Kafka, order is guaranteed only within a single partition and in the order messages are written. In practice, problems usually arise not from the broker but from consumer-side processing:

  • If messages for the same entity are sent to different partitions, there is no global ordering for them. Key messages by entity ID so that related events go to the same partition.
  • If a consumer processes messages in parallel, a later message may finish before an earlier one. To ensure strict ordering, I limit concurrency within a partition or serialize processing by key.
  • If a failure occurs after processing but before the offset is committed, the message will be delivered again. That is why I make the handler idempotent: I check the event ID, use a unique key/constraint in the database, or atomically commit the change and the processed ID.
  • Committing the offset before processing is complete can result in message loss. I usually commit the offset after successful processing; with batch processing, I carefully commit only the range that has been completed continuously.
  • Retries can disrupt ordering if a failed message is skipped and processing of the partition continues. To ensure strict ordering, I pause the partition or send the message to a separate retry process that preserves order; after a specified number of attempts, I use a DLQ and trigger an alert.
  • A rebalance can cause messages to be delivered again if the previous consumer processed them but did not have time to acknowledge them. Idempotency remains essential; it is also important to handle partition revocation correctly and finish current processing before handing off ownership.

Kafka transactions can be used to atomically write a result to Kafka and commit the offset. But if a handler modifies an external database, idempotency and, for example, the transactional outbox pattern are usually used: Kafka cannot use a single transaction to atomically cover an arbitrary external system.