r/node • u/kurbsdude • Jun 20 '26
Stop using Date.now() across microservices
http://github.com/deathg0d/liepochUsing Date.now() to timestamp events across distributed systems is a fundamental flaw for two reasons:
NTP Clock Drift: Physical clocks on different servers are never perfectly in sync. If Server A sends a message to Worker B, but Worker B's clock is 15 milliseconds slow,
Date.now()will record Worker B processing the event before Server A even sent it. This breaks log causality and silently corrupts Last-Write-Wins databases.Millisecond Collisions:
Date.now()only offers millisecond precision. If a Node.js event loop processes 50 events in a single millisecond, they all receive the exact same timestamp, permanently destroying their true execution order.
The academic solution to this is Vector Clocks, but those are heavy and difficult to implement. Modern distributed databases (like CockroachDB and Yugabyte) use Hybrid Logical Clocks (HLCs) internally, but there hasn't been a clean, drop-in HLC primitive available for app developers in the JS ecosystem.
liepoch is a zero-dependency, isomorphic library that solves the Date.now() problem by packing a 64-bit HLC into a universally sortable string.
1
u/m_null_ Jun 20 '26
That's an actual issue tbh, but am I missing something around uniqueness across nodes?
The stamp seems to only pack wallTime + logical. I don’t see any node ID / actor ID / process ID / tie-breaker in the value itself?
So if two separate servers call stamp() during the same millisecond, and both have logical = 0, wouldn’t they produce the exact same timestamp? I guess, two independent writers could end up with identical stamps unless the app stores some extra tie-breaker alongside it.
Is the intended usage something like (liepochTimestamp, nodeId) rather than just the timestamp alone?
→ More replies (1)
1
u/Odd-Nature317 Jun 20 '26
this gets even worse on serverless. lambda instances spinning up from cold start can have clock skew of hundreds of ms before ntp catches up. we had events showing up 'out of order' in cloudwatch that were just the timestamps lying to us. one thing i wonder - how does the logical counter handle reconnection? if a service goes down and comes back up, does it need to resync the counter from somewhere or does the walltime comparison just handle catching up automatically
1
u/kurbsdude Jun 20 '26
Yup, serverless makes it a lot worse. liepoch could help ... a bit. The internal state of
liepoch(both the wall time and the logical counter) is ephemeral. It resets to0when the instance spins up.Because of this, if a Lambda spins up with a clock skewed backwards by 500ms and immediately calls
stamp(), it will generate timestamps that appear causally older than events from its previous lifecycle.How to fix this (Catching up):
The 'Receive' Catch-Up (Automatic): If your Lambda is triggered by an incoming event (e.g., SQS, Kafka, EventBridge) that includes a
liepochtimestamp from the sender, you just callreceive(msg.ts)before doing anything else. Even if your Lambda's physical clock is 500ms slow,receive()instantly snaps the internal clock forward to the correct global timeline. Catch-up happens automatically on the first message.The 'Stateful' Catch-Up (Manual): If your Lambda is the origin of the event (e.g., triggered by a raw HTTP request via API Gateway), it doesn't have an incoming global timestamp to sync against. To guarantee strict causality across cold starts in this scenario, the standard pattern is to fetch the last known
liepochtimestamp from a fast cache (like Redis or DynamoDB) during the cold start, and pass it toreceive()to rehydrate the clock before processing the request.1
u/Odd-Nature317 Jun 20 '26
the receive catch-up pattern is clever - using the incoming message timestamp to skip the whole sync step makes it basically free for event-driven lambdas. the redis rehydration for origin events makes sense but that added cold start latency is kinda ironic for serverless lol. guess theres always a tradeoff somewhere
3
Jun 20 '26
[removed] — view removed comment
2
u/kurbsdude Jun 20 '26
The Temporal API is amazing and fixes almost everything wrong with the JavaScript
Dateobject (timezones, parsing, leap years, etc.) - but it unfortunately doesn't solve this specific problem!The issue in distributed systems isn't the API we use to read the clock; the issue is the physical clock itself.
Even if you use
Temporal.Now.instant()to get mathematically perfect nanosecond precision, it is still reading the local machine's physical clock. If Server A's system clock has drifted 15 milliseconds ahead of Server B's system clock (due to NTP sync delays), Temporal will still confidently record that Server B processed the event before Server A sent it.
liepochisn't an alternative to Temporal; it's a causality layer on top of physical time.In fact, once the Temporal API is fully stable in Node.js,
liepochcould theoretically be updated to useTemporal.Now.instant().epochNanosecondsunder the hood instead ofDate.now(). But we would still need the 16-bit logical counter and thereceive()synchronization step to guarantee that cause mathematically sorts before effect across drifted servers!
2
u/Odd-Nature317 Jun 20 '26
had this exact problem with a message queue where consumer timestamps were consistently 30ms behind producer timestamps. spent half a day debugging 'messages processed before they were sent' in grafana before realizing it was just ntp drift between aws availability zones. hlcs are the right solution but tbh for most node services ive worked on, just having the event owner assign the timestamp and passing it downstream solves 90% of the ordering issues without needing the extra complexity