Fleet-Scale Security Camera Liveness and Offline Monitoring
Medium · System Design · Software Engineer · Technical Screen
Prompt
Architect the backend for a live health-monitoring service managing a fleet of 1,000,000 security cameras. Every active device transmits a lightweight JSON heartbeat payload containing camera_id and timestamp once every 10 seconds. Operators rely on a real-time monitoring view—backed by GET /cameras/offline—that surfaces every camera from which no check-in has arrived during the trailing 60 seconds.
Your system must satisfy the following requirements:
- Ingestion throughput & burst handling: Continuously process
100,000heartbeats per second in steady state while absorbing sudden network-reconnect bursts without losing status accuracy. - Sub-linear offline lookup: Serve
GET /cameras/offlinereturning the identifiers of all cameras silent past the60-second cutoff without scanning the entire1,000,000-device fleet on each call. - Low-latency state transitions: Reflect online-to-offline and offline-to-online changes within a few seconds of crossing the
60-second boundary.
Scope & Expectations
- A high-throughput ingestion pipeline and persistent connection model capable of sustaining
100,000writes/second and buffering transient retry spikes. - An in-memory state layout and indexing mechanism that retrieves silent camera IDs in work proportional to the offline subset rather than total fleet size.
- Clean handling of device clock skew, duplicate or out-of-order packets, newly registered cameras that have never sent a heartbeat, and state expiration/cleanup.
- Bottleneck analysis, shard recovery, and read-side caching/pagination so operator views stay responsive even during major regional outages.
Step-by-step walkthrough
Clarify requirements and scope
At first glance, tracking 1,000,000 cameras looks simple because each camera only needs a single "last seen" timestamp. Three practical pressures make this a classic interview design problem:
- High continuous write rate:
1,000,000cameras checking in every10 secondsproduce100,000 heartbeats/snonstop (300,000/sduring network-recovery bursts). - Sub-linear offline queries:
GET /cameras/offlinemust return the exact IDs of every camera silent for more than60 seconds—without scanning all1,000,000cameras on every API request. - Outage amplification: during a regional blackout, the offline list jumps from ~10,000 IDs to ~300,000 IDs at the exact moment hundreds of operators start refreshing the dashboard.
Functional requirements
- Accept 10-second JSON heartbeat payloads (
{"camera_id": "...", "timestamp": ...}) across a fleet of1,000,000security cameras. - Implement
GET /cameras/offlineto list every provisioned camera whose latest check-in is older than60 seconds(or missing altogether).
Non-functional requirements
- Sustain
100,000 heartbeats/ssteady state and absorb3xtransient network spikes (300,000/s) without dropping status accuracy. - Reflect offline/online transitions on the dashboard within a few seconds (
<= 5 s) of crossing the 60-second threshold. - Keep dashboard reads fast and consistent even when thousands of users poll during a major outage.
Clarifying questions and assumptions
- Are all valid cameras registered in advance? Yes: cameras live in a provisioning registry (
activevs.decommissioned). Crucially, a newly installed camera that has never sent a single heartbeat must still appear inGET /cameras/offline—a trap that catches designs tracking only arriving packets. - Which clock counts for the 60-second window? Server gateway receive time, never the camera's payload
timestamp. Device clocks drift or reset on reboot; the camera's timestamp is kept for hardware diagnostics only. - How big can
GET /cameras/offlineget, and how often is it called? Roughly1%(~10,000cameras) offline on a normal day and up to30%(~300,000cameras) during a regional outage, polled by ~1,000 open dashboards every 5 s (~200 req/snormal,~2,000 req/sduring incidents)—so the endpoint uses snapshot-consistent cursor pagination.
- High continuous write rate:
Back-of-the-envelope numbers
Estimate traffic, memory, and payload sizes first so every storage decision follows directly from math.
Heartbeat ingestion Steady write rate 1,000,000 / 10 s = 100,000 heartbeats/s Network spike (3x) retries / reconnects = 300,000 heartbeats/s Wire bandwidth ~200 B per frame = ~20 MB/s steady, ~60 MB/s in a 3x spike Ingestion gateways 1,000,000 persistent TLS sockets (~100K/node) -> 10 gateways minimum Run 30 gateways across 3 Availability Zones -> ample headroom for 3x spikes & losing 1 AZ Live state in Redis Sorted Sets Per-camera entry camera_id + 8 B float64 score + skip-list/dict pointers ~ 150 B in RAM All 1,000,000 cams 1,000,000 x 150 B = ~150 MB total RAM! (fits trivially in memory) Raw heartbeat volume (if persisted to disk) 100,000/s x ~100 B = 10 MB/s = ~864 GB/day (~2.6 TB/day with 3x replication) GET /cameras/offline response size (~55 B JSON per item: {"id": "cam-...", "last_seen": ...}) Normal (1% offline) 10,000 cameras = ~550 KB JSON Outage (30% offline) 300,000 cameras = ~16.5 MB raw JSON (~2 MB gzipped) -> paginate! Dashboard traffic ~200 req/s normal -> ~2,000 req/s during an incidentFour clear lessons jump out of these numbers:
- The entire fleet's live state (
~150 MB) fits in tiny RAM, so storage capacity is never the bottleneck—write packet rate (100K–300K/s) is. - Storing
864 GB/dayof raw heartbeats in an indexed database is wasted work becauseGET /cameras/offlineonly ever cares about each camera's single newest timestamp. - Keeping cameras ordered by
last_seenlets us read only theMoffline cameras (10Kinstead of1,000,000), skipping the 99% of healthy cameras completely. - A 16.5 MB outage list requested 2,000 times/s (
33 GB/sif naive!) requires precomputing a 1-second snapshot and paginating responses.
- The entire fleet's live state (
API design
1. Device heartbeat ingestion
Opening a fresh TLS connection for every 10-second heartbeat would burn CPU on
100,000TLS handshakes per second. Instead, each camera keeps a persistent HTTP/2 or MQTT connection over mutual TLS (mTLS) (where both server and camera authenticate via cryptographic certificates, proving the sender ownscamera_id).POST /v1/heartbeats (over persistent HTTP/2 + mTLS, or MQTT PUBLISH) Body: {"camera_id": "cam-70412", "timestamp": 1758205200123} 204: Accepted (returned once durably appended to Kafka; camera retries on timeout/5xx)2. Dashboard read endpoints
GET /cameras/offline?limit=5000&cursor=<opaque_cursor> 200 OK (Cache-Control: private, max-age=2) { "as_of": "2026-09-18T14:20:05Z", "threshold_s": 60, "total": 10233, "cameras": [ {"id": "cam-55190", "last_seen": null}, {"id": "cam-70412", "last_seen": "2026-09-18T14:18:41Z"} ], "next_cursor": "v88213:5000" } 410 Gone (returned if cursor's 60-second snapshot version expired; client restarts at page 1) GET /cameras/offline/summary 200 OK {"as_of": "...", "total": 10233, "by_region": {...}, "by_site": {...}} GET /cameras/{camera_id}/status 200 OK {"id": "cam-70412", "status": "online", "last_seen": "2026-09-18T14:20:02Z"}Why each field earns its place:
- Versioned cursor (
v88213:5000): embeds the snapshot ID (v88213) and slice offset (5000) so paging through 50,000 offline cameras never skips or duplicates cameras while live devices flicker online and offline. as_of: reports the exact ingestion timestamp represented by the snapshot so operators immediately spot pipeline lag.last_seen: null: cleanly distinguishes a newly provisioned camera that has never connected from one that went dark five minutes ago.
- Versioned cursor (
Data model: Redis Sorted Sets vs. a raw heartbeat database
A Redis Sorted Set (
ZSET) is an in-memory data structure that maps unique member strings (camera_id) to floating-point numbers (score = received_at_ms), maintaining both a hash table (for instant lookup by ID) and a skip list (a layered linked list kept continuously sorted by score). That gives usO(log N)timestamp updates andO(log N + M)range queries returning only theMcameras older than our 60-second cutoff!1. Redis Cluster (4 primary nodes + 4 replicas; 16 Sorted Set shards total) hb:{0..15} ZSET: member = camera_id, score = newest received_at_ms (0 = never seen) shard = crc32(camera_id) % 16 (~62,500 cameras, ~9.5 MB per shard) wm:{0..31} STRING: applied-up-to timestamp (ms) for each Kafka partition offline:snap:{version} BYTES: compressed sorted list of (camera_id, last_seen_ms), TTL = 60 s offline:latest STRING: current snapshot version number 2. Kafka (durable spike buffer & 70-second crash-replay log) heartbeats 32 partitions, partition = crc32(camera_id) % 32, 24 h retention {camera_id, received_at_ms, device_ts_ms, gateway_id} 3. Relational Provisioning DB (Postgres — source of truth for which cameras exist) cameras camera_id PRIMARY KEY, org_id, site_id, region, status (active | decommissioned)Notice the aligned 32-to-16 partitioning trick (
crc32(camera_id) % 32->partition % 16): because32is an exact multiple of16, every camera in Kafka partitionpbelongs to one single Redis shardhb:{p % 16}! Each stream writer talks to just one Redis primary per batch instead of scattering writes across all four primaries, and rebuilding one lost Redis shard only replays 2 of the 32 Kafka partitions instead of the entire cluster.Why skip storing individual check-ins in disk tables? Writing
100,000indexed rows/s (864 GB/day) into Postgres or a time-series database pays a massive storage and I/O tax for historical rows thatGET /cameras/offlinenever queries. Instead, live state lives in~150 MBof fast Redis RAM, while Kafka (an unindexed, sequential append-only disk log that automatically deletes segments after 24 hours) provides durability—if a Redis node dies completely, replaying just the last 70 seconds of its 2 Kafka partitions restores 100% of online/offline state!High-level architecture
1,000,000 Security Cameras (persistent mTLS HTTP/2 or MQTT) | v [ L4 TCP Load Balancers ] | v +------------------------------------------------------------------+ | Ingestion Gateways (30 stateless pods across 3 AZs) | | - Verify mTLS cert == camera_id; stamp server received_at_ms | | - Produce to Kafka (partition = crc32(camera_id) % 32, acks=all) | | - Emit 1-second tick on idle partitions so watermarks advance | +------------------------------------------------------------------+ | v [ Kafka: heartbeats (32 partitions, 24 h retention) ] | v +------------------------------------------------------------------+ | State Writers (32 partition tasks) | | - Micro-batch 50 ms, coalesce duplicates to max(received_at_ms) | | - 1 pipelined ZADD hb:{p % 16} XX GT per batch + update wm:{p} | +------------------------------------------------------------------+ | v [ Redis: hb:{0..15} Sorted Sets ] <--- seed (ZADD NX 0) / remove (ZREM) --- [ Registry Sync + SQL DB ] | | every 1 s: ZRANGE hb:{0..15} -inf (cutoff BYSCORE WITHSCORES v +------------------------------------------------------------------+ | Snapshot Builder (1 active leader via lease + 1 warm standby) | | - Computes cutoff = min(wm:{0..31}) - 60,000 ms | | - Writes compressed offline:snap:{v} + updates offline:latest | +------------------------------------------------------------------+ | v Dashboards ---> [ Stateless API Servers (cache latest snapshot in local RAM, slice pages in O(limit)) ]Deep dive 1: push vs. pull and spike-resilient ingestion
Push vs. pull for the 60-second window:
- Why device ingestion MUST be push, never pull: In a pull model, servers would have to poll
1,000,000cameras every 10 seconds (100,000outbound requests/s), maintain connection schedules, stall worker threads on dead cameras, and—most decisively—fail to reach customer security cameras sitting behind NAT (Network Address Translation) routers and corporate firewalls that block inbound connections from the internet. With push, cameras open outbound connections through their firewall and push heartbeats on their own 10-second timer. - Why dashboard reads combine background push (precompute) with lightweight client pull: Rather than making
2,000concurrentGET /cameras/offlinecalls each run 16 range queries against Redis, one background Snapshot Builder precomputes the list once per second and pushes it into cache so API servers answer every pull from local memory.
Why buffer with Kafka instead of writing straight from Gateways to Redis? At
100K writes/s, gateways could write directly to 4 Redis primaries—a valid, simpler setup for small fleets. Putting Kafka in between buys resilience against transient network spikes: when a regional ISP recovers and300,000retries hit in one second, sequential disk appends in Kafka absorb the spike effortlessly while State Writers drain batches into Redis using pipelining (packing thousands of Redis commands into a single TCP round trip instead of waiting on network latency per command):import zlib def kafka_partition_for(camera_id: str, num_partitions: int = 32) -> int: # Use deterministic CRC32 (Python's built-in hash() is randomized per process!). return zlib.crc32(camera_id.encode("utf-8")) % num_partitions def apply_partition_batch(partition_id: int, records: list[dict], redis_client, num_shards: int = 16) -> int: # Phase 1: Coalesce retries inside this 50 ms micro-batch to keep only max timestamp per camera. newest_by_camera = {} max_timestamp_ms = 0 for record in records: received_at_ms = record["received_at_ms"] if received_at_ms > max_timestamp_ms: max_timestamp_ms = received_at_ms if record.get("tick"): # Gateway tick records advance the partition watermark without touching ZSETs. continue camera_id = record["camera_id"] if received_at_ms > newest_by_camera.get(camera_id, 0): newest_by_camera[camera_id] = received_at_ms # Phase 2: All cameras in partition_id belong to ONE shard (partition_id % 16)! shard_key = f"hb:{partition_id % num_shards}" pipeline = redis_client.pipeline(transaction=False) for camera_id, received_at_ms in newest_by_camera.items(): # xx=True: update ONLY existing provisioned cameras (blocks decommissioned stragglers). # gt=True: update ONLY if received_at_ms > stored score (ignores out-of-order retries). pipeline.zadd(shard_key, {camera_id: received_at_ms}, xx=True, gt=True) # Record how far this partition has been applied before committing Kafka offsets. if max_timestamp_ms > 0: pipeline.set(f"wm:{partition_id}", max_timestamp_ms) pipeline.execute() return max_timestamp_msLook at what
xx=True, gt=Truesolves in two flags:gt=True("greater than"): if an older retried packet arrives after a newer heartbeat, Redis refuses to movescorebackward—making crashes and at-least-once Kafka replays 100% idempotent.xx=True("exists only"): because Registry Sync seeds every valid camera on creation (ZADD hb:s NX 0 cam_id) and removes retired ones (ZREM hb:s cam_id), late in-flight packets from a retired camera can never resurrect it in Redis. (If a brand-new unboxed camera sends its very first packet 100 ms beforeZADD NX 0runs,XXdrops that one packet and the next 10-second heartbeat marks it online automatically.)
- Why device ingestion MUST be push, never pull: In a pull model, servers would have to poll
Deep dive 2: finding offline cameras in O(log N + M) without full scans
Because every Redis shard keeps its
~62,500cameras sorted from oldestlast_seenon the left to newestlast_seenon the right, all offline cameras sit in one contiguous prefix at the left end of each Sorted Set:Sorted Set hb:3 (62,500 cameras ordered by score = last_seen_ms; watermark = 120,000 ms, cutoff = 60,000 ms) score: 0 18,000 54,500 | 111,200 115,400 119,800 ... (61,880 online cams) [cam-new] -> [cam-214] -> [cam-637] | [cam-108] -> [cam-452] -> [cam-891] ... |<--- ZRANGE -inf (60000 BYSCORE --->| |<--- NEVER READ OR SCANNED BY REDIS! ---------------->| returns M = ~620 offline IDsIn Redis syntax,
"-inf"means the lowest possible score (catchingscore = 0cameras that have never checked in), and prefixing the upper bound with"("("(60000") makes it strictly less thancutoff(score < cutoff). Across 16 shards, total Redis work is16 x O(log 62,500 + M_shard)—touching ~10,000 offline entries in a couple of milliseconds and never visiting the 990,000 online cameras.Crucial detail — compute
cutofffrom the ingestion watermark, never wall clock:Suppose a 3x network spike causes State Writers to lag
15 secondsbehind real time. If Snapshot Builder queriedwall_clock - 60 s, any camera whose latest 50-second-old heartbeat is still waiting in Kafka would have a Redis score65 sbehind wall clock—falsely flipping hundreds of thousands of healthy cameras to"offline"! Instead, define:global_watermark_ms = min(wm:0, wm:1, ..., wm:31) cutoff_ms = global_watermark_ms - 60_000When writers lag by
15 s,cutoff_mslags by15 stoo: the snapshot remains 100% accurate as ofas_of = global_watermark_msrather than inventing a fake outage.OFFLINE_WINDOW_MS = 60_000 def build_offline_snapshot(redis_client, num_partitions: int = 32, num_shards: int = 16, version: int = 1) -> dict: # Phase 1: Read all 32 partition watermarks in one round trip; global progress is the minimum. wm_keys = [f"wm:{p}" for p in range(num_partitions)] wm_values = [int(v) for v in redis_client.mget(wm_keys) if v is not None] watermark_ms = min(wm_values) cutoff_ms = watermark_ms - OFFLINE_WINDOW_MS # Phase 2: Pipeline all 16 O(log N + M) prefix range queries in a single network round trip. pipeline = redis_client.pipeline(transaction=False) for shard in range(num_shards): # "(" prefix means strictly less than cutoff_ms; "-inf" includes score=0 never-seen cameras. pipeline.zrange(f"hb:{shard}", "-inf", f"({cutoff_ms}", byscore=True, withscores=True) shard_results = pipeline.execute() # Phase 3: Merge, sort deterministically for stable cursor slicing, and tag with watermark. offline_cameras = [] for rows in shard_results: for camera_id, score_ms in rows: last_seen_ms = None if int(score_ms) == 0 else int(score_ms) offline_cameras.append((camera_id, last_seen_ms)) offline_cameras.sort() return { "version": version, "as_of_ms": watermark_ms, "cameras": offline_cameras, }End-to-end latency check: Gateway -> Kafka (
~10 ms) + Writer micro-batch (<= 50 ms) + Watermark tick (<= 1 s) + Snapshot Builder tick (<= 1 s) + API server cache refresh (<= 1 s) + HTTPmax-age=2(<= 2 s) =~3–5 secondstotal delay after crossing 60 seconds!Deep dive 3: data expiration, TTL pitfalls, and fast shard recovery
Why NOT set a 60-second Redis TTL on 1,000,000 individual keys (
SET cam:X 1 EX 60)?That approach looks tempting at first, and fails on two counts:
- You cannot efficiently list keys that do not exist. Once a key expires and vanishes, answering
GET /cameras/offlinerequires checking all1,000,000registered IDs (MGETorSCAN) on every poll—bringing back theO(N)full scan we were asked to eliminate! - Redis keyspace expiry events are delayed and lossy. Redis deletes expired keys lazily via random sampling (so under load an expiry notification can fire many seconds late), and delivers notifications over fire-and-forget Pub/Sub—meaning any brief listener disconnect permanently drops offline transitions.
With Sorted Sets, online status needs no deletion at all—a silent camera's timestamp simply stands still while
cutoff_msmarches past it! Each actual data store expires cleanly by its own natural lifecycle:Data item How it is cleaned up / expired -------------------------- ---------------------------------------------------------------------- Online/offline camera state Zero TTL needed; score naturally falls below cutoff_ms after 60 s Decommissioned cameras Registry Sync runs ZREM hb:{shard} <id>; ZADD XX blocks stragglers Raw Kafka heartbeat log Kafka segment retention deletes logs older than 24 h automatically Offline snapshots in Redis 60 s Redis TTL on offline:snap:{version} (ample time to page through)Fast recovery from Redis failures:
- Routine primary failover (replica promotion): Redis replication is asynchronous, so promoting a replica can lose the last
~1 secondofZADDwrites. Because cameras send a heartbeat every10 seconds, an affected online camera temporarily holds its previous timestamp (~11 sold)—nowhere near the60 soffline threshold—and heals itself on its very next heartbeat! - Total loss of a Redis shard (both primary and replica wiped):
- Registry Sync re-seeds that shard's
~62,500active cameras withZADD NX 0(< 0.2 s). - A recovery worker seeks only the 2 mapped Kafka partitions (
sands + 16) back70 seconds(7,000,000 / 16 = ~437,500records,~44 MB) and replays them with pipelinedZADD XX GTin~1–2 seconds! Meanwhile Snapshot Builder serves the previous good snapshot (as_of2 seconds old) so zero false offline alerts appear during rebuild.
- Registry Sync re-seeds that shard's
- You cannot efficiently list keys that do not exist. Once a key expires and vanishes, answering
Scaling, failure modes, and trade-off summary
Scaling bottlenecks and headroom
- Redis write throughput:
16shards across4Redis primaries handle~25,000writes/s per primary steady (~75,000/sin a 3x spike)—comfortably below the200K+pipelinedZADD/scapacity of a single modern Redis core, and scaling horizontally to 8 or 16 primaries requires only moving shard slots. - Dashboard read scaling: Whether
10or10,000engineers refreshGET /cameras/offlinesimultaneously, Redis still runs16range queries once per second. Stateless API servers hold the latest ~1–2 MB compressed snapshot in local memory and slice 5,000-item pages in microseconds. - Reconnect storms: Cameras use exponential backoff with jitter (randomizing retry delays across doubling windows) and TLS session resumption so a recovered power grid doesn't trigger
300,000simultaneous handshakes in the same millisecond. - At 10x fleet scale (
10,000,000cameras,1,000,000 heartbeats/s): Movelast_seenfrom shared Redis into the local RAM of partitioned Kafka stream consumers (using a hashed timer wheel) to eliminate1Mcross-network Redis writes per second entirely.
Failure scenario User-visible effect System response Gateway pod crashes ~33K cameras reconnect smoothly Unacked packets retried; dead gateway dropped from partition watermarks after 10 s State Writer crashes 1 of 32 partitions pauses ~3 s Reassigned consumer replays uncommitted batch safely ( ZADD GTis idempotent);as_ofpauses ~3 s3x network spike lags writers as_oftrails wall clock by secondsWatermark shifts cutoff_msby identical lag -> zero false offline camerasRedis primary fails over None Replica promoted; ~1 s lost score gap heals on next 10 s heartbeat Whole Redis shard wiped as_ofpauses ~2 sRe-seed 1/16registry + replay 2 mapped Kafka partitions (70 s=~438Krecords)Snapshot Builder crashes Stale snapshot for ~2–3 s Warm standby acquires lease; API servers continue serving cached snapshot Operational monitoring: alert on
wall_clock - global_watermark_ms > 10 s, Snapshot Builder age, Gateway5xx/Kafka produce errors, Redis CPU/memory, and ~100 external synthetic canary cameras whose heartbeats traverse the public internet load balancers so operators instantly know whether an issue lies in our pipeline or in customer networks.Summary of key trade-offs
- Device push + precomputed read snapshots over server polling or per-request scans: works smoothly across customer NAT firewalls and keeps Redis read load constant (
1 query/s) regardless of how many thousands of dashboards refresh. - Sharded Redis Sorted Sets (
~150 MB) + 24 h Kafka log over a raw SQL/time-series database (864 GB/day): deliversO(log N + M)offline queries with zero wasted disk indexing while recovering wiped shards from70 secondsof 2 co-partitioned Kafka logs in~2 seconds. - Watermark-anchored cutoff over wall-clock cutoff: converts ingestion spikes into a visible
as_ofdelay of a few seconds instead of falsely marking healthy cameras offline. - Aging scores in Sorted Sets over per-key 60-second TTLs: avoids lossy expiry Pub/Sub and full-registry scans while naturally surfacing newly provisioned cameras (
score = 0) that have never reported.
- Redis write throughput:
Intuition & how it works
Think of this system like a long timecard rail sorted from oldest check-in on the left to newest check-in on the right, photographed once a second for everyone watching. Every registered camera starts on the far-left peg (score = 0, meaning "never checked in"). Whenever a camera sends its 10-second heartbeat, a worker plucks its card and moves it to the far-right "just seen" end using a Redis Sorted Set (ZSET)—an in-memory collection that keeps unique IDs continuously sorted by numeric timestamp so updates take O(log N) time. Once a second, a single Snapshot Builder slides a divider to 60 seconds ago and reads only the cards sitting to the left of that divider in O(log N + M) time (M = offline cameras), ignoring the 99% of healthy cards on the right completely, and publishes a compressed snapshot that API servers slice into pages from memory.
Why do the obvious approaches fail? Scanning all 1,000,000 camera records on every GET /cameras/offline request wastes 99% of its CPU reading healthy cameras and melts storage during an outage when thousands of operators hit refresh simultaneously. Writing every heartbeat into a relational or time-series database adds 100,000 indexed disk inserts per second (864 GB/day) for historical rows the endpoint never reads. Conversely, setting a 60-second Time-To-Live (TTL) (an automatic key-deletion timer) on 1,000,000 separate Redis keys deletes silent cameras cleanly, yet leaves no way to list which keys vanished without scanning all 1,000,000 registry IDs anyway!
Trace four cameras (cam-101 through cam-104) inside one shard to see how updates, retries, and GET /cameras/offline behave:
Provisioning seed (ZADD NX 0): [cam-101: 0] -> [cam-102: 0] -> [cam-103: 0] -> [cam-104: 0]
1. Normal check-ins up to t = 116,000 ms (cam-104 was never plugged in; cam-102 lost power at t = 30,000):
ZADD XX GT moves active cameras right:
[cam-104: 0] -> [cam-102: 30,000] -> [cam-103: 112,000] -> [cam-101: 116,000]
2. Out-of-order network retry arrives for cam-101 with older timestamp 105,000 ms:
ZADD XX GT checks 105,000 > 116,000 -> False! Redis ignores it so cam-101 never moves backward.
3. Snapshot Builder runs at ingestion watermark = 120,000 ms -> cutoff = 120,000 - 60,000 = 60,000 ms:
ZRANGE hb:0 -inf (60000 BYSCORE WITHSCORES
-> Walks left-to-right and stops as soon as it hits cam-103 (112,000 >= 60,000)!
-> Returns ONLY [(cam-104, null), (cam-102, 30000)] without ever touching cam-103 or cam-101.
Key trade-offs
- Redis Sorted Sets (
~150 MB) + Kafka log vs. a persistent database of raw heartbeats. Keeping only the newest timestamp per camera in Redis answers offline range queries inO(log N + M)and avoids100Kindexed disk writes/s (864 GB/day). Durability comes from Kafka (an unindexed, append-only disk log with 24-hour auto-expiry): by mapping32Kafka partitions (crc32(id) % 32) cleanly onto16Redis shards (partition % 16), a wiped Redis shard is rebuilt in~1–2 secondsby replaying just the last70 seconds(~438Krecords) of its 2 Kafka partitions. - Buffering through Kafka vs. writing directly from Gateways to Redis. Direct Redis writes remove a hop and work at
100K/sin calm weather, whereas buffering in Kafka absorbs300K/snetwork-recovery spikes as sequential disk appends, survives Redis primary failovers with zero dropped data, and enables70-second shard rebuilds. The trade-off is maintaining an event-time watermark so queue delay never looks like camera silence. - Device push vs. server pull (and precomputed snapshots vs. per-request scans). Cameras sit behind customer NAT (Network Address Translation) routers and firewalls that block inbound server polling, so devices must push heartbeats outbound over persistent mutual TLS (mTLS) connections (where cryptographic device certificates prevent spoofing). On the read side, precomputing one snapshot per second makes Redis load constant (
16tiny queries/s) whether1or10,000dashboards are open, trading up to ~1 second of snapshot age. - Watermark-anchored cutoff vs. wall-clock cutoff. Defining
cutoff = min_partition_watermark - 60 sensures that if State Writers fall 15 seconds behind during a spike,as_ofadvances 15 seconds late instead of falsely marking healthy cameras offline while their heartbeats wait in Kafka. The price is emitting lightweight 1-second gateway ticks so idle partitions keep advancing their watermarks. - Aging scores (
ZADD XX GT) vs. per-key 60-second TTLs. Keeping all registered cameras permanently inside the Sorted Set surfaces never-connected cameras (score = 0), ignores out-of-order retries (GT), blocks decommissioned stragglers (XX), and avoids Redis's lazily delayed, lossy keyspace-expiry Pub/Sub notifications. - Micro-batch coalescing + pipelining vs. per-heartbeat Redis round trips. Grouping 50 ms of records per writer collapses rapid duplicate retries into a single
ZADDand packs thousands of updates into one pipelined TCP write, slashing Redis CPU at the cost of<= 50 mslatency.
Common mistakes
- Scanning all 1,000,000 cameras on every API request (via SQL
SELECTor RedisSCAN), which wastes 99% of its work on online cameras and collapses when incident responders refresh the dashboard. - Tracking only cameras that have sent at least one heartbeat, causing brand-new cameras that failed right out of the box to be invisible on
GET /cameras/offlineinstead of seeded atscore = 0from the provisioning registry. - Trusting the client's JSON
timestamp, which lets a camera with a clock stuck in2030pin itsZADD GTscore in the future and appear"online"forever even when unplugged. - Calling
ZADDwithoutGT, allowing a delayed retry from an earlier 10-second tick to overwrite a newer timestamp and falsely push a healthy camera below the 60-second cutoff. - Using per-camera keys with
EX 60TTLs and Redis keyspace notifications, which cannot list already-expired keys without a full registry scan and loses offline events whenever a Pub/Sub subscriber blips. - Computing
cutoff = wall_clock - 60 sbehind an asynchronous queue, turning any temporary consumer lag into a fake mass outage. - Persisting all 864 GB/day of raw heartbeats into Postgres or Cassandra when the functional spec asks only for current offline status.
- Returning an unpaginated JSON array from
GET /cameras/offline(or paginating with rawOFFSETagainst a live changing Sorted Set), which balloons to ~17 MB per call during a blackout and skips/duplicates rows between pages. - Using Python's randomized
hash(camera_id)across multiple worker processes, routing the same camera to different Redis shards on different pods instead of using a deterministic hash likecrc32.
Follow-up questions
- What changes would you make to compute a rolling 24-hour uptime percentage per camera? Store a per-camera daily bitmap in Redis (
uptime:{utc_day}:{camera_id}) with1,440bits—one bit for each minute of the day (1,440 bits = 180 bytesper camera, or just~180 MB/dayfor all 1,000,000 cameras!). When a State Writer processes a heartbeat, it sets the bit forminute_of_day(received_at_ms)viaSETBITonly the first time that camera reports in a new minute (~16.7Kidempotent writes/s across the cluster, replay-safe because the bit index comes fromreceived_at_msrather than wall time). Rolling 24-hour uptime is computed in microseconds by counting set bits across today's slice and yesterday's tail slice (BITCOUNT ... BITin Redis 7+, divided by1,440minus any minutes marked degraded in a single fleet-widepipeline_up:{utc_day}bitmap so our own downtime never penalizes customer SLAs), with finished daily bitmaps archived to S3/ClickHouse after 48 hours—or paired with an append-only(camera_id, went_offline_at, came_back_at)interval table emitted by Snapshot Builder diffs if exact 1-second boundary precision is required. - If firmware begins transmitting heartbeats once per second instead of every 10 seconds, how would you adapt ingestion so downstream stores are not overwhelmed? First clarify whether the offline threshold is still 60 seconds or also shrinking to ~3–5 seconds. If the threshold stays
60 s,1,000,000messages/s carry 10x redundant liveness traffic, so scale the stateless Ingestion Gateways (persistent HTTP/2 or MQTT connections are mandatory here) and coalesce in gateway RAM: acknowledge every 1-second packet locally while forwarding at most 1 heartbeat per camera every 5 seconds to Kafka, keeping Kafka and Redis at<= 200,000 writes/s(2xcurrent load) while losing at most5 sof precision on a60 swindow. If the threshold itself shrinks to~3–5 seconds, every packet matters: scale out to64–128Kafka partitions and either widen Redis to~12–16primaries (~75KpipelinedZADD/seach) or eliminate cross-network Redis writes altogether by movinglast_seeninto the local memory of partitioned stream consumers using anO(1)circular timer wheel, firing snapshots every250–500 ms. - Suppose a regional blackout knocks hundreds of thousands of cameras offline at once—how do you prevent simultaneous operator refreshes and device reconnections from overloading the system? A thundering herd happens when thousands of startled operators and automated scripts simultaneously hammer the backend for a suddenly huge (
~200,000-camera) offline list—followed minutes later by200,000cameras reconnecting the instant power returns. On the dashboard read side, our Snapshot Builder already insulates Redis completely (still running just1query/s regardless of viewer count), API servers use single-flight (request coalescing) so each pod fetches a new compressed snapshot version once into local RAM and slices5,000-item cursor pages in memory, the UI loads lightweight regional/site counts from/cameras/offline/summaryfirst (drilling into IDs only on click) or subscribes to delta updates over Server-Sent Events (SSE) (a one-way HTTP stream pushing incremental changes), and alerts group into one regional incident notification instead of200,000emails. On the power-restoration side, camera firmware reconnects using exponential backoff with jitter plus TLS session resumption, gateways enforce per-second connection-accept caps, Kafka absorbs the reconnect spike, and our watermark prevents temporary writer lag from causing false offline flaps.
Follow-up questions
- What changes would you make to compute a rolling 24-hour uptime percentage per camera?
- If firmware begins transmitting heartbeats once per second instead of every 10 seconds, how would you adapt ingestion so downstream stores are not overwhelmed?
- Suppose a regional blackout knocks hundreds of thousands of cameras offline at once—how do you prevent simultaneous operator refreshes and device reconnections from overloading the system?
Similar questions
- Hierarchical Camera Authorization Service
- Camera Fleet Health Monitoring
- Windowed IoT Status Count Pipeline
- Fault-Tolerant Distributed Matrix Transpose
- Filterable Camera Dashboard
- Extract and Unify Camera Alert Windows
More Verkada interview questions
- Detect Contiguous Active Sensor Windows Medium
- Camera Log Ingestion and Query API Server Medium
- Find the User Reaching All Cameras via Transitive Group Membership Medium Pro
- Design O(1) LRU and LFU In-Memory Caches Medium Pro
- Score Letter Feedback for Word Guesses Hard Pro
- Simultaneous High-Motion Intervals Across Camera Feeds Hard Pro
- Constant-Memory Generator Parser for Quoted Key-Value Logs Medium Pro
- Filterable Camera Dashboard Medium Pro
- Camera Fleet Health Monitoring Medium Pro
- Hierarchical Camera Authorization Service Hard Pro