skip to content

A meditation app's offline sleep-session events arrive days later from phones whose clocks are wrong; how should the client timestamp events so the server can place them correctly?

level: seniorimportance: nice to knowfreq 35%

answer

  1. upload time is not event time
  2. the wall clock can jump
  3. a monotonic count since boot
  4. send the phone's now with the batch
  5. keep the local time-zone offset

basics

~20 s

Record each event's device wall time plus a monotonic time since boot. At upload, send the phone's current times; the server places same-boot events by elapsed time and corrects the rest by the clock offset, flagged as less certain.

solid answer

~50 s

Upload time is useless as event time here: a session played at 23:40 in airplane mode may arrive two days later. The phone's wall clock alone is no better, because users set clocks by hand, travel across time zones, and clocks jump when they re-sync. So each event records its wall time, a monotonic elapsed time since boot, a boot id and the local time-zone offset. Each upload carries the phone's wall time and monotonic time at sending. For events from the current boot, the server places each one at its receive time minus the monotonic time elapsed since the event, which no clock change can disturb. Events from an earlier boot fall back to device time plus the offset between the server's clock and the phone's, and are flagged. The raw device time is kept too.

code

http · 14 lines
http
POST /v1/events HTTP/1.1
Content-Type: application/json

{"sent_wall": "2026-10-10T10:15:00Z", "sent_mono_ms": 124500000, "boot_id": "7c1e",
 "events": [
  {"id": "5b0e7d2a-1c4f-4e3b-9a6d-8f2c1b7e0a95", "seq": 912, "name": "session_completed",
   "wall": "2026-10-09T02:40:00+02:00", "mono_ms": 3600000, "boot_id": "7c1e",
   "session_id": "s-0419", "props": {"kind": "sleep_story", "minutes": 42}}
 ]}

HTTP/1.1 200 OK
Content-Type: application/json

{"results": [{"id": "5b0e7d2a-1c4f-4e3b-9a6d-8f2c1b7e0a95", "status": "accepted"}]}

go deeper

for a junior

Recall that a phone's clock can be wrong and that events uploaded later must carry the time they happened, not the upload time.

for a middle

Explain the difference between wall-clock and monotonic time, and what the client records so the server can correct an event's time.

for a senior

Work through the same-boot correction and the flagged fallback, including reboots, clock changes before upload and the local night for streaks.

for a principal

Decide which corrected time every report uses and how confidence flags are surfaced, so teams do not each reinvent timestamp rules.

## Three clocks, none right on its own A sleep session played at 23:40 in airplane mode produces `session_started` and `session_completed`, which may reach the server two days later. Three candidate times exist, and each fails somewhere: | Time source | Survives a long offline wait | Survives a wrong or changed clock | Survives a reboot | |---|---|---|---| | Server receive time | no, it is the upload moment, days late | yes | yes | | Device wall clock | yes | no | yes | | Monotonic time since boot | yes | yes | no, it restarts at boot | - The **wall clock** is what the user sees. It can be set wrong by hand, and it can jump forward or backward when the phone re-syncs with network time; the UUID specification itself warns that a system clock can move backward through manual adjustment or time-sync corrections. - A **monotonic clock** counts elapsed time since boot and ignores every wall-clock change, but restarts from zero after a reboot. For a sleep app, use the monotonic clock that keeps counting while the device sleeps; some monotonic clocks pause in deep sleep, which would shrink an overnight gap. ## What the client records Each event stores: - `wall`: the device wall time when recorded, with its local time-zone offset; - `mono_ms`: the monotonic time when recorded; - `boot_id`: an identifier of the current boot, so the server knows whether two monotonic readings are comparable. If the platform offers none, a per-process id is a safe substitute; it only sends more events down the fallback path. Each upload adds, once per batch, the phone's `sent_wall`, `sent_mono_ms` and current `boot_id` at the moment of sending. These fields belong in the envelope the shared pipeline adds, not in each feature's code, so every event in the app gets them the same way. The client does not try to correct its own clock: it has no trustworthy reference while offline, and a correction applied on the phone would hide the raw evidence the server needs. ## What the server computes 1. **Same boot**: the event's `boot_id` matches the batch's. Event time = server receive time − (`sent_mono_ms` − `mono_ms`). Neither the wrong wall clock nor any change to it enters the result. 2. **Earlier boot**: the monotonic readings are not comparable. Offset = server receive time − `sent_wall`; event time = `wall` + offset. This is right only if the clock was not changed between the event and the upload, so the event is flagged as lower confidence. 3. **Network delay** of the upload itself is usually small next to the errors being corrected; half the request's round-trip time can be subtracted if it matters. 4. **Keep all three**: raw device time, corrected time and receive time are stored, so a later fix can be re-run. ## A worked example The phone's clock is three hours fast. A session completes at a real 21:40 UTC on 8 October; the phone records `wall` 00:40 UTC on 9 October and `mono_ms` 3,600,000. The upload reaches the server at 07:15 UTC on 10 October with `sent_mono_ms` 124,500,000 from the same boot. - Elapsed = 124,500,000 − 3,600,000 = 120,900,000 ms = 33 h 35 min. - Event time = 07:15 on 10 October − 33 h 35 min = **21:40 UTC on 8 October**, correct to the minute. - The fallback gives the same answer here: `sent_wall` reads 10:15, the offset is −3 h, and 00:40 on 9 October − 3 h = 21:40 on 8 October, because nobody changed the clock in between. ## Local time and order - A streak or a "nights per week" metric needs the user's **local night**, not a UTC date: 23:40 at UTC+2 is 21:40 UTC, and the time-zone offset recorded with the event is what lets the server assign it to the right night after the user travels. - For **order** within one install, use the per-install sequence number, not the time inside a time-ordered UUID; that time came from the same unreliable clock. - **Sessions** are defined on the client: a session id minted at start, ended by an explicit stop or an inactivity timeout measured on the monotonic clock, so a clock change at 03:00 cannot split or merge one.

  • Why not simply correct every event with the clock offset measured at upload?
    That offset is right only if the phone's clock did not change between the event and the upload. A user who fixes a wrong clock, or a network time sync, in between shifts every queued event by the size of the jump. Within one boot the monotonic elapsed time is immune to that, so it is the primary correction and the offset is the fallback.
  • How should the client define a session when a sleep story plays for hours with the screen off?
    Define it explicitly in the schema instead of inheriting a foreground-based default: here a session might run from play to stop, with an inactivity timeout measured on the monotonic clock so a clock change at night cannot split or merge it. The session id is minted on the device and stamped on every event in it.

A traveller's wristwatch may be set wrong, but the stopwatch started at the event cannot be: "it happened 33 hours before I reached the desk" is exact, as long as the stopwatch was not reset on the way.

  • Use the time the server receives an event as the event's time.
  • The phone's clock is network-synced, so its timestamps are always right.
  • A time-ordered UUID gives a trustworthy event time and order.
  • A UTC timestamp alone tells which local night a session belonged to.
  • Monotonic time survives a reboot, so it can order every event.