SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
Part 3: Caching
Part 4: Data and Storage
Part 5: Architecture
Part 6: Distributed Systems
  • Clock Synchronization Problem
  • NTP: Network Time Protocol
  • Logical Clocks
  • Lamport Timestamps
  • Vector Clocks
  • Hybrid Logical Clocks (HLC)
  • TrueTime (Google Spanner)
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/Distributed Systems/Time and Ordering

Logical Clocks

Order events by counting them instead of trusting the wall clock.

⏱ 11 min readIntermediateHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

A logical clock orders events by cause and effect, not by the time of day. Instead of asking "what does my watch say?", it asks "could this event have influenced that one?"

  • Real clocks disagree, so we cannot trust them to say which event came first.
  • Logical clocks use counters that go up with each event and are shared inside messages.
  • They are built on one idea, happened-before: events on one machine are ordered, a send comes before its receive, and the order chains together. Everything else is concurrent.

02Concept: What is it?

In 1978 Leslie Lamport pointed out that in a distributed system we do not really need to know the exact time of events. We need to know which events could have affected which others. He called this the happened-before relation, written A → B.

There are three rules. One: if A and B are on the same machine and A ran first, then A → B. Two: if A sends a message and B receives it, then A → B (you cannot receive a message before it was sent). Three: if A → B and B → C, then A → C.

If neither A → B nor B → A is true, the events are concurrent. That does not mean they happened at the same instant. It means no chain of messages connects them, so neither could have influenced the other, and the system has no reason to put one first.

Happened-before and concurrent
Ordered
🖥️A2 sends
↓message
🖥️B2 receives
Concurrent
🖥️A3no link
🖥️C1no link
B2 happens after A2 because of a message. A3 and C1 have no chain between them, so they are concurrent.
🧠Logical clocks are about order, not time
A logical timestamp does not tell you how many seconds passed. It only helps answer: "did this come before that, or can we not tell?"

03Real-Life Example

🍵Letters Between Three Friends
Three friends in different cities write letters. Nobody has the same calendar. Ana posts a letter to Ben. Ben reads it, then writes to Chen. Chen's letter can only arrive after Ben read Ana's. So we know Ana wrote first, Ben second, Chen third, without checking any date. Meanwhile Chen wrote a postcard to herself on a day that has nothing to do with Ana's letter. We cannot say which was first, and it does not matter, as they never affected each other.
Friends and letters
Logical clocks
Each friend's own diary order
Events on one machine
Posting and then receiving a letter
Send then receive of a message
A chain of letters
Transitivity of happened-before
Two friends writing at unrelated times
Concurrent events
Quoting a number from the letter you got
Carrying a counter in a message
Needing the right dates on the calendar
Needing synchronized wall clocks (not needed)
Three ways to order events
🕰️Wall clockneeds sync, can be wrong
→↓replace with
🔢Lamport clockone counter, a consistent order
→↓or
🧭Vector clockone counter per machine, detects concurrency

04Why Do We Need It?

🧩Right cause-and-effect order
A reply must never look older than the question. Logical clocks guarantee this.
🕰️No clock sync needed
They work even when physical clocks are wrong, because they only use counters and messages.
🛠️Conflict detection
Some logical clocks can tell that two updates were made without knowing about each other.
🔁Replays and debugging
A consistent order helps merge logs and replay events in a safe sequence.
📬Message ordering
Chat and message systems use it to show messages in a sensible order.
🪢Base for bigger ideas
Consensus, causal consistency and CRDTs all build on happened-before.
When wall-clock time cannot be trusted, count events and pass the counts along with messages. Cause and effect is enough for most ordering needs.

05Where Do We Use It?

🗄️Replicated databases
Dynamo-style stores track versions with vector clocks or version vectors.
💬Chat and collaboration
Messages and edits carry counters so every user sees a consistent order.
📜Distributed logs and tracing
Trace and span IDs record the parent-child order of calls.
🔐Fencing tokens
A growing number lets a storage service reject stale lock holders.
🧮Consensus protocols
Paxos and Raft use numbered rounds (ballots and terms), which are logical clocks.
🧱Event ordering in event sourcing
Each event gets a sequence number for its stream.

