Closest-Timestamp Field Telemetry Service
Hard · System Design · Software Engineer · Technical Screen
Prompt
Field equipment carried or operated by public-safety personnel—such as wearable cameras, sensor-equipped holsters, and patrol-vehicle units—emits periodic operational telemetry snapshots (for example, GPS coordinates, battery percentage, recording flag, and holster state). Because personnel routinely work in cellular dead zones and upload buffered batches hours or days later over station Wi-Fi or charging docks, snapshots often arrive out of chronological sequence, delayed by days, or repeated across network retries.
Design a backend platform that ingests this telemetry stream and enables investigative and auditing tools to look up an officer's operational state closest to any historical incident timestamp.
Functional goals:
- Telemetry ingestion: Accept status events carrying
officer_id,device_id,device_timestamp, and an extensible status payload. - Closest-timestamp lookup: Given
officer_idand a target query timestampT_target, return the single retained snapshot minimizing|device_timestamp - T_target|. When two snapshots sit at the exact same temporal distance fromT_target(|t_a - T_target| == |t_b - T_target|), break the tie deterministically by returning the earlier snapshot (min(t_a, t_b)). - Retry deduplication: Process repeated uploads caused by client or transport retries idempotently so duplicate records do not accumulate.
- Sliding retention: Automatically expire and purge telemetry older than a configurable retention window (such as 90 days).
Illustrative lookup behavior:
Suppose officer off-204 (cam-910) has three retained snapshots on 2026-09-15 at 08:12:05.000Z, 08:12:10.000Z, and 08:12:15.000Z (even if the 08:12:05.000Z snapshot arrived hours after the later two):
- A lookup at
T_target = 2026-09-15T08:12:12.200Zcompares08:12:10.000Z(2,200 msprior) against08:12:15.000Z(2,800 msafter) and returns the08:12:10.000Zsnapshot. - A lookup at
T_target = 2026-09-15T08:12:12.500Zsees both neighbors2,500 msaway and returns08:12:10.000Zunder the earlier-timestamp tie-breaker.
Scale & operational constraints:
- Write throughput:
100,000concurrently active officers emitting one snapshot every5seconds (20,000writes/sec sustained peak), with an average event size of500bytes. - Query latency:
p99 < 50 msfor closest-timestamp lookups. - Durability & delayed uploads: Acknowledged writes must be stored durably, and late telemetry arriving up to
7days after capture must fold accurately into historical timelines without corrupting chronological ordering.
Scope & Expectations
- Specify the ingestion and query API contracts, select an appropriate storage engine, and justify the primary, partition, and clustering keys.
- Walk through the exact query mechanics that resolve the closest timestamp and break ties within
p99 < 50 mswithout scanning broad time ranges. - Explain how the write path handles out-of-order and up-to-7-day-late uploads, suppresses retry duplicates at high throughput, and executes rolling 90-day retention drops cleanly.
- Cover drifted or reset device clocks alongside major infrastructure failure modes.
Step-by-step walkthrough
Clarify requirements and pin down edge rules
We are building a write-intensive telemetry store for wearable cameras, sensor holsters, and patrol-car hardware. Because units lose radio coverage on patrol and flush queued events hours or days later with transport retries, events arrive out of chronological order and sometimes duplicated. Investigative tools still need to look up an officer's operational snapshot closest to any historical query timestamp
T_targetwithin tens of milliseconds.Before drawing any boxes, we pin down the exact rules for ambiguous cases:
- What "nearest" means and how ties break: Distance is
|device_timestamp - T_target|at millisecond precision across all devices assigned toofficer_id.- Equidistant before/after tie: As required, if one record before
T_targetand one afterT_targethave the exact same time distance, we return the earlier record (min(t1, t2)). - Same-millisecond multi-device tie: If an officer's camera and smart holster both emit a status at the exact same millisecond
t, neither is earlier. To keep forensic queries 100% deterministic, we break same-millisecond ties by smallestdevice_id, then smallest per-device sequence counterseq.
- Equidistant before/after tie: As required, if one record before
- Event identity and idempotency: An operation is idempotent if performing it once or repeating it ten times leaves the exact same stored result. Each record's natural identity is
(officer_id, device_id, device_timestamp, seq), whereseqis a monotonically increasing counter assigned by the device (0if a legacy device omits it). Storing records under this primary key makes network retries harmless overwrites of identical data, whileseqprevents two genuinely different events emitted after a clock reset from overwriting each other. - Durability vs. query visibility: Returning
200 OKto a device means durably stored (written across multiple replicas on disk so the device can safely erase its local flash buffer), not necessarily indexed for search in the same millisecond. Under normal load a record becomes queryable within 1–2 seconds; every query response includes acomplete_throughserver timestamp so an auditor knows up to which upload moment the results are complete. - Late data and rolling 90-day retention: Records arriving up to 7 days late are inserted cleanly into historical timestamp order. Retention is measured on
device_timestamp: queries hide records older thannow - 90 daysimmediately, and expired storage buckets are dropped in bulk once a day. However, if a record looks older than 90 days only because the device's clock reset to 1970, we quarantine it rather than rejecting it so recent evidence is not destroyed.
Summary of requirements
- Functional: (1) Idempotent batch ingestion of officer telemetry, (2) nearest-timestamp lookup with deterministic tie-breaking, (3) deduplication and clock-skew flagging, and (4) automatic 90-day rolling retention.
- Non-functional: Peak steady rate of 20,000 writes/s (500 bytes/record) plus reconnect bursts; p99 read latency < 50 ms (meaning 99 out of 100 queries finish in under 50 ms); zero loss of acknowledged data; forensic-grade read correctness (during a severe outage, returning an explicit error is safer than returning an incomplete answer).
- What "nearest" means and how ties break: Distance is
Back-of-the-envelope capacity planning
Let us turn the prompt's numbers into concrete throughput, memory, and disk budgets so the hardware constraints guide our architecture:
Steady peak writes 100,000 active officers / 5 s = 20,000 records/s Ingress bandwidth 20,000 records/s x 500 B = 10 MB/s (80 Mbit/s) Daily volume (24/7 upper bound, 100k active across shifts) 20,000/s x 86,400 s/day = 1.73 billion records/day (~864 GB/day) 90-day retention 864 GB/day x 90 days = 77.8 TB raw (~233 TB with 3 replicas, (24/7 upper bound) or ~85-100 TB after LZ4 compression) (Single 100k roster on 8 h shifts = ~26 TB raw, ~78 TB x3 before compression) Cluster node count at ~3 TB per storage node = ~25-60 nodes (fast node rebuilds) Per-officer volume 86,400 s / 5 s = 17,280 records/day = 8.64 MB per officer-day (max) 8.64 MB x 30 days = 259 MB per officer-month Shift-change burst 20,000 cameras dock at once, each uploading 7.5 h of offline backlog: 7.5 h x 3,600 s / 5 s = 5,400 records/device -> 108 M records uploaded over 30 min (1,800 s) = +60,000 records/s (80,000/s total = 4x) If DB writers drain at 50,000/s: queue grows at (80k - 50k) = 30k/s -> peaks at 54 M records after 30 min worst visibility lag at burst peak = 54 M / 50k/s = 1,080 s (18 min) queue drains completely after burst = 54 M / (50k - 20k)/s = 1,800 s (30 min) Durable ingest log 3 days buffer x 10 MB/s x 3 replicas = ~7.8 TB disk Query load forensic/audit apps <= 200 queries/s = ~400-800 single-partition reads/sFour architectural decisions fall straight out of this math:
- Writes outnumber reads by ~50x–100x, and late uploads scatter inserts across the past 7 days. We need a storage engine where out-of-order historical inserts are sequential appends rather than random disk-page rewrites.
- Shift-change bursts hit 4x steady load (
80,000/s). Placing a replicated append-only log (such as Apache Kafka) in front of the database lets us acknowledge device uploads immediately while sizing database writers for50,000/sinstead of paying for peak-sized database hardware 24/7. - One officer-month can reach 259 MB, which exceeds the healthy single-partition limit (~100 MB) in distributed wide-column databases. Bucketing each officer's rows by UTC day (
<= 8.64 MB) keeps every partition small and balanced. - Purging 1.73 billion records/day row by row would cripple storage. Grouping data into coarse time-bucket tables lets us drop an entire expired day or week in milliseconds with zero per-row delete traffic.
API design
Devices connect over mutual TLS (mTLS)—an encrypted connection where both the server and the hardware device present cryptographic certificates, proving the upload genuinely comes from an agency-issued camera or holster.
1. Batch Ingestion Endpoint (Device -> Service)
POST /v1/status-records:batch Headers: X-Device-Clock: 2026-09-20T16:40:02.123Z # Device's wall clock right when sending this HTTP call Request body (up to 1,000 records per batch): { "records": [ { "officer_id": "off-204", "device_id": "cam-910", "device_timestamp": "2026-09-15T08:12:10.000Z", "seq": 412085, "boot_id": "b-07", "uptime_ms": 9420000, "payload": {"lat": 39.74, "lon": -104.99, "battery": 74, "recording": true, "holster": "holstered"} } ] } Response 200 OK: { "server_time": "2026-09-20T16:40:02.210Z", "results": [ {"index": 0, "event_id": "7d1a4c...", "status": "accepted"}, {"index": 1, "event_id": "28f3b9...", "status": "rejected", "reason": "older_than_retention"} ] }- Safe retries: Repeating a batch returns
"accepted"again for already-ingested items, so if a cellular connection drops before the response arrives, the device simply resends the batch and clears its local flash buffer once it sees"accepted". - Authorization check: The ingest service verifies that the mTLS certificate matches
device_idand thatdevice_idwas assigned toofficer_id, preventing a compromised device from injecting status records into another officer's timeline.
2. Nearest-Timestamp & Audit Query Endpoints (Forensic App -> Service)
Forensic tools authenticate with user credentials and Role-Based Access Control (RBAC) (rules restricting which investigators can view which agency or case), and every query writes an immutable audit log entry:
GET /v1/officers/{officer_id}/status:nearest?t=2026-09-15T08:12:12.200Z&max_distance=10m Response 200 OK: { "record": { "officer_id": "off-204", "device_id": "cam-910", "device_timestamp": "2026-09-15T08:12:10.000Z", "seq": 412085, "time_quality": "device", "clock_error_bound_ms": 180, "payload": {"lat": 39.74, "lon": -104.99, "battery": 74, "recording": true} }, "distance_ms": 2200, "side": "before", # "before" | "after" | "exact" "complete_through": "2026-09-20T16:39:59.800Z", # All uploads acked before this time are indexed "source": "hot" # "hot" (<= 90 days) | "cold" (archived) }max_distanceguard: Returns404 Not Foundif no retained record exists—or if the closest record is farther away thanmax_distance(optional). Withoutmax_distance, querying an incident at08:12for an off-duty officer could misleadingly return a status from Friday afternoon three days earlier.- Companion endpoints:
GET /v1/officers/{officer_id}/status?from=...&to=...&limit=...for timeline playback around an incident, andPOST /v1/status:nearest-batchfor unit-level queries.
- Safe retries: Repeating a batch returns
Data model, storage engine, and time-bucket partitioning
Why an LSM-tree wide-column store (ScyllaDB or Apache Cassandra): Traditional relational databases store indexes in B-trees (fixed-size disk pages kept updated in place; inserting a 5-day-old timestamp means reading, modifying, and occasionally splitting old disk pages across random locations). By contrast, an LSM-tree (Log-Structured Merge-tree) database appends every incoming write sequentially to a disk commit log and inserts it into a fast in-memory sorted structure (Memtable), periodically flushing immutable sorted files (SSTables) to disk. A record from 5 days ago is just as cheap to write as a record from 5 milliseconds ago.
Inside a wide-column table, the primary key has two parts: 1. Partition key: Hashed to determine which storage nodes hold a group of rows together. 2. Clustering key: Determines the exact physical sort order of rows inside that partition on disk, allowing instant single-partition binary seeks (
<= Tor> T).Choosing the time bucket (daily vs. monthly): Partitioning on
officer_idalone would create a single ever-growing partition per officer. Adding a time bucket bounds partition size and makes retention drops cheap. How wide should the bucket be? - In sharded PostgreSQL with range-partitioned tables, monthly tables (status_2026_09) with a B-tree on(officer_id, event_ts)work reasonably well because B-trees have no per-officer partition limit—though random B-tree page I/O under 20k–80k out-of-order writes/s is heavier. - In a wide-column LSM store, one officer-month is259 MB(too big for the< 100 MBpartition guideline), whereas one officer-day is at most8.64 MB. Putting each UTC day in its own tablestatus_YYYYMMDD(~93 live tables: 90 retention days + today + 2 days ahead) keeps partitions tiny (<= 8.64 MB) and turns 90-day retention intoDROP TABLE status_20260617—avoiding tombstones (per-row delete markers in LSM-trees that waste disk and slow reads until compacted). (Note: if a cluster ever runs hundreds of other tables where Memtable per-table memory matters, you can group 7 days into weekly tablesstatus_YYYY_Wwwwith partition key(officer_id, day)—keeping the exact same 8.64 MB partitions with only ~15 live tables.)1. Telemetry table (one per UTC day of event_ts, ~93 live tables) Table: status_YYYYMMDD officer_id text -- PARTITION KEY (<= 8.64 MB per officer-day) event_ts timestamp -- CLUSTERING KEY 1 ASC (ms; device_timestamp or repaired time) device_id text -- CLUSTERING KEY 2 ASC (tie-breaker across devices) seq bigint -- CLUSTERING KEY 3 ASC (per-device counter; 0 if absent) event_id blob -- SHA-256(officer_id, device_id, raw_device_ts, seq) raw_device_ts timestamp -- Original unmodified timestamp sent by the device boot_id text -- Device boot session ID (for clock repair) time_quality text -- "device" | "skewed" | "corrected" clock_offset_ms int -- Measured (server_time - device_clock) at upload received_at timestamp -- Server ingest timestamp payload blob -- LZ4-compressed JSON/Protobuf telemetry PRIMARY KEY ((officer_id), event_ts, device_id, seq) 2. Sparse active-day index (avoids probing empty days during vacations/off-duty gaps) Table: officer_days officer_id text -- PARTITION KEY day date -- CLUSTERING KEY ASC (~93 tiny rows per officer, TTL 100 days) PRIMARY KEY ((officer_id), day) 3. Supporting tables: clock_samples ((device_id), received_at) -> offset_ms, rtt_ms, boot_id quarantine ((officer_id), received_at, event_id) -> raw record + quarantine_reasonHigh-level architecture
Field Devices (cams, holsters, vehicles) Forensic & Audit Applications | | | mTLS batch POST (cellular / Wi-Fi / dock) | HTTPS + RBAC (nearest / range) v v +-----------------------+ +-------------------------+ | Stateless Ingest API | | Stateless Query Service | | - mTLS cert check | | - Floor/ceiling planner | | - Compute event_id | | - Tie-break & cutoff | | - Clock skew check | | - Audit logger | +-----------+-----------+ +-----+-------------+-----+ | produce (ack when 2 of 3 brokers write) | | v | hot (<=90d) | cold (>90d) +-----------------------+ | v | Durable Ingest Log | | +-----------------------+ | (Kafka, 64 partitions | | | Object Storage (S3) | | keyed by officer_id, | | | Sorted Parquet files | | 3-day retention) | | | + raw upload archive | +----+-------------+----+ | +-----------^-----------+ | | | | v v v | export day + 8 +----------+ +----------------+ +-------------------------------+---+ | Store | | Raw Archive | | Wide-Column LSM Store (ScyllaDB) | | Writers | | Writer (audit |----------->| RF = 3, Quorum Reads & Writes | | (upsert) | | copy -> S3) | upserts | - status_YYYYMMDD | +----------+ +----------------+ | - officer_days, quarantine | +-----------------------------------+ Background workers: - Table Manager: creates status_(d+2), compacts closed day (d-8), exports Parquet, drops (d-91) - Clock Analyzer: tracks per-device clock drift and repairs anchored quarantine recordsLet us trace one status record from camera to queryable storage:
- Ingest & durability: The Ingest API verifies the camera's mTLS certificate, computes
event_id = SHA-256(officer_id, device_id, device_timestamp, seq), classifies clock health, and publishes the record to the Kafka partition forhash(officer_id) % 64. Once 2 of 3 log replicas persist it on disk, the API returnsaccepted. - Ordered indexing: A Store Writer consumes batches for its assigned partitions. It first upserts any newly seen
(officer_id, day)intoofficer_days, then upserts the telemetry rows into the matchingstatus_YYYYMMDDtables, and only then commits its Kafka offset. Meanwhile, a separate Raw Archive Writer streams raw batches to object storage as an immutable audit trail. - Consistent lookup: The Query Service reads from ScyllaDB using quorum consistency—with replication factor
N = 3, writes wait forW = 2replicas and reads consultR = 2replicas (R + W = 4 > 3), guaranteeing every read overlaps at least one replica that holds the latest completed write.
- Ingest & durability: The Ingest API verifies the camera's mTLS certificate, computes
Deep dive 1: Nearest-record resolution with floor and ceiling queries
A naive query scans a window like
event_ts BETWEEN T_target - 5m AND T_target + 5m, computes|event_ts - T_target|for every row, and sorts. That fails two ways: if the officer's device was offline for 20 minutes, the 5-minute window returns nothing even though a valid record sits 21 minutes away; if we widen the scan to 7 days, a single query reads ~120,000 rows and blows past our 50 ms budget.Because rows inside each
(officer_id)partition are already physically sorted by(event_ts ASC, device_id ASC, seq ASC), the closest record in all of history must be one of just two candidates: - The Floor: the latest record withevent_ts <= T_target. - The Ceiling: the earliest record withevent_ts > T_target(strictly>so an exact match atT_targetisn't fetched twice).Timeline for officer off-204 on 2026-09-15: ... ---[ 08:12:05 ]---------[ 08:12:10 ]-------------[ 08:12:15 ]--- ... ^ | ^ FLOOR | CEILING (<= T, dist 2.20s) | (> T, dist 2.80s) T_target = 08:12:12.200 Winner: FLOOR (2,200 ms < 2,800 ms). If T_target were 08:12:12.500 (2,500 ms to both): FLOOR still wins (earlier tie-breaker).Handling the subtle reverse-scan tie-breaker: For the ceiling (
event_ts > T_target), we scan forward (ASC) withLIMIT 1. Becausedevice_idandseqare stored ascending, the very first row already has the smallest(device_id, seq)! For the floor (event_ts <= T_target), we scan backward (ORDER BY event_ts DESC, device_id DESC, seq DESC). In wide-column stores like Cassandra and ScyllaDB, a reverse scan inverts all clustering columns, so if two devices emitted a status at the exact same floor millisecondt_floor, the descending scan visits the largest(device_id, seq)first. ReadingLIMIT 8handles simultaneous multi-device ticks in one round trip, and if all 8 rows sharet_floor(e.g., after a pathological burst), a 1-row forward point read atevent_ts = t_floorguarantees the exact tie-break winner:-- 1. Ceiling in day d: forward scan returns smallest (device_id, seq) immediately SELECT * FROM status_20260915 WHERE officer_id = ? AND event_ts > ? ORDER BY event_ts ASC, device_id ASC, seq ASC LIMIT 1; -- 2. Floor in day d: reverse scan reads up to 8 rows at the newest timestamp <= T_target SELECT * FROM status_20260915 WHERE officer_id = ? AND event_ts <= ? ORDER BY event_ts DESC, device_id DESC, seq DESC LIMIT 8; -- 3. Rare fallback ONLY if all 8 floor rows had identical event_ts = t_floor: SELECT * FROM status_20260915 WHERE officer_id = ? AND event_ts = ? ORDER BY event_ts ASC, device_id ASC, seq ASC LIMIT 1;Crossing day boundaries without scanning empty days: What if
T_targetis00:00:02on Sep 15, before the officer's first Sep 15 record (so the floor lives on Sep 14—or Sep 07 if the officer was on vacation)? Queryingofficer_daystells us the exact previous and next active days in one tiny read:def pick_floor_from_desc(rows, store, day, officer_id): """Pick the record with newest event_ts and smallest (device_id, seq).""" if not rows: return None floor_ts = rows[0]["event_ts"] # If all 8 reverse-ordered rows share floor_ts, a 9th row could have a smaller device_id/seq. if len(rows) == 8 and rows[-1]["event_ts"] == floor_ts: return store.first_at_exact_ts(day, officer_id, floor_ts) best = rows[0] for row in rows[1:]: if row["event_ts"] != floor_ts: break if (row["device_id"], row["seq"]) < (best["device_id"], best["seq"]): best = row return best def find_floor(store, officer_id, target_ts, retention_cutoff_ts): """Walk active days at or before target_ts (normally reads 1 day, at most 2).""" for day in store.active_days_at_or_before(officer_id, day_of(target_ts)): if day < day_of(retention_cutoff_ts): return None rows = store.query_floor_desc(day, officer_id, target_ts, limit=8) candidate = pick_floor_from_desc(rows, store, day, officer_id) if candidate is not None: # Enforce exact millisecond 90-day cutoff even before physical table drop. if candidate["event_ts"] < retention_cutoff_ts: return None return candidate return None def pick_nearest(target_ts, floor_rec, ceil_rec): """Return nearest record; ties (<=) go to floor_rec (the earlier timestamp).""" if floor_rec is None: return ceil_rec if ceil_rec is None: return floor_rec floor_dist = target_ts - floor_rec["event_ts"] ceil_dist = ceil_rec["event_ts"] - target_ts if floor_dist <= ceil_dist: return floor_rec return ceil_recWhy
find_floorreads at most two day tables: ifday_of(target_ts)has no record<= target_ts, then the next earlier day listed inofficer_daysis strictly beforetarget_ts, so every non-expired record in that earlier day is guaranteed<= target_ts!Latency budget (
p99 < 50 ms): - Round 1 (parallel speculative reads, ~12–15 ms): Fetchofficer_daysaroundd, plus floor instatus_dand ceiling instatus_dsimultaneously. For an on-duty officer mid-shift, both floor and ceiling exist instatus_d, so Round 1 finishes the entire query! - Round 2 (only if floor or ceiling missed instatus_d, ~12–15 ms): Fetch floor in the previous active day and/or ceiling in the next active day. - Service overhead (~5–10 ms): Auth, tie-break math, JSON serialization, async audit enqueue -> Total ~25 ms typical, ~40 ms p99 (< 50 ms).Deep dive 2: Out-of-order arrivals, late data, and deduplication
1. Why late data never scrambles historical order: Writers route every record strictly by its
event_tsday bucket (status_YYYYMMDD), never by arrival time. If a patrol vehicle sits in a maintenance bay for 5 days and uploads Sep 15 telemetry on Sep 20, the Store Writer inserts those rows intostatus_20260915. Inside that table, ScyllaDB merges the new SSTable with older SSTables sorted by(event_ts, device_id, seq). Arrival order in Kafka only affects when a row becomes visible, never where it sorts in time. (Watch out for live dashboards: if you also maintain a "current officer status" cache, update it only whenincoming.event_ts > cached.event_tsso a 5-day-old replay never overwrites today's live GPS coordinate!)2. Crash-safe write order (
officer_daysbeforestatus_YYYYMMDD): Suppose a Store Writer crashes halfway through processing a batch:Wrong order (status row first, index second): 1. Write row to status_20260915 [OK] 2. Writer crashes before writing (off-204, 2026-09-15) to officer_days! -> Until replay finishes, cross-day queries skip 2026-09-15 and miss stored data. Safe order (index first, status row second, commit Kafka offset third): 1. Upsert (off-204, 2026-09-15) into officer_days [OK] 2. Upsert rows into status_20260915 [OK] 3. Commit Kafka consumer offset [OK]If the writer crashes between steps 1 and 2, a cross-day query briefly checks an empty partition on
2026-09-15(harmless) until Kafka replays the uncommitted batch seconds later. Because Kafka partitions byofficer_id, one writer handles a given officer and caches(officer_id, day)pairs already registered today in RAM, reducingofficer_dayswrites to one write per officer per day instead of 17,280.3. Lock-free deduplication at 20,000–80,000 writes/s: Checking "does this event already exist?" before writing (
SELECTthenINSERT) would double I/O and suffer race conditions without locks. Instead, because our primary key(officer_id, event_ts, device_id, seq)is the deterministic event identity, every retry from a device or Kafka consumer replay simply upserts (overwrites) the exact same row key with identical bytes. - What if buggy firmware sends two different payloads with the same(device_id, device_timestamp, seq)? Last-write-wins updates the hot table, while a daily integrity check over the S3 Raw Archive flags anyevent_idseen with differing payload hashes as a device anomaly for auditors. - Compaction after the 7-day late window: Daysd .. d + 7accumulate late SSTables, so reads merge a few files. Atday + 8, the Table Manager triggers a one-time major compaction onstatus_d, merging each officer-day partition into a single sorted file for optimal read latency over the remaining 82 days.Deep dive 3: Clock skew, epoch resets, and quarantine repair
Quartz clocks in field hardware drift (20 parts per million is ~1.7 seconds/day), and a drained internal battery can reset a camera's clock to
1970-01-01T00:00:00Z(the Unix epoch, the zero point of POSIX timestamps). Because records arrive every 5 seconds, even a 3-second clock error can flip which status appears nearest to an incident.Step 1: Measure clock offset on every upload. Every batch header includes
X-Device-Clock. The Ingest API computesoffset_ms = server_receive_time - device_clockalongside the HTTP request duration as an uncertainty bound, appending a sample toclock_samplesso we have a continuous clock-health timeline per device.Step 2: Classify every record at ingest (evaluated top-to-bottom).
Condition on device_timestamp Action & Stored Label ---------------------------------------------------------- -------------------------------------------- 1. > server_now + 5 min (impossible future) -> Write to quarantine ("future_timestamp") 2. < device provisioning date (e.g., 1970 epoch reset) -> Write to quarantine ("epoch_or_pre_provision") 3. < server_now - 90 days AND |device offset| <= 10 min -> Reject ("older_than_retention") 4. < server_now - 90 days AND |device offset| > 10 min -> Write to quarantine ("suspect_clock_old") 5. |latest device offset| > 2,000 ms -> Store normally, time_quality = "skewed" 6. Otherwise -> Store normally, time_quality = "device"Notice the critical difference between rules 3 and 4: if a camera's clock is off by 4 months, its brand-new patrol recording will carry a timestamp from 120 days ago. Rule 4 catches that the device's clock is broken (
|offset| > 10 min) and quarantines the record instead of rejecting it, preserving fresh evidence!Step 3: Re-time anchored sessions without erasing raw evidence. Inside a single device boot session (
boot_id), the hardware'suptime_mscounter ticks smoothly even when the wall clock is wrong. Whenever the Clock Analyzer finds one trustworthy time anchor in that sameboot_id—such as a GPS satellite fix (which carries atomic UTC time) or a live mTLS upload handshake—it reconstructs each quarantined event's true time:corrected_ts = anchor_true_utc + (record.uptime_ms - anchor.uptime_ms)It inserts the repaired record intostatus_YYYYMMDDwithevent_ts = corrected_ts, keepsraw_device_tsuntouched, and setstime_quality = "corrected". Unanchored quarantine rows remain visible in a separate auditor warning panel—never silently discarded and never mixed in unlabeled.Rolling retention, scaling, and failure handling
Lifecycle of a day table
status_d:Day d - 2 Table Manager pre-creates status_d (schema DDL never runs on the live write path) Day d..d + 7 Receives live telemetry and up-to-7-day-late uploads Day d + 8 Late window closes -> compact status_d into 1 SSTable/partition + export to S3 Parquet Day d + 91 Copy any rows under active Legal Hold into held_status -> verify S3 export -> DROP TABLE status_d and clear Scylla/Cassandra auto-snapshots to reclaim disk immediatelyScaling & bottleneck protections: - Ingest API: Stateless behind an L4/L7 load balancer. Keep persistent HTTP/2 connections open so devices do not repeat expensive mTLS handshakes every 30 seconds (~3,300 batch requests/s steady). - No hot partitions: Hashing
officer_idspreads 100,000 active officers evenly across all storage nodes, and each officer-day receives ~1 write every 5 seconds (<= 8.64 MBtotal). - Batch-query concurrency cap: If an audit report queries 500 officers at once vianearest-batch, the Query Service bounds internal fan-out concurrency so an investigation cannot starve live reads.Failure handling: - Cellular blackout / service unreachable: Devices buffer to encrypted local flash and retry later; records are deleted locally only after
"accepted". - Kafka broker or Store Writer crash: Kafka replicates 3-way (acks=2oracks=allwithmin.insync.replicas=2). Writers commit offsets after ScyllaDB writes succeed; crash recovery replays idempotent upserts. - Storage node failure:RF = 3with quorum writes (W = 2) and quorum reads (R = 2) tolerates losing any single availability zone with zero stale reads and zero downtime. - Loss of read quorum (2+ zones down): Fail closed with503 Service Unavailable. For legal auditing, waiting for recovery is far safer than returning a wrong "nearest" status that missed an unavailable replica's newer write.Summary of design trade-offs
- Wide-column LSM store vs. sharded relational B-tree: Sequential-append ingestion for 20k–80k out-of-order historical writes/s and effortless horizontal scaling to 100+ TB, at the cost of supporting only primary-key ordered lookups rather than arbitrary ad-hoc SQL joins.
- Daily
status_YYYYMMDDtables vs. single table with per-row TTL: Instant, tombstone-freeDROP TABLEpurges, small<= 8.64 MBpartitions, and clean post-7-day compaction/export boundaries, at the cost of managing ~93 rolling tables and anofficer_daysindex. - Durable Kafka buffer before DB vs. synchronous DB writes: Absorbs 4x shift-change reconnect bursts (
80,000/s) without over-provisioning the database, at the cost of a brief visibility lag (1–2 s normal, up to ~18 min at burst peak) surfaced honestly viacomplete_through. - Upsert by deterministic key vs. read-before-write deduplication: Zero lock or read overhead at 20,000+ writes/s, trading away inline conflict rejection if defective firmware reuses
(device_id, timestamp, seq)with altered bytes (caught asynchronously via the Raw Archive). - Indexing by
device_timestamp+ quarantine repair vs. indexing by server arrival time: Queries reflect when field events actually occurred rather than when Wi-Fi returned, requiring clock-offset tracking, quarantine storage, and explicittime_qualitymetadata.
Intuition & how it works
Think of storing officer telemetry like keeping one loose-leaf binder per officer with a separate tabbed divider for each calendar day, where field reports arrive in the mail days late and sometimes photocopied twice. If a clerk simply stapled reports in the order the mail carrier dropped them off (server arrival time), a 6-hour batch uploaded after a shift would sit in the wrong day and scramble history. Instead, every page carries a unique deterministic label (event_ts, device_id, seq): the clerk opens that date's tab and slips the page into its exact chronological slot—and if an identical photocopy arrives later, it lands in the exact same slot and harmlessly replaces itself (idempotency, meaning repeating the same write leaves the state unchanged). When an investigator asks, "What was Officer off-204's status closest to 08:12:12.200?", the clerk never reads the whole binder: they open the September 15 tab straight to 08:12:12.200, inspect just one page at or before 08:12:12.200 (the floor) and one page strictly after 08:12:12.200 (the ceiling), and return whichever of those two pages is closer in time.
Why do naive approaches fail here? Scanning a fixed window like T_target ± 5 minutes and sorting by |event_ts - T_target| returns nothing when an officer's radio was out of range for 20 minutes, yet scans thousands of rows if widened to hours or days. Storing records in a traditional B-tree database under 20,000–80,000 out-of-order writes/s causes constant random disk-page splits across old days, whereas an LSM-tree (Log-Structured Merge-tree) database turns out-of-order writes into fast sequential disk appends. Finally, deleting 1.73 billion 90-day-old rows one by one creates a storm of tombstones (deletion marker records that slow down reads until background cleanup runs), whereas dropping an entire expired day table (DROP TABLE status_20260617) frees space in milliseconds.
Let us trace 4 incoming events (including a late upload and a retry duplicate) for officer off-204 (cam-910) on 2026-09-15, followed by two closest-timestamp queries:
1. Ingestion (arriving out of order and duplicated):
- Arrive 08:12:11: (off-204, cam-910, 08:12:10.000, seq=21, holster="holstered") -> stored at 08:12:10
- Arrive 08:12:16: (off-204, cam-910, 08:12:15.000, seq=22, holster="drawn") -> stored at 08:12:15
- Arrive 13:25:00: (off-204, cam-910, 08:12:05.000, seq=20, holster="holstered") -> late! Slotted at 08:12:05
- Arrive 13:25:01: (off-204, cam-910, 08:12:10.000, seq=21, holster="holstered") -> retry! Overwrites 08:12:10
Sorted partition on disk for (off-204, 2026-09-15):
[08:12:05.000, cam-910, 20] -> [08:12:10.000, cam-910, 21] -> [08:12:15.000, cam-910, 22]
2. Query A: T_target = 08:12:12.200
- Floor (<= 08:12:12.200): 08:12:10.000 (distance = 2,200 ms)
- Ceiling (> 08:12:12.200): 08:12:15.000 (distance = 2,800 ms)
-> Returns 08:12:10.000 (2,200 ms < 2,800 ms).
3. Query B (equidistant tie): T_target = 08:12:12.500
- Floor (<= 08:12:12.500): 08:12:10.000 (distance = 2,500 ms)
- Ceiling (> 08:12:12.500): 08:12:15.000 (distance = 2,500 ms)
-> Returns 08:12:10.000 (tie-break rule: floor_dist <= ceil_dist picks the earlier record).
Key trade-offs
- Targeted floor + ceiling seeks vs. fixed time-window scans. Running two bounded single-partition seeks (
event_ts <= T_targetdescending andevent_ts > T_targetascending) plus a tinyofficer_daysactive-day index finds the closest record even across multi-day off-duty gaps in 1–2 reads. ScanningT_target ± Wis simpler to write, but misses records outsideWand wastes I/O inside dense windows. - Wide-column LSM store (ScyllaDB/Cassandra) vs. sharded relational B-tree vs. specialized TSDB. An LSM store absorbs 20,000–80,000 out-of-order writes/s sequentially and clusters each officer-day in timestamp order, trading away flexible ad-hoc secondary-index joins. Sharded PostgreSQL with monthly range partitions can also serve floor/ceiling B-tree index seeks, but suffers heavier random page I/O when late batches scatter writes across the past 7 days. Off-the-shelf metric TSDBs optimize numeric aggregations rather than 500-byte arbitrary status payloads with forensic tie-breaking.
- Daily buckets (
<= 8.64 MB/officer-day) vs. monthly buckets (259 MB/officer-month). Wide-column stores keep reads and node repairs healthy when individual partitions stay well under ~100 MB, which rules out a 259 MB officer-month partition. Daily buckets mean queries near midnight occasionally check an adjacent day, which theofficer_daysindex caps at one extra single-partition read. - Table-per-day
DROP TABLEvs. per-row TTL expiration. Droppingstatus_YYYYMMDDat day 91 is instantaneous, writes zero tombstones, and gives a clean "closed day" atday + 8to compact and export to cold storage once. Per-row TTL (Time-To-Live) avoids rolling table creation, but mixing 7-day-late arrivals into fresh SSTables delays whole-file expiration under Time-Window Compaction Strategy (TWCS) and requires computing remaining TTL fromdevice_timestamprather than write time. - Durable log acknowledgment vs. synchronous database writes. Acknowledging uploads from a 3-way replicated log (Kafka) absorbs 4x shift-change bursts (
80,000/s) while keeping database writers sized for50,000/s. The trade-off is an ingestion-to-query lag (1–2 s normally, up to ~18 minutes at the peak of a massive docking burst), surfaced transparently viacomplete_through. - Deterministic primary-key upsert vs. read-before-write deduplication. Using
(officer_id, event_ts, device_id, seq)as the primary key deduplicates retries with zero extra reads or distributed locks. If buggy firmware emits two different payloads under the same identity, last-write-wins overwrites the hot row while an asynchronous check over the S3 raw archive flags the hardware defect. - Indexing by
device_timestampwith quarantine vs. indexing by server arrival time. Forensic audits ask what happened at incident time, so indexing by arrival time is flatly wrong for delayed uploads. Indexing bydevice_timestampforces us to measure clock skew, quarantine impossible timestamps, and exposetime_qualityrather than pretending hardware clocks are perfect.
Common mistakes
- Scanning a range and sorting by
|t - T_target|instead of executing twoLIMITindex seeks, or forgetting to look in the previous/next active day bucket whenT_targetfalls near midnight or during days off. - Subtle tie-break bugs: Returning the later record on equidistant ties, fetching an exact match twice by using
>= T_targeton the ceiling alongside<= T_targeton the floor, or failing to realize that a descending scan (ORDER BY event_ts DESC, device_id DESC, seq DESC LIMIT 1) flipsdevice_idandseqto largest-first when two devices share the same millisecond. - Partitioning by
officer_idalone (creating unbounded partitions that grow forever) or partitioning byofficer_id+ month in Cassandra/ScyllaDB without calculating17,280 × 30 × 500 B = 259 MBper officer-month. - Writing telemetry rows before updating the
officer_daysbucket index, which can leave crashed batches invisible to cross-day floor/ceiling lookups, or blindly updating a "latest status" cache without checkingincoming.event_ts > cached.event_ts. - Purging 1.73 billion rows/day with
DELETE WHERE event_ts < cutoff, triggering an LSM tombstone storm that degrades p99 read latency past 50 ms. - Omitting a monotonic sequence counter
seqfrom the event key, causing genuinely distinct events emitted after a clock reset to overwrite each other, or overwritingraw_device_tsduring clock repair and destroying forensic provenance. - Rejecting every record with
device_timestamp < now - 90 days, which destroys brand-new patrol telemetry from a camera whose clock reset to 1970 instead of routing it to quarantine for re-timing.
Follow-up questions
- What mechanisms would you put in place when field hardware reports timestamps hours off real time or reverts to 1970-01-01? We flag clock anomalies three ways at ingest: comparing the upload's
X-Device-Clockheader against server UTC to track per-device offset history, checking sanity bounds (device_timestamp > now + 5 minor< device_provisioning_date, which catches1970-01-01resets right away), and spotting backward timestamp jumps while(boot_id, seq)increases. Events with moderate skew (e.g., > 2 s) are stored normally withtime_quality = "skewed"and an error bound, while implausible timestamps—including events that appear > 90 days old only because the unit has a large measured clock offset—route to aquarantinetable with raw fields preserved. Includingseqin the primary key ensures multiple snapshots emitted at1970-01-01never overwrite one another. An offline Clock Analyzer repairs quarantined events whenever theirboot_idsession contains at least one trusted UTC anchor (such as a GPS satellite fix or live mTLS handshake) viacorrected_ts = anchor_utc + (uptime_ms - anchor_uptime_ms), writing the repaired row withtime_quality = "corrected"while preservingraw_device_tsand surfacing unanchored rows separately for investigators. - If investigators frequently request the closest status snapshot across a whole squad or precinct at once instead of one officer, how would you adapt data partitioning and indexing? Because personnel rotate across squads over time, we maintain a temporal roster table
(unit_id, officer_id, valid_from, valid_to)and look up who belonged to that squad atT_target, not today. For moderate query rates and typical squad sizes (10–50 officers), the Query Service fans out parallel single-officer floor/ceiling reads with bounded concurrency; however, tail latency compounds across parallel reads (for all 50 lookups to finish under 50 ms on 99% of squad queries, each single-officer read must stay under 50 ms at0.99^(1/50) ≈ 99.98%, i.e., p99.98). When squad queries become high-throughput or breach the 50 ms target, we maintain a denormalized read projection keyed by((unit_id, hour_bucket), event_ts, officer_id): a squad lookup reads one narrowT_target ± 2 minslice from a single partition to resolve ~99% of active members in one round trip, falling back to individualofficer_daysseeks only for members silent during those 4 minutes, while keeping the per-officer table authoritative. - How would you transition records past the 90-day hot window into low-cost object storage (such as columnar files on S3) while still supporting infrequent historical lookups? At
day + 8(once the 7-day late-upload window closes), a background job exportsstatus_dinto immutable Apache Parquet files (s3://telemetry-archive/day=2026-06-17/part-0001.parquet) sorted by(officer_id, event_ts, device_id, seq)with ~128 MB row groups and page-level min/max statistics, and writes a compact cold-catalog index mapping(officer_id) -> active_daysand(day, officer_id) -> (parquet_file, row_group_id). Only after verifying row counts and checksums (and copying any legally held rows intoheld_status) does the Table Manager executeDROP TABLE status_dat day 91, re-exporting a day only on the rare arrival of >8-day-late uploads. When an auditor runs a cold lookup (T_target> 90 days old), the Query Service runs the exact same floor/ceiling logic against the cold catalog and issues HTTP byte-range reads for just the matching Parquet pages rather than downloading multi-GB files, returning in ~200–800 ms withsource = "cold"under a separate cold-query SLA whenever agency policy permits archiving instead of permanent erasure.
Follow-up questions
- What mechanisms would you put in place when field hardware reports timestamps hours off real time or reverts to 1970-01-01?
- If investigators frequently request the closest status snapshot across a whole squad or precinct at once instead of one officer, how would you adapt data partitioning and indexing?
- How would you transition records past the 90-day hot window into low-cost object storage (such as columnar files on S3) while still supporting infrequent historical lookups?
Similar questions
- Tamper-Evident Chain-of-Custody Ledger for Video Evidence
- Distributed Test Execution and Scheduling Platform
- Flight Search, Seat Inventory, and Reservation Platform
- Multilingual Photo Text Extraction and Translation Service
- E-Commerce User Activity and Live Order Analytics Store
- Resumable Evidence Video Upload and Custody Ledger
More Axon interview questions
- Resumable Evidence Video Upload and Custody Ledger Medium
- Multi-Warehouse Container Tracking, Dock Scheduling, and Fleet Routing Medium
- Defending Project Ownership and Impact Under Rapid Interruption Medium Pro
- Leadership Trajectory, Operational Rigor, and Team Impact Screen Medium Pro
- Navigating Candid Self-Reflection and Team Critique Medium Pro
- Resumable Transfer Service for Large Files Medium Pro
- Distributed Test Execution and Scheduling Platform Medium Pro
- Tamper-Evident Chain-of-Custody Ledger for Video Evidence Hard Pro
- Flight Search, Seat Inventory, and Reservation Platform Hard Pro
- E-Commerce Event and Order Analytics Warehouse Hard Pro