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

Lamport Timestamps

A simple counter rule that gives every event an order that respects cause and effect.

โฑ 12 min readIntermediateInterview FavouriteHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

A Lamport timestamp is the simplest logical clock: each machine keeps one counter, adds 1 for every event, and sends the counter in every message. A receiver jumps ahead of the number it received.

  • Local event or send: counter = counter + 1.
  • Receive: counter = max(my counter, message counter) + 1.
  • The promise: if event A could have caused B, then A's number is smaller than B's. The reverse is not promised.

02Concept: What is it?

Leslie Lamport introduced this in 1978, in his paper "Time, Clocks, and the Ordering of Events in a Distributed System". The goal is a number for each event, so that if A happened-before B, then the number for A is less than the number for B. This is called the clock condition.

The algorithm has two rules. Rule 1: before each event on a machine (including sending), increase its counter by 1, and give the event that value. Rule 2: a message carries the sender's counter. When a machine receives one, it sets its counter to the larger of its own value and the message value, then adds 1.

Rule 2 is the important one. It makes the receive always look later than the send, even if the receiver had a lower counter before. Without the max step, a receiver with a small counter would stamp the receive with a number smaller than the send, and the effect would look older than its cause.

One message, one jump
๐Ÿ–ฅ๏ธA counter 5sends: counter becomes 6
โ†’โ†“message (6)
๐Ÿ–ฅ๏ธB counter 2max(2, 6) + 1 = 7
B was at 2. A's message carries 6. B jumps to max(2, 6) + 1 = 7.
๐Ÿง One direction only
If A โ†’ B then L(A) < L(B). But L(A) < L(B) does not mean A โ†’ B. Two unrelated events can have any numbers. To detect concurrency, you need vector clocks.

03Real-Life Example

๐ŸตThe Ticket Number at a Deli
Each shop in a chain has a ticket machine. A shop never looks at a clock. When a customer calls another shop to say "I was number 40 at the first shop", the second shop makes sure its next ticket is above 40, so the follow-up request is served after the first one. If its machine was at 12, it jumps to 41. Tickets never go backward, and any request caused by another always has a bigger number.
Deli shops
Lamport timestamps
A ticket machine in each shop
A counter on each machine
Each new customer gets the next number
Each event adds 1
Phoning another shop with your number
A message carrying a timestamp
Jumping the machine above that number
max(mine, received) + 1
A follow-up request always has a bigger number
Cause is always smaller than effect
Two shops with no calls between them
Concurrent events, with arbitrary numbers
Shop 3 wins when two numbers tie
Tie-break by machine ID
A tiny run with three servers
1๏ธโƒฃA: eventA = 1
โ†’โ†“send (2)
2๏ธโƒฃB: receivemax(0, 2) + 1 = 3
โ†’โ†“send (4)
3๏ธโƒฃC: receivemax(0, 4) + 1 = 5

04Why Do We Need It?

๐Ÿ”ขA simple order
One number per event, and you can sort them. No clock sync, no special hardware.
๐ŸงฉRespects causality
A cause is always numbered lower than its effect.
๐ŸชถTiny cost
One integer per message and one per machine.
๐ŸงฎA total order
With a tie-break, every pair of events is ordered the same way on every machine.
๐Ÿ”’Mutual exclusion
Lamport used it to build a distributed lock with no central server.
๐ŸชœStep to vector clocks
It is the first idea you need before learning how to detect concurrent events.
Lamport timestamps give every machine the same, causality-respecting order of events using nothing but a counter.

05Where Do We Use It?

๐Ÿ—ณ๏ธConsensus rounds
Paxos ballots and Raft terms are Lamport-style counters that decide which proposal is newer.
๐Ÿ”Distributed locks
Lamport's mutual exclusion algorithm queues requests by timestamp. Fencing tokens use the same growing-number idea.
๐Ÿ“œReplicated logs
Sorting events by (timestamp, machine ID) gives all replicas the same sequence.
๐Ÿ’ฌChat ordering
Messages are shown in timestamp order so replies appear after their questions.
๐Ÿ—„๏ธDatabase versions
A version number or revision counter in a store works like a Lamport clock.
๐ŸงฐHybrid clocks
CockroachDB and others add a Lamport-style counter to wall time.