06Types / Parts / How It Works

The main logical clocks

ClockWhat it keepsWhat it can tell you
Lamport timestampOne integer per machineIf A → B then ts(A) < ts(B). The reverse is not guaranteed.
Vector clockOne integer per machine, for every machineWhether A → B, B → A, or the two are concurrent
Version vectorLike a vector clock, but counts updates to a data itemWhether two replicas of the data diverged
Hybrid logical clock (HLC)Wall-clock time plus a small counterA close to real time order that never goes backward
Sequence number or termOne counter from a single leaderA simple total order inside one stream
Two events, four possible answers
⬅️A before BA → B
➡️B before AB → A
↔️Concurrentno chain either way
🟰Same eventthe same one
Ordered Cannot order
A logical clock helps you place any pair of events into one of these boxes.

Total order vs partial order

Kind of orderMeaningExample
Partial orderSome pairs are ordered, some are not (concurrent)Happened-before; vector clocks
Total orderEvery pair can be orderedLamport timestamps with a tie-break by machine ID
VisualizerWhich events happened before, after or at the same time?Click any event. Green events could have caused it, blue events it could have caused, and amber events have no link to it at all. Try A3 and B3, and see which ones stay amber.
Highlight

Click any circle to pick an event. Lines between servers are messages. Time flows left to right on each server.

Server AServer BServer CA1A2A3B1B2B3C1C2C3
Selected
B2
the event you clicked
Happened before
3
could have caused it
Happened after
2
it could have caused
Concurrent
3
no order exists
B2 is not connected by any chain of steps or messages to A3, C1, C2. Nothing says which came first, and no clock can honestly say it either. These events are concurrent. Real time may have ordered them, but the system cannot know.

Rules used: (1) events on one server are ordered by the order they happened there, (2) sending a message happens before receiving it, (3) if X is before Y and Y is before Z, then X is before Z. Anything left over is concurrent.

07How to Use It / Steps / Implementation

Using logical clocks well

  1. 1
    Decide what you need
    Just a consistent order? Use Lamport timestamps. Need to detect conflicts? Use vector clocks. Need real-world flavour? Use a hybrid clock.
  2. 2
    Keep a counter per machine
    Start at 0. Increase it on every local event, and before every send.
  3. 3
    Attach the counter to every message
    The receiver needs it to update its own clock.
  4. 4
    Merge on receive
    Take the larger value (per machine for vectors), then add the receiver's own tick.
  5. 5
    Store the stamp with the data
    Keep the timestamp or vector next to each record, so conflicts can be found later.
  6. 6
    Break ties by machine ID
    Equal Lamport numbers on different machines need a fixed tie-break to give a total order.
  7. 7
    Keep vectors small
    Vector clocks grow with the number of writers. Prune old entries or use version vectors per key.
💡Do I really need this?
If one machine (a database leader or a sequencer) hands out all the numbers, you already have a total order and no logical clock is needed. Logical clocks matter when there is no single place to order events.
⚠️A smaller number is not proof
With Lamport timestamps, ts(A) < ts(B) does not mean A happened before B. They may be concurrent. Only vector clocks can tell you that.

08Key Terms to Know

TermMeaning in easy words
Logical clockA counter that orders events by cause and effect, not by time of day
Happened-before (→)A relation that says one event could have influenced another
ConcurrentNeither event could have influenced the other
CausalityThe link between a cause and its effect
Partial orderAn order where some pairs of events cannot be compared
Total orderAn order where every pair of events can be compared
Lamport timestampA single counter updated by max-plus-one on receive
Vector clockA list of counters, one for each machine
Version vectorA vector that tracks updates to one piece of data across replicas
Hybrid logical clockA clock that combines wall time and a counter
Tie-breakA fixed rule, such as machine ID, to order equal timestamps

