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

Hybrid Logical Clocks (HLC)

A clock that looks like real time but keeps cause and effect in order, by mixing wall time with a counter.

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

01Quick Summary

A hybrid logical clock (HLC) is a timestamp made of two parts: a wall-clock time and a small counter. It looks like real time, so people can read it, but it also keeps cause before effect, like a Lamport clock.

  • Wall-clock clocks are readable but can run backwards or disagree.
  • Lamport clocks are safe but have no link to real time.
  • HLC keeps the best of both: always close to real time, and a cause is always stamped before its effect.

02Concept: What is it?

An HLC timestamp is a pair (l, c). l is the largest wall-clock time this machine has seen so far (its own clock, or a time that arrived in a message). c is a counter that only matters when two events have the same l. Timestamps are compared like words in a dictionary: compare l first, and if equal, compare c.

The idea comes from a 2014 paper by Kulkarni, Demirbas and others. The key trick: never let l go backwards, even if the wall clock does. If the local clock says 100 but a message arrived stamped 130, the machine keeps 130 and raises the counter. Time then stays correct in order, and the l part never drifts far from real time (it is at most as far ahead as the fastest clock).

The rules

WhenNew lNew c
Local event or sendmax(old l, my wall clock)If l did not change: c + 1. If l moved forward: 0
Receive a message (l_m, c_m)max(old l, l_m, my wall clock)If the max is tied between values, take the largest tied c and add 1. If my wall clock alone is the max: 0
A message from a clock that is ahead
🖥️A sends (130.0)A's clock is fast
→↓message
🖥️B receivesmax(old, 130, wall 100) = 130, so c + 1
→↓stamp
🔢(130.1)after the send, as it must be
B's own clock says 100, but the message carries 130. B must not stamp the receive with 100.
🧠Two promises
1) If A caused B, then HLC(A) < HLC(B), like Lamport. 2) The l part stays close to real time, so you can ask "what happened around 3 pm?" and sort and clean up by time.

03Real-Life Example

🍵Letters with a Date and a Number
Offices exchange letters. Each letter is stamped with the date, but office clocks are not exactly the same. A rule is added: "When you receive a letter, never date your reply earlier than the date on the letter you received. If the date is the same, add a small number after it." Now every reply is dated after the letter it answers, the dates still look like real dates, and no office dates anything far into the future.
Letters
Hybrid logical clocks
The date on the letter
l, the wall-clock part
The small number after the date
c, the counter
Never date a reply before the letter you got
l = max(my wall, message l)
Same date again? Add 1 to the number
c = c + 1 when l did not move
A new day starts the number again at 0
c resets when l moves forward
Sorting letters by date, then by number
Compare (l, c) in order
Refusing letters dated far in the future
A maximum allowed offset check
Three clocks side by side
🕰️Wall clockreadable, can go backwards
🔢Lamportsafe order, no time
🧬HLCreadable and safe
Same events, three kinds of stamp.

04Why Do We Need It?

🧩Cause before effect
A reply is always stamped after the message it answers, even with a slow clock.
📅Still looks like time
You can read it, query a range like “last 10 minutes”, and delete old data by it.
🪶Small
One 64-bit number often holds both parts (48 bits of time, 16 bits of counter).
🚫No special hardware
Works with ordinary NTP clocks. It does not need GPS or atomic clocks.
🛡️Bounded drift
The l part stays within the clock error of real time, unlike a Lamport number.
🔁Snapshot reads
A timestamp can be used to read the database as of one moment in time, across nodes.
An HLC is a Lamport clock that stays close enough to real time to be useful, at the cost of one counter.

05Where Do We Use It?

🪳CockroachDB
Every transaction and write gets an HLC timestamp. It is the core of its ordering.
🍃MongoDB
Cluster time and oplog timestamps are hybrid values used for causal consistency.
🧮YugabyteDB
Uses HLC for multi-version reads and for ordering transactions across shards.
🗂️Multi-version databases
Each version of a row is stamped, so a read can ask for “the data as of time T”.
🔔Event and audit logs
Log ordering across services where a readable timestamp matters.
🧰Changefeeds and CDC
Resolved timestamps say “everything up to T has been seen”.

06Types / Parts / How It Works

Where HLC sits among the clocks

