Topics / 🗄️ Distributed Data Systems / ⏱️ Level 69: Distributed Data: Faults, Time & Consensus

Python exercise · about 5 minutes · free

Lamport Clocks: Ordering Without a Wall Clock

Server clocks disagree by milliseconds or seconds. For ordering events, a counter that respects cause and effect is enough.

Wall clocks drift and jump, so comparing timestamps from different machines can order events wrongly. A Lamport clock is a counter per node: increment on every local event; stamp each message with the counter; on receiving a message set your counter to max(mine, theirs) + 1. If event A could have caused B, A's timestamp is smaller. Break ties with the node id to get a total order consistent with causality (concurrent events get an arbitrary but agreed order).

Prices, versions and service names last checked 2026-11-19. They change, so confirm on the official pages before you rely on them.

Flow: a: tick, tick, send (stamp (3, a)) → b receives (max(0, 3) + 1 = 4) → b ticks (5). if A could cause B, A's timestamp is smallera: tick, tick, sendstamp (3, a)b receivesmax(0, 3) + 1 = 4b ticks5if A could cause B, A's timestamp is smaller
Your quest: Write class LamportClock(node) with tick() (increment and return the new value), send() (a tick; return (value, node)), and receive(stamp) (stamp is (value, node); set counter to max(own, value) + 1 and return it). Write total_order(events) sorting a list of (value, node, label) by (value, node) and returning the labels.
Try it now Runs in your browser. No sign-in needed. Ctrl+Enter to run.
Hint<code>receive</code>: <code>self.time = max(self.time, stamp[0]) + 1</code>. <code>total_order</code>: <code>sorted(events, key=lambda e: (e[0], e[1]))</code>.
Output appears here.

Open it in the full course → Free with Google: saves your progress and unlocks 627 lessons.

In this level you'll learn:
More in Level 69: Distributed Data: Faults, Time & Consensus

Share on LinkedIn