09Pros, Cons and Trade-offs

✅ Pros
  • No synchronized clocks needed
  • Cheap: only a few numbers to send
  • Gives a correct cause-and-effect order
  • Simple to implement and to reason about
  • Works across data centres and unreliable networks
⚠️ Cons
  • Not tied to real time, so you cannot ask “what happened at 3 pm?”
  • Lamport clocks cannot detect concurrent events
  • Vector clocks grow with the number of machines
  • Every message must carry extra data
  • A total order can put unrelated events in an arbitrary order

Trade-offs

ChoiceWe gainWe lose
Lamport clockTiny metadata, total orderCannot tell concurrent from ordered
Vector clockExact causality and conflict detectionSize grows with the writer count
Hybrid logical clockOrder plus a time close to realNeeds reasonably synced wall clocks
Single sequencerSimple, strict orderA bottleneck and a single point of failure
Wall clockHuman meaningWrong order when clocks differ

10Common Problems and Mistakes

Common mistakes

  1. Reading too much into a smaller number. Lamport order is consistent with causality, but does not prove it.
  2. Forgetting to send the counter. A message without a timestamp cannot update the receiver, so the order breaks.
  3. Only adding 1 on receive. The receiver must take the larger of its own value and the message value first.
  4. No tie-break rule. Two machines with the same number create an order that differs per reader.
  5. Letting vectors grow forever. Without pruning, the metadata can be larger than the data.
  6. Using logical time for time-based rules. Expiry and billing still need real clocks.
  7. Hidden channels. If two machines talk outside your messages (a shared file, a human), causality can be missed.

Things to watch

📏Metadata size
A vector with thousands of clients is too big. Track per replica, not per client.
🕳️Hidden causality
A user who sees A on one screen and then types B has caused B. Your system might not know.
🔄Crash and restart
A machine that loses its counter can reuse old numbers. Persist it.
🧾Ties
Equal timestamps happen all the time, so decide the tie-break up front.

11Real-World Examples

🛒Amazon Dynamo
The original Dynamo paper used vector clocks to find conflicting versions of a shopping cart.
🗄️Riak
Used vector clocks (later dotted version vectors) to keep track of sibling values.
📊CockroachDB
Uses hybrid logical clocks so timestamps are close to real time, but never go backward.
🐘Raft and Paxos
Terms and ballot numbers are logical clocks that tell which leader is newer.
🕸️Distributed tracing
Trace and parent IDs show which call caused which.
📝Collaborative editors
Use counters per user so concurrent edits can be merged in a stable order.
📝Note
Products change their internals over time. Check the current docs of any database before relying on a specific clock type.
Mini case: three replicas, two writers
👤User 1 writes v1on replica A
→↓both unaware
👤User 2 writes v2on replica B
→↓sync
⚔️Concurrent!keep both, merge later
Counters show that two updates did not know about each other, so the system keeps both.

12Related Topics to Read Next

Clock Synchronization Problem→

Why wall-clock time is not enough to order events.

Lamport Timestamps→

The simplest logical clock, step by step.

Vector Clocks→

A logical clock that can detect concurrent events.

CRDTs→

Data types that merge concurrent updates safely.

Consistency Models→

Causal consistency is built on happened-before.

Event Sourcing→

A numbered stream of events is a simple logical order.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • ✔Idea: order events by cause and effect, not by time of day.
  • ✔Happened-before: same machine order, send before receive, and chains of those.
  • ✔Concurrent: no chain in either direction, so the order is unknown.
  • ✔Counters: tick on each event, send the counter in each message, merge on receive.
  • ✔Lamport: one number, gives a total order, cannot detect concurrency.
  • ✔Vector: one number per machine, detects concurrency, grows with machines.
  • ✔Hybrid: wall time plus counter, close to real time and never backward.
  • ✔One line: “If clocks cannot be trusted, count events and pass the counts along.”
← Previous
NTP: Network Time Protocol
Next →
Lamport Timestamps