Ordering and Causality
How distributed systems decide what happened before what: the happens-before relation, Lamport and vector clocks, causal consistency, and total order broadcast.
Overview
Many bugs in distributed systems are ordering bugs: a reply shown before its question, an update applied before the record exists, two nodes that apply the same writes in different orders and end up with different data. This chapter explains which orders matter and the tools that produce them.
Why order matters: cause and effect
Some events depend on others. A reply depends on the question it answers; an update depends on the row it changes. If a replica applies the effect before the cause, users see something impossible.
Here is how a chat thread shows an effect before its cause.
- Alice's question arrives at Replica 1.
- Bob reads the thread from Replica 1 and sees the question.
- Bob posts a reply, and it goes to Replica 2, which is lagging and has not yet received the question.
- Carol reads the thread from Replica 2.
- Replica 2 returns the reply without the question. Bob's reply depends on Alice's question, but Carol sees an answer to a question that does not exist yet.
Many other events are independent of each other. If Alice and Bob each post in unrelated threads at about the same time, it does not matter which one a replica shows first. Such events are concurrent: neither could have known about the other. Concurrent does not mean simultaneous; it only means no information flowed between them.
Key concepts
- Happens-before
- Concurrent events
- Lamport timestamp
- Vector clock
- Causal consistency
- Total order broadcast
- Replicated log
Interview questions
- What is the difference between Lamport timestamps and vector clocks?
- Why can causal consistency stay available when linearizability cannot?
- What is total order broadcast, and why is it equivalent to consensus?
- How do you keep events for one order in sequence in Kafka?
- How would you enforce unique usernames with total order broadcast?
Sign up free to read the full topic
More DDIA topics
- Linearizability
- LSM-Trees and SSTables
- MapReduce
- Modes of Dataflow: Databases, Services, Messages
- Multi-Leader Replication
- OLTP vs OLAP
- Partitioning Strategies: Range vs Hash
- Rebalancing Partitions
- Relational vs Document Data Models
- Reliability, Scalability, and Maintainability
- Replication Lag and Consistency Anomalies
- Schema Evolution and Backward/Forward Compatibility
Start free on Cariara · Coding problems · System design studio