ClockClose to real time?Cause before effect?Needs special hardware?Typical use
Wall clock + NTPYes, within msNoNoLogs, display, expiry
Lamport clockNoYesNoOrdering, locks, terms
Vector clockNoYes, plus detects concurrentNoConflict detection (Dynamo-style)
Hybrid logical clockYes, within the clock errorYesNoDistributed SQL, snapshot reads
TrueTimeYes, with a known boundYes, with commit waitYes, GPS and atomicSpanner, strong global order

Why the counter is needed

Two events in the same millisecond
Wall clock only
1️⃣Event 1: 100
2️⃣Event 2: 100same value, order unclear
HLC
1️⃣Event 1: 100.0
2️⃣Event 2: 100.1counter breaks the tie
Without a counter two events would get the same stamp and could not be ordered.

Packing it in one number

Many systems squeeze both parts into a single 64-bit integer: the high bits hold physical time in milliseconds, and the low bits hold the counter. Because the high bits come first, sorting the plain integers gives the correct order, which is why HLCs fit easily in existing storage.

l: wall-clock part c: counter part
VisualizerWall clock, Lamport and HLC on the same eventsServer B starts 40 ms behind. With “Wall clock only”, a receive can look older than its send. Switch to HLC and the problem disappears while l stays close to real time. Then make C fast and watch the counter appear.
Which stamp do we trust?
Add an event
From
To
Events with the wall clock, Lamport timestamp and HLC of each
EventReal timeIts own wall clockLamportHLC (l.c)
A does something1000100011000.0
A sends1010101021010.0
B receives1014974 ✗ older than send31010.1
B does something102098041010.2
B sends103099051010.3
C receives1034103461034.0
C sends1040104071040.0
A receives1044104481044.0
Wall clock mistakes
1
receive looks older than send
Lamport mistakes
0
but numbers mean no time
HLC mistakes
0
receive ≤ send
HLC away from real time
20 ms
largest counter: 3
The plain wall clocks would have 1 receive that look older than the send. HLC has none: when a message arrives with a time later than the receiver clock, the receiver keeps that time and raises its counter. The HLC part stays within 20 ms of real time.

Real time moves 10 ms per step and a message takes 4 ms. Server A has a perfect clock, B is slow and C is fast by the amounts you set. HLC is shown as l.c, where l is a time in ms and c is the counter that breaks ties. Real systems also reject a message whose time is far ahead of the local clock.

07How to Use It / Steps / Implementation

