Designing a Data Integrity System for Multi-Store Order Data
System DesignModel answerLast updated
Design a validation and reconciliation pipeline that enforces order-book correctness across a set of loosely coupled databases with different freshness guarantees.
Scenario
A trading platform ingests market data and internal order activity and fans it out into four stores:
- Raw feed store — append-only log of every exchange message, keyed by venue, channel, session, and sequence number.
- Normalized order store — one row per order lifecycle event in a canonical schema.
- Execution store — records of trades and fills.
- Analytics store — aggregated bars, snapshots, and derived metrics in a columnar format.
Each store is written by a different pipeline. They are eventually consistent with one another, not immediately so. Data quality regressions have been noticed: fill quantities that don't add up, sequence gaps that weren't flagged, and analytics snapshots that don't match the raw feed.
What you are asked to design
Walk through a complete validation and reconciliation system for this architecture. Your answer should cover:
-
Invariants — What rules must always hold for orders, executions, and the live book? State them precisely enough that they could be turned into automated checks.
-
Single-store validation — How do you enforce and detect violations within one store? Consider both schema-level constraints and batch analytical checks.
-
Cross-store reconciliation — How do you compare stores that may be at different points in time? How do you distinguish "not arrived yet" from "genuinely lost"? What do you actually compare, and at what granularity?
-
Edge cases — How does your approach handle partial fills, order replacements (modify/cancel-replace), out-of-order message delivery, duplicate messages, and reconnect replays from exchanges?
-
Operationalizing it — How does the system surface problems? Think about alerts, dashboards, SLAs, and what a backfill looks like when a bug is found and fixed.
Be concrete: name the things you would compute, the comparisons you would make, and the thresholds or grace periods you would apply.
Hints
Hint 1
Start by defining the order lifecycle as an explicit state machine. Every invariant you care about either protects a state transition or enforces a numeric conservation law. Getting these written down precisely is more than half the answer.
Hint 2
Eventual consistency means a mismatch at time T might be fine by time T+10m. The design trick is watermarks: only compare a range once all stores declare they are complete through it. Define what 'complete' means per store, and define an SLA for how long a gap can stay in PENDING before it becomes an alert.
Hint 3
Don't diff billions of rows directly. Use order-independent fingerprints (e.g., sum of row hashes) bucketed by time and symbol, then recurse into finer buckets only where the fingerprints disagree. This is essentially a Merkle tree over time, and it makes drill-down cost proportional to the number of bad rows rather than total volume.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
How to approach this
This is a data-integrity design problem set in a financial context. A strong answer demonstrates four things: you know order-book semantics well enough to write down checkable invariants; you treat the raw feed as the source of truth from which everything else is derived; you have a concrete plan for reconciling stores that move at different speeds without generating constant false alarms; and you can describe the operational layer that makes it a running system, not a one-off script.
1. Clarify scale and scope first
Before designing anything, nail down a few assumptions. Call out volume (say 10–50B raw messages per day, peaks of a few million per second), the number of venues (around 15), and the validation cadence you are targeting. A reasonable split is: lightweight streaming checks for the most urgent, cheapest invariants (sequence gaps), intraday batch checks every 5–15 minutes, and a full end-of-day pass. Partitioning all checks by (trade_date, venue, symbol) is the natural choice because that is also the unit of replay and backfill.
2. Invariants
Group them into four categories so they map cleanly onto check types.
Sequence / feed integrity
seq_nois strictly increasing and contiguous per(venue, channel, session). Any gap must be explained by a recorded gap-fill or snapshot recovery event.- Each
seq_noappears exactly once after deduplication. - Exchange timestamps are non-decreasing in sequence order.
- Receive timestamp is ≥ exchange timestamp minus a configurable clock-skew tolerance (typically 50–500 ms depending on the venue).
Order state machine
- Legal transitions are:
NEW → (PARTIAL_FILL)* → {FILLED | CANCELED | EXPIRED}, orNEW → REPLACEDwhere the old order id is terminal and the new one is linked viaorig_order_id. - No events may follow a terminal state.
- Every non-NEW event must reference an order that already exists in the store.
Quantity conservation
cum_qty + leaves_qty + canceled_qty = order_qtyat every point in time.cum_qtyis monotonically non-decreasing across events for the same order.leaves_qty ≥ 0, and every individual fill quantity is strictly positive.cum_qtyequals the sum of fill quantities across all execution records for that order.
Book-level consistency
- The displayed quantity at each price level equals the sum of
leaves_qtyof all resting orders at that level. - During continuous trading the book is not crossed (
best_bid < best_ask). Crossed or locked books are only permitted during auctions, halts, or venue-specific conditions that are explicitly whitelisted. - The book rebuilt by replaying raw L3 events must match stored analytics snapshots at the same sequence number.
3. Validation within one store
Schema constraints are the cheapest line of defense and should be applied wherever the storage engine supports them: UNIQUE(venue, channel, session, seq_no) in the raw store, CHECK(qty > 0), CHECK(leaves_qty >= 0), NOT NULL on all keys, and a foreign key from executions to orders where write latency permits it. These catch structurally malformed rows at write time but cannot catch multi-row violations.
Batch checks handle the rest. Run them as SQL window queries or a Spark job per partition:
- Gap detection:
seq_no - LAG(seq_no) OVER (...) != 1 - Monotonic
cum_qty:LAGcomparison over events ordered within eachorder_id - Conservation:
GROUP BY order_idcomparingorder_qtyagainst the sum of its parts - State-machine violations: encode allowed
(prev_state, next_state)pairs as a small reference table and anti-join against observed transitions
Deterministic replay is the strongest single-store check. A replay engine consumes raw events in sequence order for one (date, venue, symbol) partition and rebuilds the book from scratch. At each snapshot boundary it asserts no crossed book, correct level totals, and no reference to an unknown order. This engine is the reference implementation of order-book logic; everything else is validated against its output.
4. Cross-store reconciliation
The central problem is distinguishing "not yet arrived" from "genuinely missing." The solution is watermarks.
Each store publishes a completeness watermark per partition — for example, "normalized is complete through raw seq_no N for venue X as of wall-clock time T." Reconciliation only covers ranges up to min(all watermarks) − grace_period. A mismatch within the grace period gets status PENDING. If it persists past the SLA (15 minutes intraday, end-of-day for the full pass), it flips to FAILED and triggers an alert.
Compare aggregates first, then drill down. Never diff billions of raw rows directly. For each (venue, symbol, minute) bucket in each store, compute:
- event counts by type (new, cancel, replace, fill)
SUM(qty)andSUM(qty × price)(notional)COUNT DISTINCT order_id- an order-independent fingerprint:
SUM(hash64(canonical_row)) mod 2^64
The fingerprint is order-independent, so it tolerates parallel writes and out-of-order arrival. If a bucket's fingerprint differs, recurse into 1-second sub-buckets, then into row-level diffs. This is a Merkle tree over time: drill-down cost scales with the number of bad rows, not total volume.
Pairwise checks along the lineage:
| Pair | What to compare |
|---|---|
| Raw → Normalized | Re-normalize raw with the current versioned normalizer; fingerprints must match. Every raw message maps to exactly one normalized event unless it is a recorded administrative drop. |
| Normalized → Executions | Every fill event maps to an execution row with matching (venue, trade_id, qty, price). Bucket-level volume and notional must match. |
| Executions → Analytics | Bar volume, VWAP, and high/low recomputed from executions must match stored values (within float epsilon for VWAP). Book snapshots must match replay output at the same sequence number. |
| Internal fills → External confirms | Internal execution records must match exchange drop copies and clearing reports. This is the business-critical check; failures here are escalated immediately. |
Canonicalization before comparing. Prices as integer ticks, quantities as integer lots, timestamps in UTC microseconds, all string fields trimmed and uppercased. Without this, floating-point and encoding differences generate false positives constantly.
5. Edge cases
- Partial fills: check conservation at every intermediate event, not just at order close. A common bug is only validating the terminal state.
- Cancel-replace: treat as two linked orders. The original reaches a terminal
REPLACEDstate; the replacement carriesorig_order_id. Validate each separately and validate the link. - Out-of-order delivery: the raw store is append-only in receive order. Re-sort by
(session, seq_no)before any replay or state-machine check. Never assume physical row order equals logical event order. - Duplicates and replays: the dedup key is
(venue, channel, session, seq_no). Exchange reconnect replays will resend the same sequence numbers with the same content; idempotent upserts handle these cleanly. Flag any case where the same key arrives with different content — that is a data corruption signal, not a duplicate.
6. Operationalizing it
- Rule registry: each invariant is a named, versioned rule with an owner, severity, and SLA. Rules are disabled during known market phases (auction, halt) that would generate expected violations.
- Results store: every check run writes
(rule_id, partition, run_ts, status, bad_row_count, sample_keys). This enables trend graphs and distinguishes a new failure from a known ongoing one. - Alerts: sequence gaps and fill-conservation failures are P1 (page immediately). Cross-store fingerprint mismatches within SLA are P2 (ticket). Persistent mismatches past SLA escalate automatically.
- Backfill: when a bug is fixed, the backfill job replays the affected
(date, venue, symbol)partitions through the corrected pipeline and reruns all checks against the updated output. Partitioning by natural trading unit makes this cheap and safe to re-run without touching other data.
Common mistakes to avoid
- Validating only terminal order states and missing mid-lifecycle conservation violations.
- Comparing stores without watermarks, generating floods of false-positive alerts during normal catch-up.
- Diffing at row level instead of using hierarchical fingerprints, making checks too slow to run frequently.
- Forgetting to canonicalize fields before comparison, especially prices stored as floats in one store and integers in another.
- Treating a duplicate sequence number with different content as a normal replay rather than a corruption event.