Real-Time Analytics Dashboard: Range Queries and Event-Time Completeness
System DesignModel answerLast updated
Design a backend that turns a live event stream into dashboard metrics, serves arbitrary time-range queries from rollups, and uses watermarks to decide when event-time windows are final.
You are asked to design the backend of an analytics dashboard. Its charts are computed from a never-ending stream of events (for example page views, API calls, or purchases), and users can pick any time range to inspect.
Walk through your design as you would in a conversation with an interviewer. Two areas deserve particular depth:
- Range queries. How does the system answer "show me metric X between time A and time B" quickly, whether the range is the last 15 minutes or the last 90 days?
- Watermarks. How does the stream processor decide that a time window is complete when events can arrive late or out of order? What happens to events that show up after that decision?
The scope is deliberately underspecified. The metrics shown, event volume, freshness target, allowed lateness, retention, and number of dashboard viewers are all unknown. Ask clarifying questions or state explicit assumptions before committing to an architecture.
A strong answer should cover:
- Your assumptions about metrics, freshness, lateness, and query shapes
- An end-to-end pipeline: ingestion, windowed aggregation, storage, and a query service
- Which metrics can be combined exactly across buckets (counts, sums) and which need special structures (percentiles, distinct counts)
- What a watermark asserts, how it is generated, and the freshness-versus-completeness trade-off
- Failure handling and observability: replay, idempotent writes, backfills, and monitoring of pipeline lag
Hints
Hint 1
Pin down the query shapes first. Short recent ranges want fine granularity, long ranges tolerate coarse granularity. That suggests storing the same metric at several resolutions.
Hint 2
Ask which metrics are mergeable. Sums and counts add across buckets, but a percentile of percentiles is wrong, and distinct counts cannot be summed. Think about mergeable sketches.
Hint 3
A watermark is a claim of the form 'no more events with event time earlier than T are expected'. Consider how it is derived (max observed event time minus a delay, per partition, then the minimum across partitions) and what you do with events that violate it.
Hint 4
Separate the speed path from the correction path: emit provisional results early, finalize on watermark, and reconcile later arrivals via updates or a batch backfill.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Assumptions (stated up front)
- Metrics: counts, sums, rates, p50/p95/p99 latency, and unique users, sliced by a handful of low-cardinality dimensions (region, product, status).
- Volume: about 100k events/s peak, roughly 8 billion per day.
- Freshness: the newest data should appear within about 10 to 30 seconds; the most recent minutes may be marked provisional.
- Lateness: most events arrive within seconds, but mobile clients may deliver up to 10 minutes late, and a small tail up to 24 hours.
- Queries: last 15 minutes to last 90 days, with resolutions of 1 minute, 1 hour, and 1 day. Retention is 7 days for raw events, 30 days at 1-minute resolution, and 13 months at hourly/daily resolution.
- Hundreds of concurrent viewers, so reads must be cheap and cacheable.
Pipeline
- Ingestion. Producers write to a partitioned log (Kafka-style), keyed so that events of one entity stay ordered within a partition. The log is the source of truth and enables replay.
- Stream aggregation. A stream processor (Flink or similar) assigns each event to tumbling windows by event time (not arrival time) and computes partial aggregates per (metric, dimensions, window). Raw events are also archived to object storage for backfills.
- Storage. Pre-aggregated buckets go to a time-series or columnar store (ClickHouse, Druid, Pinot, or a time-partitioned table) at three granularities: 1 minute, 1 hour, 1 day. Hourly and daily rollups are produced by merging finer buckets.
- Query service. Accepts (metric, dimensions, range, step), picks the coarsest granularity that satisfies the step, and merges buckets. A cache keyed by (query, aligned range) serves repeated reads; only the trailing, still-changing edge is recomputed.
Answering range queries
Never scan raw events for dashboard queries. Decompose the range [A, B) into aligned pieces: partial edges at fine granularity, the middle at the coarsest granularity that fits. For example, 3 days and 2 hours becomes some 1-minute buckets at each edge, hourly buckets for the partial days, and daily buckets for the full days. A 90-day chart at daily resolution reads about 90 rows per series instead of billions.
Mergeability matters:
- Counts, sums, min, max: merge exactly by addition or comparison. Averages are stored as (sum, count), never as a precomputed mean.
- Percentiles: do not average percentiles. Store a mergeable sketch (t-digest, DDSketch, or HDR histogram) per bucket and merge sketches at query time. Error is bounded and tunable.
- Distinct counts: store HyperLogLog sketches per bucket; union is exact in the sketch sense, giving about 1 to 2 percent error. Exact distinct counts over arbitrary ranges require raw data and are expensive, so state the trade-off.
- High-cardinality dimensions: limit pre-aggregated dimension combinations, or roll up only the top N and push the rest to an ad hoc path.
Watermarks
Events carry an event time, but they arrive in processing time, out of order and late. A watermark is the processor's running assertion: "I believe no further events with event time ≤ T will arrive." When the watermark passes the end of a window, the window can be closed and its result finalized.
Generation: a common heuristic is watermark = max event time seen − allowed out-of-orderness (say 10 minutes). With many partitions, each partition has its own watermark and the operator uses the minimum across them. An idle partition would stall everything, so configure idle-partition detection to exclude it after a timeout.
Trade-off: a small delay yields low latency but more late events; a large delay yields completeness but stale charts and more state held in memory. This is why the dashboard emits provisional results early (on a timer, say every 10 seconds) and a final result when the watermark passes.
Late events (event time behind the watermark) have a few options:
- Allowed lateness: keep window state for an extra period (for example 1 hour). A late event triggers an updated result, written as an upsert to the same bucket key.
- Side output: beyond allowed lateness, route to a late-events stream and dead-letter store, with a metric on the late rate.
- Batch correction: a periodic job recomputes closed buckets from the archived raw events and overwrites them, so long-tail lateness is eventually correct.
Because updates overwrite buckets, hourly and daily rollups must be recomputed (or incrementally corrected) when a finer bucket changes.
Reliability and operations
- Exactly-once effect: checkpoint processor state together with log offsets, and write buckets as idempotent upserts keyed by (metric, dimensions, window start). Replays then do not double count.
- Backfills: reprocess from the log or archive into a shadow table and swap, so users never see half-written data.
- Observability: track consumer lag, watermark lag (now minus watermark), late-event rate, state size, and query latency percentiles. Alert when watermark lag exceeds the freshness target.
- Scaling: partition by hash of the key, scale processor parallelism with partitions, and shard the store by time and dimensions. Cache and precompute popular dashboard queries.
Common mistakes
- Windowing by arrival time, which makes charts depend on network delays.
- Averaging averages or percentiles across buckets.
- Treating the watermark as a guarantee; it is a heuristic, and late data must still have a defined path.
- Letting one idle partition freeze the watermark.
- Non-idempotent writes, which double count after a restart.
- Querying raw events for long ranges instead of using rollups.