06Types / Parts / How It Works

The two rules, step by step

WhenWhat the machine doesExample
Local eventcounter = counter + 1, event gets the valueCounter 3, event is 4
Send a messagecounter = counter + 1, message carries the valueCounter 4, sends 5
Receive a messagecounter = max(counter, message) + 1Counter 2, message 5, new counter 6
Why max matters
Just add 1 (broken)
๐Ÿ“คSend stamped 9
โ†“receiver was at 2
๐Ÿ“ฅReceive stamped 3looks older than its cause
max + 1 (correct)
๐Ÿ“คSend stamped 9
โ†“receiver was at 2
๐Ÿ“ฅReceive stamped 10always after the send
Without max, the receive would get a number smaller than the send.

Getting a total order

Two events on different machines can get the same number. To make every pair comparable, sort by (timestamp, machine ID). The result is arbitrary for concurrent events, but identical on every machine.

๐Ÿ”ข3Atimestamp 3, machine A
โ†’โ†“
๐Ÿ”ข3Bsame number, so B after A
โ†’โ†“
๐Ÿ”ข4A
Machine A Machine B
VisualizerBuild a run of events and watch the countersAdd local events and messages between servers. Then switch the receive rule to โ€œjust + 1โ€ and see a receive that looks older than its send. Check the sorted order at the bottom.
Rule when a message arrives
Add an event
From
To
Server AServer BServer C12314567
โ— local eventโ— sendโ— receiveโ— receive that looks older than its send
One agreed order for all events: sort by timestamp, and break ties with the server name
1A1C2A3B4B5C6C7A
Clock A
7
Clock B
4
Clock C
6
Messages
3
sent and received
Broken receives
0
receive โ‰ค send
A received a message stamped 6. Its own counter was 2, so it takes max(2, 6) + 1 = 7. The receive is now guaranteed to look later than the send.

Each step is one local event, or one message that is sent and received straight away. Lamport timestamps never go backwards, but a smaller number does not prove that an event really happened first: two events with different numbers may be unrelated.

07How to Use It / Steps / Implementation

Implementing it

  1. 1
    Give each machine a counter
    Start at 0 and save it to disk, so a restart does not reuse numbers.
  2. 2
    Tick on every event
    Add 1 before each local event and before each send.
  3. 3
    Put the counter in every message
    A header or a field is fine. It is one integer.
  4. 4
    On receive, take the max
    counter = max(counter, received) + 1. This is the step people forget.
  5. 5
    Store the stamp with the data
    Keep (counter, machine ID) next to each record or log entry.
  6. 6
    Sort by (counter, machine ID)
    That gives all machines the same total order, even for concurrent events.
  7. 7
    Do not use it as time
    A Lamport number says nothing about seconds. Keep a wall-clock time too if you need one.
๐Ÿ’กA few lines of code
on_event: c += 1 ยท on_send: c += 1; msg.ts = c ยท on_receive: c = max(c, msg.ts) + 1
โš ๏ธDo not infer too much
If L(A) < L(B), A might be the cause of B, or the two might be unrelated. If you need to know which, use vector clocks.

08Key Terms to Know

TermMeaning in easy words
Lamport timestampA number from a per-machine counter that respects cause and effect
CounterAn integer each machine increases on every event
Clock conditionIf A happened-before B then L(A) < L(B)
Happened-beforeA โ†’ B means A could have influenced B
ConcurrentNeither event could have influenced the other
Total orderA way to order every pair of events
Tie-breakA fixed rule (such as machine ID) used when two numbers are equal
max ruleOn receive, set the counter to max(own, message) and then add 1
ConverseThe opposite claim. L(A) < L(B) does not imply A โ†’ B
Lamport mutual exclusionA lock built by ordering requests by timestamp
Fencing tokenA growing number given with a lock, so storage rejects old holders

09Pros, Cons and Trade-offs

