How to synchronize a timer between the server and all its clients over the internet (down to the millisecond)

I’m writing a tiny online game where every event is kept track of by the time it occurred. Whenever an event happens the current clock (number of milliseconds since the game started) is polled from, and that value dictates exactly the millisecond that that event happened (this allows to server to recreate the entire game world using only these events and the times they happened)

In order to get the server’s recreation of the world to line up as closely as possible with what the players see, I want both the server and the clients to run on the same EXACT timer, as close as possible, preferably down to the millisecond.

What’s the best way to go about this? Currently my two ideas are:

  1. Have the server send a date (in milliseconds) to each client, and have them take that date and determine how many milliseconds ago the server’s clock was started, and then they can start their own clock that many milliseconds in the past.

However, I don’t believe this is reliable since it relies on the client’s clock having the exact same date as the server, which is completely unlikely.

  1. Have the server keep track of all the clients’ pings (latency) and send a latency-compensated timestamp to tell each client what the current time is.

However, this has the flaw of almost always being at least ~5 milliseconds off, since the latency fluctuates constantly.


And both of these solutions suffer from the fact that computer clocks are NOT accurate, and I will need to constantly re-sync the timers to keep them from drifting too far apart…

All of this leads me to believe that there must be some better way to go about this. Any tips or advices are greatly appreciated.