Designing Data-Intensive Applications
Ch. 9

Ordering Guarantees

Ordering events is fundamental to consistency, causality, and replication.

If event B depends on event A, all observers must process A before B. Establishing global order in a distributed system requires either a single sequencer (leader) or logical clocks that track causality.

In practice

Kafka guarantees order within a partition — so related events (e.g., all updates for user_id=42) must share a partition key. PostgreSQL logical replication streams changes in log sequence number (LSN) order. Debezium CDC publishes database changes to Kafka preserving per-table ordering. Cross-partition causal ordering still requires application-level design.

Uber at scale

All events for one trip_id share a Kafka partition so pickup → en-route → completed always arrive in causal order. Cross-trip ordering does not matter and stays unordered.

typescript — Kafka consumer with partition ordering
// LinkedIn / Uber-style Kafka consumer with offset tracking
async function consumeMessages(groupId: string) {
  const consumer = kafka.consumer({ groupId });
  await consumer.subscribe({ topic: "user-events" });

  await consumer.run({
    eachMessage: async ({ partition, message }) => {
      const event = JSON.parse(message.value!.toString());
      await processEvent(event); // must be idempotent for at-least-once
      // offset committed after processing (or in transaction with side effect)
    },
  });
}
Key Takeaways
  • Causality: if A caused B, every node must see A before B.
  • Sequence numbers assign a total order within one leader.
  • Total order broadcast delivers the same messages in the same order to all nodes.
  • Lamport timestamps provide partial ordering without a central sequencer.
  • Consistent ordering simplifies replication and conflict resolution.
  • Kafka partition ordering, PostgreSQL LSNs, and Debezium CDC preserve event order.
causalityKafkaDebeziumtotal order broadcastLamport timestampsequence number