Time-Series Telemetry Service with Proximity Search
System DesignModel answerLast updated
Build a scalable backend that ingests out-of-order device telemetry and supports efficient queries for the status record nearest to any given timestamp.
Problem Context
You need to design a backend service for handling continuous telemetry streams from field devices. These devices—such as wearable sensors, vehicle trackers, or IoT equipment—send operational status updates containing metrics like location, battery level, and sensor readings.
Due to connectivity constraints, telemetry arrives with significant challenges:
- Out-of-order delivery: Events may arrive minutes, hours, or even days after they were generated
- Network retries: The same event may be transmitted multiple times
- Batch uploads: Devices buffer data during offline periods and upload in bursts when connectivity is restored
Your service must support forensic and auditing applications that need to reconstruct the exact operational state at any historical moment.
System Requirements
Core Functionality
- Telemetry Ingestion: Accept status events containing
officer_id,device_id,device_timestamp, and arbitrary structured payload data - Proximity Query: Given an
officer_idand target timestampT_query, return the single record whosedevice_timestampis temporally closest toT_query- Tie-breaking rule: when two records are equidistant from
T_query, return the earlier one
- Tie-breaking rule: when two records are equidistant from
- Automatic Deduplication: Handle duplicate submissions gracefully without storing redundant data
- Time-Based Retention: Automatically expire records older than a configurable window (assume 90 days)
Scale and Performance
- Active entities: 100,000 concurrent officers
- Update frequency: One record every 5 seconds per officer
- Peak ingestion rate: ~20,000 writes/second
- Record size: Approximately 500 bytes per event
- Query latency: p99 read latency must stay below 50ms
- Late arrivals: System must correctly handle data arriving up to 7 days late
Design Constraints
- Data durability is critical—no acknowledged writes can be lost
- Late-arriving data must be correctly integrated without corrupting the temporal ordering of existing records
- The system should handle device clock drift and network-induced timestamp inconsistencies
What to Deliver
Provide a complete system design covering:
- API specification: Define the ingestion and query endpoints
- Storage architecture: Select appropriate database technology and justify your choice based on the access patterns
- Data model: Design the schema, including partitioning strategy and indexing approach
- Query algorithm: Explain how you efficiently locate the temporally nearest record
- Handling disorder: Describe how out-of-order and late data are managed throughout the pipeline
- Edge cases: Address clock skew, deduplication mechanics, and retention implementation
Hints
Hint 1
Consider how time-series databases or wide-column stores handle range queries on a clustering key
Hint 2
Think about whether partitioning by day vs. month affects both query performance and storage efficiency given the per-officer data volume
Hint 3
A single exact-match query cannot find the nearest neighbor—you need to search in both temporal directions
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Solution: Time-Series Telemetry Service with Proximity Search
1. Capacity Planning and Clarifications
Start by quantifying the workload before selecting technologies:
Write throughput:
- 100k officers × 1 record/5s = 20,000 writes/second sustained
- Plan for 3× burst capacity (60k writes/s) to handle batch uploads when devices reconnect
Storage requirements:
- Daily ingestion: 20k writes/s × 500 bytes × 86,400s = ~864 GB/day
- 90-day retention: 864 GB × 90 ≈ 78 TB raw data
- With 3× replication: ~234 TB (compression can reduce this 2-4×)
- Per-officer daily volume: 17,280 records × 500 bytes ≈ 8.6 MB
Read patterns:
- Low query volume (100-1000 queries/second) but latency-sensitive
- Each query must scan at most a few partition rows to meet the 50ms p99 target
Critical clarifications:
- Is proximity measured by device timestamp or server receipt time? Device timestamp (the moment the event occurred).
- Can one officer operate multiple devices simultaneously? Yes, so queries aggregate across devices.
- What's the correct behavior for data arriving beyond 7 days late? Accept if within 90-day retention, log a monitoring alert.
2. API Design
POST /v1/telemetry/ingest
Request body:
{
"events": [
{
"officer_id": "string",
"device_id": "string",
"device_timestamp": "ISO8601 timestamp",
"sequence_number": "int64",
"boot_session_id": "string",
"payload": { arbitrary JSON }
}
]
}
Response: 202 Accepted
{ "accepted": 850, "rejected": [ {"index": 3, "reason": "outside retention window"} ] }
GET /v1/officers/{officer_id}/status-at?timestamp={ISO8601}&max_distance_ms={optional}
Response: 200 OK
{
"record": { full event object },
"temporal_distance_ms": 1247,
"matched_by": "floor" | "ceiling"
}
Or 404 if no records exist within constraints
Design rationale:
- Batch ingestion reduces HTTP overhead and matches device upload patterns
- Idempotent POST allows safe retries from devices
- 202 response means durably logged, not necessarily indexed yet
- Query API provides observability (distance, match direction) for debugging
3. System Architecture
Field Devices
↓
Load Balancer → API Gateway Cluster
↓ (validate, authenticate, normalize timestamps)
Kafka / Kinesis (partitioned by officer_id, ack=all, RF=3)
↓
Stream Processor Workers (batched writes, 100-1000 events/batch)
↓
ScyllaDB / Cassandra (RF=3, LOCAL_QUORUM)
↓
Query Service (stateless, issues parallel range queries)
Separate async pipeline:
Kafka → S3/Parquet archiver (cold storage for compliance)
Component responsibilities:
- API Gateway: Clock skew detection and correction, schema validation, deduplication key generation
- Message queue: Durability guarantee point, burst smoothing, enables replay if corruption is detected
- Database choice: Wide-column store (Cassandra/ScyllaDB) or DynamoDB
- Handles high write volume with LSM tree architecture (out-of-order writes are cheap)
- Native support for clustering key range scans
- Built-in TTL for automatic expiration
- Time-series databases (TimescaleDB, InfluxDB) are viable but wide-column stores handle arbitrary JSON payloads and multi-device deduplication more naturally
4. Data Model
CREATE TABLE telemetry_by_officer (
officer_id text,
day_partition date, -- derived from corrected device_timestamp
device_timestamp timestamp, -- millisecond precision
device_id text,
sequence_number bigint,
ingestion_time timestamp,
original_device_ts timestamp, -- before clock correction
clock_adjusted boolean,
payload blob,
PRIMARY KEY ((officer_id, day_partition), device_timestamp, device_id)
) WITH CLUSTERING ORDER BY (device_timestamp ASC, device_id ASC)
AND default_time_to_live = 7776000 -- 90 days in seconds
AND compaction = {
'class': 'TimeWindowCompactionStrategy',
'compaction_window_unit': 'DAYS',
'compaction_window_size': 1
};
Key design decisions:
Partition size: Daily partitioning yields ~8.6 MB per partition (17,280 rows × 500 bytes), which is well within Cassandra's recommended 100 MB limit. Monthly partitioning (~260 MB) would exceed it. Weekly (~60 MB) is acceptable but offers no benefit over daily.
Composite clustering key: (device_timestamp, device_id) provides:
- Natural temporal ordering for range scans
- Deterministic tie-breaking when multiple devices report at the same millisecond
- Implicit deduplication: duplicate submissions map to identical primary keys and become idempotent upserts
Deduplication mechanism:
- Primary key alone enforces uniqueness:
(officer_id, day_partition, device_timestamp, device_id) - No read-before-write required
- Gateway computes
event_id = hash(officer_id, device_id, device_timestamp, sequence_number)for distributed tracing - If retries carry different payloads (rare), last-write-wins is acceptable; emit alerts on payload checksum mismatches
Retention implementation:
- Compute per-row TTL dynamically:
TTL = retention_period - (server_now - corrected_device_timestamp) - Drop events already beyond retention at ingestion
- TimeWindowCompactionStrategy drops entire SSTables once all rows expire, avoiding tombstone accumulation
- Alternative: monthly tables with
DROP TABLEoperations (simpler expiration, more complex routing)
5. Proximity Search Algorithm
To find the record nearest to T_query, issue two parallel range queries:
-- Floor query: latest record at or before T_query
SELECT * FROM telemetry_by_officer
WHERE officer_id = ?
AND day_partition = date(T_query)
AND device_timestamp <= T_query
ORDER BY device_timestamp DESC, device_id DESC
LIMIT 1;
-- Ceiling query: earliest record after T_query
SELECT * FROM telemetry_by_officer
WHERE officer_id = ?
AND day_partition = date(T_query)
AND device_timestamp > T_query
ORDER BY device_timestamp ASC, device_id ASC
LIMIT 1;
Result selection logic:
- If only one query returns data, that's the answer
- If both return results, compute
distance_floor = |T_query - floor_ts|anddistance_ceiling = |T_query - ceiling_ts| - Return floor if
distance_floor <= distance_ceiling(satisfies the tie-breaking rule: prefer earlier) - An exact timestamp match always appears in the floor result
Handling partition boundaries:
- If a query returns no results in the target day partition, expand search to adjacent partitions
- For floor: check day - 1, day - 2, etc.
- For ceiling: check day + 1, day + 2, etc.
- Optimization: maintain a lightweight auxiliary table
active_days(officer_id, day_partition)to skip empty days without issuing queries - Stop expansion once one direction finds a result at distance D; the other direction only needs to search within distance D
- Respect
max_distance_msparameter if provided
Performance characteristics:
- Each query is a single-partition range scan with LIMIT 1 (typically 2-10ms in Cassandra)
- Two parallel queries complete in ~5-15ms p50, ~20-40ms p99
- Partition boundary crossings add one additional seek per boundary
Caching considerations:
- Results for
T_querywithin the past 7 days can still change as late data arrives - Only cache responses where
T_query < current_time - 7 days - safety_margin - Use officer_id + rounded timestamp as cache key
6. Handling Out-of-Order and Late Data
Write path invariant: An event's storage location depends solely on its corrected device timestamp, not arrival time.
- Record arriving 3 days late writes to a 3-day-old partition
- LSM architecture makes this an ordinary append to memtables
- Temporal ordering is established during reads and compaction, not at write time
- No global "high-water mark" or complex backfill logic required
Query correctness: Late arrivals are immediately visible in queries once written (at LOCAL_QUORUM consistency). No eventual consistency issues for proximity search.
Compaction interaction: With TimeWindowCompactionStrategy, late records land in newer SSTable files than their temporal neighbors. This slightly delays compaction but doesn't affect correctness. With a 7-day late bound, expiration may be delayed by ~7 days. Monitor droppable_tombstone_ratio metrics.
Consistency guarantees:
- Kafka partitioning by
officer_idpreserves per-officer ordering through the pipeline - Write and read at
LOCAL_QUORUM(guarantees overlap: writes acknowledged by 2 of 3 replicas, reads query 2 of 3) - Workers commit Kafka offsets only after database acknowledgment (at-least-once delivery)
- Idempotent upserts convert at-least-once to effectively-once
7. Clock Skew and Edge Cases
Clock correction strategy:
At connection establishment, compute skew = server_timestamp - device_reported_current_time.
- If |skew| > 30 seconds, apply correction:
corrected_ts = raw_device_ts + skew - Store both
original_device_tsandcorrected_ts; use corrected for partitioning and queries - Set
clock_adjusted = trueflag for monitoring
Limits on correction:
- Reject records with |skew| > 24 hours (likely indicates hardware failure)
- After correction, reject records outside the retention window
Multi-device scenarios:
- Different devices for the same officer may have independent clock skews
- Correction is applied per-device based on that device's connection handshake
- The
device_idcomponent of the clustering key ensures deterministic ordering when timestamps collide
Sequence numbers:
- Used during deduplication detection:
(device_id, device_timestamp, sequence_number)forms a stronger event identity - Helps identify true duplicates vs. legitimate events at the same millisecond
- Monotonically increasing within a device boot session
Common mistakes to avoid:
- Don't partition by month without checking partition size against data volume
- Don't use server arrival time for partitioning or proximity calculations
- Don't require read-before-write for deduplication (defeats scalability)
- Don't implement nearest-neighbor search as a full scan with application-side sorting
- Don't ignore clock skew—field devices often have significant drift
Monitoring and observability:
- Track late arrival distribution (histogram of
ingestion_time - device_timestamp) - Alert on increasing clock skew magnitudes
- Monitor partition size distribution
- Track query latency by number of partitions scanned
- Count duplicate submissions per device (high rates indicate network issues)
This design handles 20,000 writes/second with sub-50ms query latency while correctly integrating out-of-order data and supporting efficient time-based expiration.