Implementing an HLC

  1. 1
    Keep (l, c) on every node
    Start with l = 0 and c = 0. Keep it in memory, and persist a safe upper bound so a restart never goes backwards.
  2. 2
    On a local event or send
    Let pt be the wall clock. Set l' = max(l, pt). If l' equals the old l, then c = c + 1, else c = 0. Stamp the event (l', c).
  3. 3
    Send the stamp in each message
    Add (l, c) as a header or a field so the receiver can use it.
  4. 4
    On receive
    Set l' = max(l, l_msg, pt). If l' ties with the old l and the message l, c = max(c, c_msg) + 1. If it ties with one, use that c + 1. If only pt is the max, c = 0.
  5. 5
    Reject wild timestamps
    If l_msg is more than a set limit (for example 500 ms) ahead of pt, refuse the message or raise an alert. One bad clock must not pull the cluster into the future.
  6. 6
    Pack into one integer
    Time in the high bits, counter in the low bits. Sorting the number sorts the events.
  7. 7
    Use it as the version
    Stamp each write with it and let reads ask for “as of timestamp T”.
💡Pseudo-code
send: l2 = max(l, pt); c = (l2 == l) ? c + 1 : 0; l = l2 · receive: l2 = max(l, lm, pt); c = f(ties); l = l2
⚠️Do not skip the upper limit
Without a maximum offset check, a single machine with a clock far in the future drags every other machine's l forward with it.

08Key Terms to Know

TermMeaning in easy words
Hybrid logical clockA timestamp of wall-clock time plus a counter
l (logical wall part)The largest wall-clock time this node has seen, from its own clock or a message
c (counter)A small number that breaks ties when l is the same
Physical time (pt)What the machine's own clock says right now
CausalityIf A could have caused B, A must be stamped before B
Max clock offsetThe largest clock error the system accepts between nodes
Bounded driftl never gets further from real time than the clock error
Lamport clockA pure counter that respects cause but has no time
Snapshot readReading the data as it was at one timestamp
Resolved timestampA time T up to which all changes have been delivered
Uncertainty windowThe range in which the true time may lie, because clocks are not exact

09Pros, Cons and Trade-offs

✅ Pros
  • Readable like real time
  • Cause always before effect
  • Tiny: one 64-bit value
  • No special hardware
  • Never goes backwards, even if the wall clock does
⚠️ Cons
  • Not a true global order for events that are not connected by messages
  • Needs a maximum offset assumption to stay safe
  • A clock far in the future can pull others forward
  • Does not detect concurrent events (unlike vector clocks)
  • Weaker than TrueTime, so strict global order needs more work

Trade-offs

ChoiceWe gainWe lose
HLC instead of LamportStamps that mean real timeA small bound check to maintain
HLC instead of TrueTimeNormal hardware, no commit waitNo external consistency without extra steps
HLC instead of vector clockConstant sizeNo exact concurrency detection
A small max offsetSafer, tighter boundsMore messages rejected when clocks drift
Large counter fieldMany events per millisecondFewer bits for time

10Common Problems and Mistakes

Common mistakes

  1. Using plain wall-clock timestamps. A slow clock makes an effect look older than its cause.
  2. Ignoring the message time on receive. The max with the message l is what keeps cause before effect.
  3. Forgetting the counter. Two events in the same millisecond get the same stamp.
  4. No max offset check. A clock set to next year pushes everyone's l into next year.
  5. Not saving state on restart. After a crash a node may stamp events older than before. Wait out or persist a bound.
  6. Thinking HLC order is real order. Two events with no message between them are ordered, but not by truth.
  7. Counter overflow. Too many events in one millisecond can overflow a small counter field.

Things to watch

🔮Future clock
Reject or alert on a message stamped far beyond your own clock.
🧮Counter size
A busy node may need to wait a millisecond so the counter does not run out.
🕳️Outside channels
If people or files carry information between nodes, no stamp captures that link.
🔄Restarts
Persist an upper bound, or wait one max-offset period after restart.

11Real-World Examples

🪳CockroachDB
Uses HLC with a configured max offset (500 ms by default). A node whose clock drifts too far shuts itself down.
🍃MongoDB
Cluster time is a hybrid value, gossiped between nodes, used for causal consistency sessions.
🟣YugabyteDB
A hybrid time shared by all tablets, so a multi-shard read sees one snapshot.
📄The HLC paper (2014)
“Logical Physical Clocks and Consistent Snapshots in Globally Distributed Databases”, which defined the algorithm.
🗄️Cassandra-style stores
Some designs add an HLC-style counter to last-write-wins timestamps to stop lost writes.
📡Change feeds
Resolved timestamps tell consumers when it is safe to say “nothing older will arrive”.
📝Note
CockroachDB also keeps an uncertainty interval for reads, a small cousin of Spanner's TrueTime idea. HLC alone is not enough for strict global order.
Mini case: slow clock on the replica
✍️Write at 130.0node A, clock is fast
→↓replicate
📥Replica clock says 100wall stamp would be older
→↓HLC: max(100, 130)
✅Stamp 130.1after the write
With wall clocks the reply looks older than the request. HLC fixes the stamp.

12Related Topics to Read Next

Lamport Timestamps→

The counter idea that an HLC builds on.

Logical Clocks→

The big picture of ordering by cause.

Vector Clocks→

The next step if you must detect concurrent events.

Clock Synchronization Problem→

Why wall clocks alone are not safe.

NTP: Network Time Protocol→

The source of the wall clock in an HLC, and its error.

TrueTime (Google Spanner)→

A stronger answer that uses special hardware and waits.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • ✔HLC = (l, c): wall-clock part plus a counter. Compare l first, then c.
  • ✔Send or local: l = max(l, wall). If l did not move, c + 1, else c = 0.
  • ✔Receive: l = max(l, message l, wall). Ties pick the biggest c and add 1.
  • ✔Promise 1: cause is always stamped before effect.
  • ✔Promise 2: l stays within the clock error of real time.
  • ✔Safety: reject a message stamped far ahead of your clock.
  • ✔Used in: CockroachDB, YugabyteDB, MongoDB.
  • ✔One line: “A Lamport clock you can read as a date.”
← Previous
Vector Clocks
Next →
TrueTime (Google Spanner)