Fast Dashboards and Auditable Finance Tables from One Event Stream
System DesignModel answerLast updated
Design a marketplace order-event pipeline that serves five-minute operational metrics and a reproducible next-morning finance table, weighing batch, streaming, and hybrid approaches.
Scenario
You are the data architect for an online marketplace. Order lifecycle events (placed, paid, shipped, cancelled, refunded, and so on) flow in continuously. The feed is messy: events can be duplicated, arrive late, or arrive out of order. Two groups depend on the data:
- Product teams want operational metrics (orders, revenue, cancellations) that are no more than five minutes behind.
- Finance wants a daily table, available the next morning, that can be regenerated exactly for a stated input version.
Historical corrections and event-schema changes are both expected over time.
Given facts
- Every event has a stable event ID, an event-time timestamp, and an order ID.
- The source can replay retained events, but consumers must not assume exactly-once delivery over the network.
- The operational view may be eventually consistent. The finance table must be reproducible.
- Pick technologies by capability, not by vendor.
- Privacy, access control, and deletion requests are part of the design.
What to cover
1. Choose the processing model. Compare batch, streaming, and hybrid designs on latency, correctness, operational complexity, replay, and cost. Make a recommendation and say what evidence would change it.
2. Design the data flow. Walk through ingestion, durable storage, validation, deduplication, event-time handling, stateful computation, batch finalization, metadata, and serving. Explain how data contracts and schema evolution are handled.
3. Operate and validate. Explain how you would roll out changes, detect wrong-but-healthy output, recover from failures, and check that the fast view and the finalized view agree within their documented semantics.
Before designing, list the clarifying questions you would ask (volume and peak rate, what "five minutes" actually measures, how late events can be, joins against mutable reference data, and whether consumers need updates and retractions or only appended versions) and state the assumptions you adopt.
Hints
Hint 1
Begin with the two service levels rather than defaulting to streaming: one is about how quickly an answer appears, the other about how much that answer can be trusted and reproduced.
Hint 2
Keep an immutable raw copy of every event so corrected logic can be rerun later, and decide for every write boundary what makes a retry harmless (deterministic keys, upserts, atomic swaps).
Hint 3
Healthy infrastructure does not imply correct numbers. Think about monitoring freshness, volume, duplicate rates, late-event rates and reconciliation between the fast and final outputs.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Core idea
The problem combines two different needs that are easy to conflate:
- Speed of an answer: product metrics within about five minutes, eventual consistency acceptable.
- Authority of an answer: a finance table that is complete, deduplicated, and reproducible for a declared input version.
Derive the architecture from those two requirements instead of picking a technology first.
Assumptions to state
- About 50M orders/day with roughly 10 events each gives about 500M events/day, around 6k events/s on average and perhaps 60k/s at peak. At about 1 KB per event that is roughly 500 GB/day raw.
- "Five minutes" means event-time freshness at the dashboard: p95 of (now minus the newest event time included) stays under five minutes.
- About 99.9% of events arrive within 10 minutes, but a tail (mobile retries, partner backfills) can arrive days late.
- The log retains 7 days. Raw storage is kept long term, subject to deletion policy. Operational recovery target is under one hour. Finance data is due by 06:00.
Part 1: Processing model
| Batch only | Streaming only | Hybrid | |
|---|---|---|---|
| Latency | Hours | Seconds to minutes | Minutes for ops, daily for finance |
| Correctness | Strong, sees all data | Approximate under late data | Each view correct for its declared semantics |
| Replay | Rerun the job | Hard: state rebuild, retention limits | Batch reruns from raw, stream rebuilds from log |
| Complexity | Low | High (state, watermarks, checkpoints) | Highest unless logic is shared |
| Cost | Lowest | Always-on compute | Both, but the streaming part is small |
Recommendation: hybrid. A streaming job feeds the operational metrics. A batch job over immutable raw storage produces the authoritative finance table. Both read from the same ingested log and share transformation logic (a common library or the same SQL definitions), so the two outputs cannot silently drift. This avoids the classic two-codebase Lambda problem.
What would change the answer:
- If product could accept hourly freshness, use micro-batch only.
- If the stream engine can replay from a long-retention table format and finance accepts "stream output plus a declared cutoff snapshot", a single-codebase Kappa-style design works.
- At small volume, one database with materialized views may be enough.
Part 2: Data flow
- Ingestion. Producers write to a partitioned, replicated log keyed by
order_id, preserving per-order ordering. Acknowledge only after replication. Each event carries a schema ID from a registry. - Raw landing. A sink writes the log to object storage in an open table format, partitioned by ingestion time so late events never rewrite old partitions. File names derive from partition and offset range, so retries overwrite identical files. This is the replay source of truth.
- Validation and contracts. Check required fields, types, enums, and plausible event time (for example, not far in the future). Failures go to a quarantine table with a reason code and are never silently dropped. Schema changes must be backward-compatible (additive, optional fields), enforced by the registry. Breaking changes use a new versioned topic with a dual-write migration window.
- Deduplication.
- Stream: keyed state on
event_idwith a TTL longer than the lateness bound (say 24 hours). Best effort beyond that. - Batch: global distinct on
event_idover the full input. This result is authoritative.
- Stream: keyed state on
- Event-time handling (stream). One-minute tumbling event-time windows, watermark at max event time minus 10 minutes, allowed lateness of about an hour with updates emitted to already-published windows. Anything later goes to a side output and is counted.
- Stateful computation. Track order lifecycle state (placed, paid, refunded) so metrics use the latest state per order rather than summing every event. Joins with mutable reference data use a versioned snapshot or a temporal join, and the choice is documented.
- Batch finalization. At about 02:00, declare an input version: the raw table snapshot ID, the code version, and reference-data snapshot IDs. Select events whose event time falls in day D, deduplicate, apply business rules, and publish partition D as a new immutable version through an atomic swap.
- Metadata and lineage. Record for each output version its input snapshot IDs, code commit, row counts, and checksums. Rerunning with the same manifest reproduces the same result. That is the audit story.
- Serving. Operational metrics are upserted into an OLAP store keyed by (window, dimensions), so replays converge instead of double counting. Finance reads views pinned to the published version.
- Privacy and access.
- Keep PII out of event bodies; tokenize it or store it in a separately controlled table.
- Apply column- and row-level access controls; finance tables are read-only for analysts.
- For erasure requests, delete the token mapping (crypto-shredding) so immutable raw files stay valid without exposing personal data, and use table-format deletes with snapshot expiry where physical removal is required.
- Define reproducibility as "modulo legally erased PII" and say so explicitly.
Part 3: Operations and validation
Deploying changes
- Version every job. Run streaming changes as a shadow pipeline writing to a parallel table, compare for a day, then cut over.
- Batch logic changes backfill into a new table version, are diffed against the current one, and are published after sign-off.
- Finance-facing changes are announced through a visible change log.
Detecting wrong-but-healthy output
- Freshness: event-time lag and watermark lag per partition.
- Volume: row counts versus historical baselines by hour and day of week.
- Quality: duplicate rate, quarantine rate, null rates, late-event side-output rate, schema-version mix.
- Business invariants: for example, refunds never exceed payments, and each order has at most one terminal state.
Reconciliation between views. After finalization, compare the streaming totals for day D with the batch table. Differences should be explainable by late events beyond allowed lateness, TTL-limited dedup, and reference-data timing. Alert if the gap exceeds a stated tolerance (for example 0.5% on order count), and track the gap as a metric over time.
Recovery
- Stream failure: restart from checkpoint; if state is lost, replay from the log (within retention) and rely on idempotent upserts.
- Bad logic or bad data: fix, rerun batch from raw for the affected days, publish a new version, and let the operational view be corrected by a replay or overwritten by the final numbers.
- Late corrections to finalized periods: publish a new version of the partition with a recorded reason, never mutate in place; consumers needing stability pin to a version.
Trade-offs and common mistakes
- Defaulting to streaming for everything and then being unable to reproduce finance numbers.
- Two independent codebases for stream and batch that drift apart.
- Partitioning raw data by event time, which forces constant rewrites for late data.
- Treating at-least-once delivery as exactly-once; idempotency must be designed at each sink.
- Ignoring deletion and PII until after the raw layer is immutable.
- Monitoring only CPU and lag, not data behavior.
- Not stating what "five minutes" measures.
Summary
Use a hybrid: a lightweight streaming path for fast, eventually consistent metrics and a batch path over immutable raw data for authoritative, versioned finance output, both sharing business logic. Make every write idempotent, make every published result traceable to an input manifest, and validate continuously by reconciling the two views.