00:00

Kafka Message Ordering and Concurrent Processing

Last updated:

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.

SettingFor ordered delivery
enable.idempotencetrue (set it explicitly)
acksall
max.in.flight.requests.per.connection5 or less (default 5)
Record keyThe 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

CauseWhy order breaks
Adding partitions to a topicThe hash now maps some keys to a different partition; old and new records of a key live in two partitions
Null or random keysRecords of one entity are spread over all partitions
Idempotence disabled with several requests in flightRetries reorder batches
Retry topicsA failed record moves to another topic while later records of the same key continue
Unordered thread pools in the consumerRecords of one key run on different threads and finish in any order
Several producers for one entityNo 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.

Key-based parallel processing in a Kafka consumerA partition contains records A1, B1, A2, C1, B2 in that order. The consumer's dispatcher hashes each key to a lane. Lane 1 processes A1 then A2, lane 2 processes B1 then B2, lane 3 processes C1. Lanes run in parallel, but records of the same key keep their order. After all lanes finish the batch, the consumer commits the offset after B2. Partition accounts-3 (offset order) A1 B1 A2 C1 B2 Dispatcherlane = hash(key) mod 3 Lane 1: A1 → A2 Lane 2: B1 → B2 Lane 3: C1 all lanes done commit offset after B2 Same key → same lane → same order.Different keys run in parallel; the commit waits for the whole batch.
Records are dispatched to single-threaded lanes by key, so per-key order is kept while different keys are processed concurrently.

A simple and correct version processes each poll batch in parallel lanes and commits only after the whole batch has finished:

KeyOrderedConsumer.java
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; reduce max.poll.records if 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-1001 go 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.
AccountLedger.java
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=true explicitly 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.

10. References