Search code examples
httptimehttp-headersutc

Calculate time offset using HTTP header `date`


I have a program that needs to do something exactly every hour. The catch is that the time needs to be relative to the remote server, which is not synchronised with a time server and is, in fact, about 6 seconds ahead (!). There is no way for me to change that server.

All I have, is access to the HEAD headers of the web server, which have a handy field date (that's how I found out about the discrepancy).

Question: regardless of the language (I use nodeJS, but that's not the point), what would you do to calculate a precise offset between my server and the remote server?

I am especially worried about network latency: I have the following variables:

  • Local server time
  • Time when request was sent
  • Time when the response with the Date header arrived
  • Remote server time

However, the remote server time was generated when the server received the request -- something that might have taken up to 1 second. And, the time when the response arrived needs to take into account the time it took to receive it...

Right now I am offsetting with (Time request was sent - Time response arrived) / 2. However, it feels lame.

Is there a better, established way to deal with this?


Solution

  • Hmm, i know this kind of problem, though i never had the limitation of not being able to change one of the 2 'actors'. I would say this approximation (Time request was sent - Time response arrived) / 2 feels ok. If you care more about it you could experiment with the approximation in a 'benchmark' kind of way:

    • don't make one synchronization request but make 10 in sequence, then eliminate the first 3 offsets and the last 3 offsets and average the remaining 4
    • or:
    • don't make one synchronization request but make a burst of 10 in 10 different threads, this should theoretically eliminate the client side (local side) time it takes to create the request and should block (if it blocks) on the server side (or remote side in your case). But this would involve some math and i think it's too much trouble for value

    P.S. the number 10 is arbitrary (and hopefully the remote server doesn't ban/block you for making too many requests :)