Home > OS >  Java Instant.toEpochMilli() & Javascript Date.now() not in sync
Java Instant.toEpochMilli() & Javascript Date.now() not in sync

Time:06-29

I am trying to collect performance metrics on the client for streaming pricing data coming from a server process over websockets. The server is written in Java and the client is an Angular UI application. Both the server and the client are written in-house and are within the same organisation's network. The data goes stale in 250 ms and we measure several parameters one of which is network lag.

The server stamps the sentAtTime on the message header just before it leaves the server using Java's Instant.toEpochMilli(). The client records the receivedAtTime using Javascript's Date.now() as soon as it picks the message up.

I then calculate time over the wire as NetworkLag = receivedAtTime - sentAtTime

Surprisingly the lag is negative sometimes upto -30 ms which is baffling me. I have checked that the maths isn't wrong and I also get positive lag values. The only explanation I can think of is that the clocks on the server and client are somehow are not in sync. Have others seen something like this and what are the steps I could take to remediate the situation.

CodePudding user response:

There is a way to figure out the time difference between server and client despite the effects of network lag. Check out how NTP works. It synchronizes system clocks over the laggy internet and intends to resolve down to milliseconds deviation.

From Wikipedia:

NTP is intended to synchronize all participating computers to within a few milliseconds of Coordinated Universal Time (UTC). It uses the intersection algorithm, a modified version of Marzullo's algorithm, to select accurate time servers and is designed to mitigate the effects of variable network latency.

  • Related