# Estimating server time When a client schedules an action against a server clock, its own clock needs a reliable relationship to that clock. Estimate the difference, then calculate server time whenever you need it. Neither approach here changes the operating-system clock. This guide covers the reusable measurement, averaging and Kalman algorithms. Your API's guide specifies the time endpoint, response field, timestamp units and how to use the estimate. For Handy REST, see [clock setup and playback timing](https://links.handyfeeling.com/docs-handy-rest-api-v3#keep-playback-synchronized). ## Choose an approach | Approach | What it retains | Suitable use | | --- | --- | --- | | Trimmed averaging | A mean clock offset, held until refreshed. | Short, stable sessions or a straightforward implementation. | | Offset-and-drift Kalman estimation | Clock offset, its rate of change, and uncertainty. | Ongoing media or interactive sessions where relative clock drift matters. | Both use repeated server-time measurements. Averaging removes a chosen number of slow observations before calculating the mean. Kalman updates its model from each observation, gives delayed measurements less influence, and predicts between measurements. One observation initializes an offset; learning drift requires observations separated in time. The reference implementations below specify both approaches completely. Their constants and sampling choices are client implementation choices, rather than API parameters or accuracy guarantees. ## Measure the clock offset Record client time immediately before sending a time request and immediately after receiving its response. Read the server timestamp according to the selected API's response contract. ```text rtd_ms = received_at_ms - sent_at_ms server_at_receipt_ms = server_timestamp_ms + rtd_ms / 2 offset_sample_ms = server_at_receipt_ms - client_time_at_receipt_ms ``` The observation belongs to the **response-receipt instant**. A positive offset means the server is ahead of the client. For example, with client send time `1000`, receipt time `1020`, and server timestamp `1022`, the RTT is `20 ms`, estimated server time at receipt is `1032`, and the offset sample is `12 ms`. The half-RTT adjustment approximates travel time. A single server timestamp cannot identify unequal outbound/return delays or isolate server processing and timestamp-capture delays. A stable estimate can therefore retain a systematic error. Filter covariance is not an end-to-end accuracy bound. ### Keep the clock basis consistent | Approach | Client clock basis | | --- | --- | | Averaging | Epoch time in milliseconds for send, receipt and subsequent estimates. | | Kalman | A monotonic clock in milliseconds plus a fixed epoch anchor. Use monotonic elapsed time for RTT and state prediction. | For Kalman, capture `anchor_ms = epoch_now_ms - monotonic_now_ms` once when creating the model. At monotonic time `m`, the anchored client time is `anchor_ms + m`. In a browser, these clocks are `Date.now()` and `performance.now()` respectively. Obtain the two readings close together; repeat collection if execution was suspended between them. The Kalman sample is therefore `server_timestamp_ms + rtd_ms / 2 - (anchor_ms + received_mono_ms)`. Do not subtract an epoch timestamp directly from an unanchored monotonic reading. Discard failed requests, missing/nonfinite timestamps and negative RTTs. Process requests sequentially and observations in receipt order. Reject a batch spanning a clock discontinuity. Keep fractional milliseconds internally and round only the final server-time result. ## Trimmed averaging 1. Collect successful offset/RTT pairs on the same epoch clock basis. 2. Sort by RTT, ascending. Remove `drop_slowest` observations from the end, including none when the value is zero. This trims by delay, rather than by offset magnitude. 3. Require at least one retained observation, then calculate the arithmetic mean of their offsets. 4. Until the next successful refresh, estimate `epoch_now_ms + mean_offset_ms`. Set `drop_slowest = 0` for ordinary averaging without trimming. One concrete starting configuration collects 30 requests and trims the six slowest valid observations. These counts are configurable. Apply trimming to the observations actually obtained; if too few remain, fail the refresh and retain the previous valid estimate subject to its freshness policy. Do not update the saved mean while the batch is still being collected. For offsets/RTTs `(12,20)`, `(14,22)` and `(90,200)`, dropping the slowest observation leaves a mean offset of `13 ms`. At client epoch time `5000 ms`, estimated server time is `5013 ms`. ## Offset-and-drift Kalman model This section specifies a two-state offset-and-drift model, including its initialization and noise formulas. The state at the last accepted receipt time is `[offset, drift]`. Offset is in milliseconds; drift is in milliseconds per second. Drift multiplied by `1000` gives parts per million: `0.02 ms/s` is `20 ppm`, which accumulates `72 ms` in an hour if left uncompensated. The covariance is symmetric: `P = [[p00,p01],[p01,p11]]`. Its units are `ms²`, `ms²/s`, and `ms²/s²` respectively. For elapsed time `dt` in **seconds**, predict: ```text offset_prior = offset + dt * drift drift_prior = drift A = p00 + 2*dt*p01 + dt²*p11 + 0.01*dt + 0.000001*dt³/3 B = p01 + dt*p11 + 0.000001*dt²/2 C = p11 + 0.000001*dt ``` This uses `F = [[1,dt],[0,1]]` and `H = [1,0]`. The process-noise rates are `0.01 ms²/s` for offset and `0.000001 ms²/s³` for drift. With observed offset `z` and measured RTT, update: ```text R = max(1, (rtd_ms / 2)²) S = A + R k_offset = A / S k_drift = B / S residual = z - offset_prior offset = offset_prior + k_offset * residual drift = drift_prior + k_drift * residual p00 = (1 - k_offset) * A p01 = (1 - k_offset) * B p11 = max(0, C - k_drift * B) ``` Use the unmodified predicted `A`, `B` and `C` throughout the update. `R` is a variance in `ms²`; its minimum is `1 ms²`, rather than an extra term added to the RTT variance. For the first valid observation, initialize offset to `z`, drift to zero, `p00 = max(10000,R)`, `p01 = 0`, and `p11 = 0.01`. Apply the measurement update at that same instant with `dt = 0`. Later observations use the actual receipt-to-receipt elapsed time. Feed consecutive observations individually, without averaging a batch first. To estimate at a later monotonic time `m`, calculate `anchor_ms + m + offset + dt*drift`, where `dt` runs from the last accepted observation to `m`. Prediction for a read must not advance or alter the stored observation state. This model weights valid delayed observations; it does not trim them or apply an additional residual-rejection gate. ## Executable reference The following Python uses only the standard library. The state and equations above can be translated directly to another language. Inputs are numeric milliseconds; transport, clocks, sampling and freshness checks belong to the caller. Both implementations reject invalid input without replacing an existing estimate. ```python from math import floor, fsum, isfinite def require_finite(*values): if any(isinstance(v, bool) or not isinstance(v, (int, float)) or not isfinite(v) for v in values): raise ValueError("Expected finite numeric clock values") def offset_sample(server_ms, client_at_receipt_ms, rtd_ms): require_finite(server_ms, client_at_receipt_ms, rtd_ms) if rtd_ms < 0: raise ValueError("Negative round-trip delay") return server_ms + rtd_ms / 2 - client_at_receipt_ms def trimmed_average(samples, drop_slowest): # samples contains (offset_ms, rtd_ms) pairs from one valid batch. if (isinstance(drop_slowest, bool) or not isinstance(drop_slowest, int) or not 0 <= drop_slowest < len(samples)): raise ValueError("Trimming must leave at least one observation") for offset, rtd in samples: require_finite(offset, rtd) if rtd < 0: raise ValueError("Negative round-trip delay") retained = sorted(samples, key=lambda pair: pair[1])[:len(samples) - drop_slowest] return fsum(pair[0] for pair in retained) / len(retained) class OffsetDriftKalman: def __init__(self, anchor_ms): require_finite(anchor_ms) self.anchor_ms = anchor_ms self.last_mono_ms = None self.offset = self.drift = 0.0 self.p00 = self.p01 = self.p11 = 0.0 def observe(self, mono_ms, z, rtd_ms): require_finite(mono_ms, z, rtd_ms) if mono_ms < 0 or rtd_ms < 0: raise ValueError("Negative monotonic time or RTT") if self.last_mono_ms is not None and mono_ms < self.last_mono_ms: raise ValueError("Out-of-order observation") R = max(1.0, (rtd_ms / 2) ** 2) if self.last_mono_ms is None: offset_prior, drift_prior = z, 0.0 A, B, C = max(10000.0, R), 0.0, 0.01 else: dt = (mono_ms - self.last_mono_ms) / 1000 offset_prior = self.offset + dt * self.drift drift_prior = self.drift A = (self.p00 + 2 * dt * self.p01 + dt**2 * self.p11 + 0.01 * dt + 0.000001 * dt**3 / 3) B = self.p01 + dt * self.p11 + 0.000001 * dt**2 / 2 C = self.p11 + 0.000001 * dt S = A + R k_offset, k_drift = A / S, B / S residual = z - offset_prior self.offset = offset_prior + k_offset * residual self.drift = drift_prior + k_drift * residual self.p00 = (1 - k_offset) * A self.p01 = (1 - k_offset) * B self.p11 = max(0.0, C - k_drift * B) self.last_mono_ms = mono_ms def estimate(self, mono_ms): require_finite(mono_ms) if mono_ms < 0: raise ValueError("Negative monotonic time") if self.last_mono_ms is None: return None if mono_ms < self.last_mono_ms: raise ValueError("Estimate precedes the observation state") dt = (mono_ms - self.last_mono_ms) / 1000 server_ms = self.anchor_ms + mono_ms + self.offset + dt * self.drift return floor(server_ms + 0.5) ``` For averaging, replace the saved mean only after `trimmed_average` succeeds; return `floor(epoch_now_ms + mean_offset_ms + 0.5)`. For Kalman, compute `z = offset_sample(server_ms, anchor_ms + received_mono_ms, rtd_ms)`, call `observe(received_mono_ms, z, rtd_ms)`, then call `estimate(monotonic_now_ms)` as needed. `estimate` makes no network request. A return value of `None` means that initialization is still required. ### Worked Kalman example Use these two accepted offset observations; `mono_ms` records their receipt times: ```json { "anchor_ms": 1700000000000, "samples": [ {"mono_ms": 1000, "offset_ms": 12, "rtd_ms": 20}, {"mono_ms": 11000, "offset_ms": 14, "rtd_ms": 22} ], "estimate_at_mono_ms": 16000, "expected_server_time_ms": 1700000016013 } ``` After the first update, offset is `12 ms`, drift is zero, and `p00` is approximately `99.009901 ms²`. After the second, offset is approximately `12.9055 ms` and drift is approximately `0.000905 ms/s`. Predict five seconds beyond that observation and round the final server timestamp to obtain `1700000016013`. Drift is still being learned; it is not simply the difference between two offset samples. ## Sampling, freshness and recovery Obtain a successful initial estimate before scheduling synchronized actions. Collect fresh measurements explicitly: creating a model does not start polling, and reading an estimate does not refresh it. Keep the last successful measurement time separately and choose an application-specific maximum age. Report an unavailable or stale estimate instead of silently using an arbitrarily old model. A useful scheduling example is frequent sampling during a 15-second warm-up, about two seconds after each completed attempt, followed by a 15-second interval with ±20% jitter. After failures, increase the delay up to a chosen cap, such as two minutes. These are scheduling choices. Averaging batches contain several requests, so account for their larger request budget. Do not overlap attempts or issue a catch-up burst after a suspended tab resumes. Monitor the relationship `epoch_now_ms - monotonic_now_ms`. A reference client can reset when that relationship changes by more than `1000 ms`, with stricter application checks when needed. Reject observations spanning a detected jump, invalidate the old offset/model, capture a new anchor and require fresh measurements. For averaging, also discard a batch whose epoch timing no longer agrees with its monotonic elapsed time. A smaller clock change can still matter to the application's accuracy requirement. On wake, a network change or an unexpected playback discrepancy, collect fresh samples and repeat warm-up. Distinguish a connection change from a clock-origin change: a still-valid model can be retained while resampling after a network change; a changed monotonic origin or epoch anchor requires resetting it. Do not restore cached state into a new clock context without validating origin, anchor and age. Associate each in-flight request with the clock context/model that issued it. After a reset, discard late responses from that old context. Collect Kalman observations into a temporary model if a multi-request refresh must succeed atomically before replacing the active model. Playback actions such as seeking do not themselves change the clock relationship. Evaluate estimated server time at the same instant as the media position. Keep API-specific playback correction, device-clock synchronization and script timeline positions separate from this client/server estimate.