Kafka Message Ordering and Concurrent Processing
Kafka message ordering is guaranteed in exactly one place: within a single partition. Records in a partition are stored and read in the order they were appended, but there is no ordering between partitions. Designing for ordering therefore means sending related records to the same partition, keeping the producer from reordering them, and processing them on the consumer side without losing that order, even when you want concurrency.
This article explains what Kafka guarantees, what silently breaks ordering, how to process records concurrently while keeping per-key order, and how to design a banking flow where transactions for one account must be applied strictly in order.
1. What Kafka Guarantees About Ordering
- Within a partition: records get increasing offsets in the order the leader appends them, and every consumer reads them in offset order.
- Across partitions: no order at all. A consumer reading partitions 0 and 1 can receive a later record from partition 1 before an earlier one from partition 0.
- Per key, by convention: the default partitioner sends every record with the same non-null key to the same partition (a murmur2 hash of the key modulo the partition count). That is how “all events of order 17 in order” is achieved.
So the practical guarantee is per-key ordering, as long as the key is chosen well and the partition count does not change.
2. Keeping Order on the Producer Side
A producer can have several requests to the same partition in flight at once. If request 1 fails and is retried after request 2 succeeded, the records land out of order. The idempotent producer prevents this: the leader accepts only the next expected sequence number, so with up to 5 in-flight requests per connection the order is preserved. Idempotence is the default since Kafka 3.0, but a conflicting setting such as acks=1 disables it silently. Without idempotence, only max.in.flight.requests.per.connection=1 keeps order during retries, at a large cost in throughput.
| Setting | For ordered delivery |
|---|---|
enable.idempotence | true (set it explicitly) |
acks | all |
max.in.flight.requests.per.connection | 5 or less (default 5) |
| Record key | The entity whose events must stay ordered: account ID, order ID |
One more producer-side rule: ordering is only defined for records sent by one producer. If two services write events for the same account, Kafka orders them by arrival at the leader, which may not be the business order.
3. Ordering Across Partitions
Kafka cannot give a total order across partitions. If you truly need it, the options are:
- A single-partition topic: total order, but throughput is limited to what one partition and one consumer thread can handle.
- A sequence number in the payload assigned by a single source, and a consumer that buffers and re-sorts. This is complex and needs bounds on how long to wait.
- Rethinking the requirement: almost always, what is really needed is order per entity, which keys already provide.
Timestamps are not a safe substitute: clocks on different producers drift, and CreateTime is set by the client.
4. What Breaks Ordering
| Cause | Why order breaks |
|---|---|
| Adding partitions to a topic | The hash now maps some keys to a different partition; old and new records of a key live in two partitions |
| Null or random keys | Records of one entity are spread over all partitions |
| Idempotence disabled with several requests in flight | Retries reorder batches |
| Retry topics | A failed record moves to another topic while later records of the same key continue |
| Unordered thread pools in the consumer | Records of one key run on different threads and finish in any order |
| Several producers for one entity | No common order between them |
Choosing the partition count up front, with room to grow, avoids the most common cause; see Kafka Partition.
5. Concurrent Processing Without Losing Order
The unit of parallelism in Kafka is the partition: a consumer group can have at most one active consumer per partition. There are two ways to get more concurrency while keeping per-key order.
5.1 More partitions, more consumers
The simplest option: create enough partitions and run as many consumer threads as partitions. In Spring for Apache Kafka, @KafkaListener(concurrency = "6") starts six consumers in the group; more consumers than partitions leaves the extra ones idle (see Consumer Groups).
5.2 Key-based parallelism inside one consumer
When processing is slow (an HTTP call, a database write) and partitions are few, one consumer can process a partition’s records in parallel by key: records with the same key always go to the same single-threaded lane, so their order is kept, while different keys run concurrently.
A simple and correct version processes each poll batch in parallel lanes and commits only after the whole batch has finished:
int laneCount = 8;
ExecutorService[] lanes = new ExecutorService[laneCount];
for (int i = 0; i < laneCount; i++) {
lanes[i] = Executors.newSingleThreadExecutor(); // one thread per lane keeps order
}
while (running) {
ConsumerRecords<String, String> records = consumer.poll(Duration.ofMillis(500));
List<Future<?>> batch = new ArrayList<>();
for (ConsumerRecord<String, String> record : records) {
int lane = Math.floorMod(Objects.hashCode(record.key()), laneCount);
batch.add(lanes[lane].submit(() -> handler.process(record)));
}
try {
for (Future<?> f : batch) {
f.get(); // wait for every lane to finish
}
consumer.commitSync(); // at-least-once: commit after processing
} catch (ExecutionException e) {
// a record failed: do not commit; seek back to the committed offsets and retry the batch
rewindToCommitted(consumer);
}
}
Objects.hashCode(key)maps a null key to lane 0, so the loop never throws.- The whole batch must finish within
max.poll.interval.ms; reducemax.poll.recordsif processing is slow. - A failed batch is retried in full, so the handler must be idempotent.
For continuous pipelining without a batch barrier, track completed offsets per partition and commit only the highest offset below which everything is done. That is more complex, which is why the batch approach is a good default.
6. Design Example: Strict Order per Bank Account
Requirement: deposits, withdrawals and transfers for the same account must be applied in exactly the order they happened; different accounts can be processed in parallel.
6.1 Producer
- Key every event by account ID. All events of account
ACC-1001go to one partition. A transfer produces two events, one keyed by each account. - A single writer per account: only the account service publishes account events, ideally through a transactional outbox read in commit order.
- Idempotent producer with
acks=all, so retries neither reorder nor duplicate. - Include a per-account sequence number (or version) in each event, assigned by the account service.
- Fix the partition count with headroom, because adding partitions later remaps accounts.
6.2 Consumer
- Process each account sequentially: one consumer per partition, or key-based lanes as above.
- Blocking retries only. A failed event is retried in place; moving it to a retry topic would let the next event of the account overtake it. After a bounded number of attempts, stop the partition or park the account’s events instead of skipping.
- Check the sequence number in the database: apply an event only if its sequence is the account’s last applied sequence + 1, in the same transaction that updates the balance. A lower number is a duplicate to skip; a higher number means a gap to investigate.
record AccountEvent(String accountId, long sequence, BigDecimal amount) {}
@Transactional
public void apply(AccountEvent e) {
// Apply only the next expected event, and advance the sequence in the same statement
int updated = jdbc.update("""
UPDATE account
SET balance = balance + ?, last_sequence = ?
WHERE id = ? AND last_sequence = ?
""", e.amount(), e.sequence(), e.accountId(), e.sequence() - 1);
if (updated == 0) {
long last = jdbc.queryForObject("SELECT last_sequence FROM account WHERE id = ?",
Long.class, e.accountId());
if (e.sequence() <= last) {
return; // duplicate: already applied
}
throw new SequenceGapException(e.accountId(), last, e.sequence()); // blocking retry, then alert
}
}
Kafka provides the per-account order; the sequence check proves it in the database and makes redelivery harmless.
7. Best Practices
- Ask “ordered per what?” and use that entity’s ID as the key.
- Size partitions for the future and avoid increasing them on topics that need key order.
- Set
enable.idempotence=trueexplicitly on producers of ordered data. - Never use unordered thread pools for ordered topics; use key-based lanes.
- Prefer blocking retries for ordered data, and alert when a partition is stuck.
- Carry a version or sequence number when correctness depends on order.
8. Summary
Kafka orders records only within a partition, so ordering is designed per key: a stable key, a fixed partition count, an idempotent producer and a single writer per entity. Across partitions there is no order, and a single partition is the only way to get a total order. On the consumer side, scale with partitions or with key-based lanes, commit after the work is done, use blocking retries for ordered data, and add sequence numbers when the business must prove order, as in a banking ledger.
9. Related Reading
10. References
Kafka Message Ordering Interview Questions and Answers
Common interview questions on Kafka Message Ordering, from basic to scenario-based, with short answers you can explain in your own words.
Basic questions
Q. How does Kafka maintain message ordering, and is there ordering across partitions?
Answer: Kafka guarantees order only within a partition: records are appended with increasing offsets and read in that order. There is no ordering between partitions. Related records are kept in order by giving them the same key, because the default partitioner sends equal keys to the same partition. A total order across a topic is only possible with a single partition, which limits throughput to one partition and one consumer thread.
Q. Two producers send records with the same order ID as key, yet the records land in different partitions. How is that possible?
Answer: The default partitioner hashes the serialized key bytes, not the Java value. If one producer serializes the order ID as the string "1001" and another as a Long, or adds whitespace or a different case, the bytes differ and so do the partitions. Other causes are a custom partitioner in one of the producers, or producers created with different partition counts in their metadata during a partition increase. Use one shared key format and serializer for every producer of a topic.
Intermediate questions
Q. How do you process Kafka messages concurrently without compromising ordering?
Answer: Scale by partitions first: one consumer thread per partition keeps order automatically. If one consumer needs more concurrency, parallelise by key: hash each record’s key to a single-threaded lane, so the same key is always processed sequentially while different keys run in parallel. Commit offsets only after all records up to that offset are processed, for example by waiting for the whole poll batch. Never hand records to an unordered thread pool.
Q. Besides changing the partition count, which design choices break per-key ordering?
Answer: Null or random keys, which spread one entity across partitions; disabling idempotence while allowing several in-flight requests; moving failed records to retry topics while later records of the same key continue; processing with an unordered thread pool; and letting several producers write events for the same entity, since Kafka can only order them by arrival time at the leader.
Tricky and scenario questions
Q. In a banking application, transactions for the same account must be processed in strict order. How would you design the producer and consumer?
Answer: Producer: key every event by account ID, use a single writer per account (ideally an outbox read in commit order), keep idempotence on with acks=all, add a per-account sequence number, and choose the partition count with headroom so it never changes. Consumer: process each account sequentially, either one consumer per partition or key-based lanes; use blocking retries, never retry topics, so a failed event cannot be overtaken; and apply an event only if its sequence is the last applied + 1, in the same database transaction as the balance update, skipping lower numbers as duplicates and alerting on gaps.
Q. Two microservices both publish events about the same customer, using the customer ID as key. Is the order between their events guaranteed?
Answer: Only in the sense that both land in the same partition and are read in the order the leader appended them. That is arrival order, which depends on network timing and retries, not on when the business actions happened. If the order matters, make one service the owner that publishes all events for a customer, or include a version or timestamp from a single source so consumers can detect and handle out-of-order events.