Kafka preserves record order within a partition, not across a topic. That sounds simple until an order-update consumer runs five promises at once, a failed event goes to a retry topic, and an older status overwrites a newer one. The broker can be behaving perfectly while the application violates business ordering.
1. Define the invariant before choosing a key
Suppose an order moves from CREATED to PAID to SHIPPED. The useful invariant is not “every event in the topic is ordered.” It is “updates for the same order are applied in a valid sequence.” A stable orderId key normally routes records for that order to one partition under a consistent partitioning strategy. Different orders can be processed independently. Never use a random UUID as the partition key when entity ordering matters.
Kafka only promises partition ordering for records as stored. Producers, retries, partition-count changes, and consumers still determine whether the application observes the intended sequence. Increasing a topic's partition count can change the key-to-partition mapping for subsequent records, so plan migrations explicitly.
2. Understand the concurrency trap
One consumer group assigns each partition to at most one group member at a time, but application code can still process messages from the same partition concurrently. A naive Promise.all over records may finish offset 102 before offset 101. Committing the later offset can also mark earlier work as complete. Parallelize across partitions or keys, not blindly within an ordered stream.
// KafkaJS-style eachBatch sketch: process this partition sequentially.
// Production code must also handle heartbeats, shutdown and rebalance.
await consumer.run({
eachBatchAutoResolve: false,
eachBatch: async ({ batch, resolveOffset, heartbeat, isRunning, isStale }) => {
for (const message of batch.messages) {
if (!isRunning() || isStale()) break;
await applyEvent(message); // await before advancing this partition
resolveOffset(message.offset);
await heartbeat();
}
},
});
This is an ordering illustration, not a drop-in offset-management policy. Review KafkaJS auto-commit settings and rebalance behavior. resolveOffset marks processed offsets within the batch; durable commits follow the client's configured commit path. A crash after a database write but before an offset commit can redeliver the event.
3. Add an entity version, not just a timestamp
Even perfect per-partition execution cannot protect against duplicated messages, out-of-band updates, or replay from another pipeline. Include a monotonically increasing version assigned by the authoritative writer. Reject stale transitions atomically at the database boundary.
-- Example: accept only the immediate next version.
UPDATE orders
SET status = $2, version = $3
WHERE id = $1 AND version = $3 - 1
RETURNING id;
If the update affects zero rows, distinguish a duplicate or stale event from a missing predecessor. Do not silently acknowledge a gap that must be repaired. For a new entity, use an insert guarded by a unique constraint. Version checks belong in the same transaction as the business mutation; a read-then-write check outside the transaction is racy.
4. Treat retry topics as a different ordering model
Sending a failed event to a retry topic and immediately processing the next event from the original partition breaks strict per-key sequencing. That is sometimes acceptable for independent side effects, but not for state transitions that require predecessors. Choose deliberately: pause the affected partition with bounded backoff, isolate the failing key in a key-aware workflow, or persist pending versions until gaps close. Every option trades throughput, operational complexity and latency differently.
Dead-letter queues are not an ordering guarantee. A manual replay of an old event must pass the same version and idempotency checks as normal traffic.
5. Keep producer retries from surprising you
Use a stable partitioning strategy and enable producer idempotence when supported by your client and broker configuration. Kafka's idempotent producer helps prevent duplicate writes caused by producer retries within its guarantees; it does not make a PostgreSQL side effect exactly once. Transactions can coordinate Kafka writes and consumed offsets in Kafka-centric workflows, but external database updates still require application-level correctness.
6. Build an incident-ready test matrix
- Publish ten events with the same key and verify one partition receives them in sequence.
- Publish many different keys and verify parallel processing improves throughput without per-key reordering.
- Kill a consumer after the database transaction but before offset commit; confirm redelivery is safe.
- Inject a poison event and decide whether the next version must wait or may proceed.
- Rebalance the group during a batch and confirm stale workers do not keep mutating state.
- Replay an old event and confirm the version guard prevents regression.
- Measure partition skew, consumer lag, processing latency and gap counts before increasing concurrency.
Official references
- Apache Kafka concepts and partition ordering
- Apache Kafka delivery semantics
- KafkaJS consumer and batch processing
- PostgreSQL UPDATE reference