How do you get ordering and exactly-once processing with Kafka?
BackendSenior
In shortKafka orders messages only within a partition, so related events share a key. Delivery is at-least-once in practice, so consumers must be idempotent; Kafka's exactly-once semantics only cover read-process-write within Kafka. Producers use idempotence and acks=all, and the outbox pattern publishes database changes reliably.
Model answer
Ordering: Kafka guarantees order within a partition. Use a key that groups events that must stay ordered (order id, account id); the default partitioner sends equal keys to the same partition. Increasing the partition count later changes key-to-partition mapping, so plan it.
Producers: enable.idempotence=true (default in recent clients) and acks=all prevent duplicates and reordering from producer retries. To publish database changes reliably, write the event to an outbox table in the same transaction as the change and relay it (polling or CDC with Debezium); never “save then send” with two separate calls.
Consumers: a consumer group splits partitions among instances; one partition is processed by one consumer at a time. Commit offsets after processing, which means a crash re-delivers some messages: at-least-once. So consumers must be idempotent: dedupe by event id in the same transaction as the side effect, or make the operation naturally idempotent (upserts, conditional updates).
Exactly-once: Kafka transactions (transactional.id, read_committed consumers) make read-process-write within Kafka atomic (consume, produce results, commit offsets together). Writes to a database, emails or HTTP calls are outside that guarantee; idempotency is how you get effectively-once there.
Failures: retry with backoff for transient errors; send poison messages to a dead-letter topic with context, without blocking the partition forever; monitor consumer lag.
What they're looking for
Partition-level ordering and key choice, consumer groups and rebalancing, offset commit timing, idempotent producers, what transactions do and don't cover, idempotent consumers, retries and dead-letter topics, and the outbox pattern.
Common mistakes
- Expecting global ordering across partitions.
- Committing offsets before processing.
- Claiming exactly-once for side effects outside Kafka.
More backend questions
- What is the N+1 query problem, and how do you find and fix it?Mid-level
- What does Spring Boot's auto-configuration do, and how do you change what it set up?Mid-level
- How does a Spring backend authenticate requests from a mobile app, and how do you make sure users only see their own data?Mid-level
- Your Spring Boot service in Kubernetes keeps restarting with exit code 137. How do you investigate and fix it?Senior