โœ… Pros
  • Very simple: one integer per machine
  • No clock synchronization needed
  • Cheap to send and store
  • Gives a total order, identical on all machines
  • A building block for locks, logs and consensus
โš ๏ธ Cons
  • Cannot tell concurrent events from ordered ones
  • No link to real time
  • A smaller number does not prove a cause
  • Order of concurrent events is arbitrary
  • Hidden causality outside messages is missed

Trade-offs

ChoiceWe gainWe lose
Lamport timestampTiny, simple, total orderNo concurrency detection
Vector clockDetects concurrency exactlySize grows with machines
Tie-break by machine IDSame order everywhereSome bias toward certain machines
Persisting the counterSafe restartsA write on each tick (or batch it)
Wall-clock timestampReal time meaningNot safe for order

10Common Problems and Mistakes

Common mistakes

  1. Forgetting the max. Using counter + 1 on receive gives a receive older than its send.
  2. Reading order from numbers alone. A smaller timestamp does not prove that an event came first.
  3. No tie-break. Equal numbers sort differently on different machines.
  4. Losing the counter on restart. It restarts at 0, and new events look older than old ones.
  5. Not stamping every send. A message without the counter leaves the receiver behind.
  6. Treating it as real time. It cannot answer "what happened at 2 pm?"
  7. Counters that run away. One buggy machine sending a huge number pushes everyone up. Validate input in untrusted systems.

Things to watch

๐Ÿ•ณ๏ธOutside channels
If people or files carry information between machines, causality is not captured.
๐Ÿ’ฅCounter overflow
Use a 64-bit integer so you never wrap around.
๐ŸงฎConcurrent events look ordered
The total order can invent an order between unrelated events. Do not treat it as truth.
๐Ÿ”„Restarts
Persist the counter, or add a start epoch to the stamp.

11Real-World Examples

๐Ÿ“„Lamport's 1978 paper
One of the most cited papers in computer science. It introduced happened-before and this clock.
๐Ÿ—ณ๏ธRaft terms
A term is a counter that grows when an election starts. A node that sees a higher term steps down.
๐Ÿ›๏ธPaxos ballot numbers
Proposals carry a growing number so acceptors can ignore stale ones.
๐Ÿ”Fencing tokens
A lock service hands out a growing token, so storage can reject writes from an old holder.
๐Ÿ“ŠCockroachDB
Its hybrid logical clock includes a Lamport-style counter for events in the same instant.
๐Ÿ—„๏ธRevision numbers
etcd and others give each change a growing revision, a single-leader version of the idea.
๐Ÿ“Note
Raft and Paxos are more than a Lamport clock. The growing number is only one part of how they stay correct.
Mini case: stale lock holder
๐Ÿ”Client 1 gets token 33then pauses
โ†’โ†“lease expires
๐Ÿ”Client 2 gets token 34writes OK
โ†’โ†“Client 1 wakes, sends 33
๐Ÿ›ก๏ธStorage rejects 3334 was already seen
A growing token lets the storage server turn away the old holder.

12Related Topics to Read Next

Logical Clocksโ†’

The big picture: happened-before and concurrency.

Vector Clocksโ†’

The next step: detect concurrent events.

Clock Synchronization Problemโ†’

Why we need logical clocks at all.

Paxosโ†’

Uses growing ballot numbers that work like Lamport clocks.

Raftโ†’

Terms are a simple logical clock for elections.

Distributed Locksโ†’

Fencing tokens use the same growing-number idea.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • โœ”Counter: one integer per machine, starts at 0.
  • โœ”Local or send: add 1, and attach the value to the message.
  • โœ”Receive: counter = max(mine, message) + 1.
  • โœ”Guarantee: if A โ†’ B then L(A) < L(B).
  • โœ”Not guaranteed: L(A) < L(B) does not mean A โ†’ B.
  • โœ”Total order: sort by (timestamp, machine ID).
  • โœ”Need concurrency detection? Use vector clocks.
  • โœ”One line: โ€œCount your events, share the count, and always jump past what you hear.โ€
โ† Previous
Logical Clocks
Next โ†’
Vector Clocks