Marketplace, Dispatch, and Logistics System Design Questions
Designing two-sided marketplaces and real-time operational platforms end to end, where the domain shapes the architecture: rider/driver and order/courier matching and dispatch (batched vs greedy assignment, single-assignment guarantees, re-matching, pooling), order, booking and inventory flows (holds, double-booking prevention, quote-to-checkout price honoring), surge and dynamic pricing systems (demand/supply signals, damping, caps and fairness controls, pricing rules), ETA and routing services (road graphs, time-dependent weights, map-matching, traffic fusion, degraded modes), proximity-driven matching over moving supply (geo-partitioned matchers, hotspot rebalancing, boundary effects), and real-time location tracking. Covers the canonical ride-hailing, food/parcel delivery, and booking marketplace case studies and the consistency, latency, and scale challenges they share. Generic building blocks used by these designs (caching, rate limiting, sagas, stream-processing internals, spatial index primitives, observability, deployment) are covered by their own topics.
Design an order routing and fulfillment decision system for a marketplace processing 1,000,000 orders/day. Requirements: minimize total delivery cost while meeting SLAs (95% on-time), support multi-warehouse inventory, carrier selection with live capacity, retries and fallbacks; make routing decisions within 200ms per order at peak. Outline architecture, data stores, matching algorithm approach, caching strategy, coordination between services, scaling plan, and success metrics.
Sample Answer
Direct answer
I would split the problem in two: a slow planner that every few minutes looks at the whole network (warehouse backlogs, carrier capacity, SLA risk) and publishes a small set of "prices" for scarce resources, and a fast per-order decider that, within 200 ms, enumerates the feasible warehouse-and-carrier options for one order, drops those that break hard rules, and picks the lowest expected cost, where expected cost includes a penalty for the chance of being late and the planner's price for using a nearly full carrier. The decision is committed by atomically reserving inventory and carrier capacity, with a pre-computed fallback if either reservation fails. Success is measured by on-time rate against the 95% SLA, cost per order, and decision latency at the 99th percentile.
Requirements and load
- 1,000,000 orders/day is 1,000,000 / 86,400 ≈ 11.6 orders/s on average. If the busiest hour carries 10% of the day, that is 100,000 / 3,600 ≈ 28 orders/s, and a flash sale at 5 times that is about 139 orders/s. This is modest; the 200 ms budget, not throughput, drives the design.
- SLA (service-level agreement, the promise to customers): 95% of orders delivered by the promised date.
- Each order may be fulfilled from several warehouses (possibly split across them) and by several carriers whose daily pickup capacity is live and limited.
Architecture
flowchart LR
OS[Order service] --> RD[Routing decider]
RD --> INV[Inventory service]
RD --> CAP[Carrier capacity service]
RD --> RULES[Rules and overrides]
RD --> RATES[Rate and transit-time cache]
PL[Network planner] --> PRICES[Shadow prices]
PRICES --> RD
RD --> EV[Decision log]
EV --> PL
CAR[Carrier APIs] --> CAP
| Component | Responsibility | Data store |
|---|---|---|
| Routing decider (stateless) | Per-order enumerate, filter, score, reserve | None of its own |
| Inventory service | Stock per SKU (stock-keeping unit: one sellable product variant) per warehouse; reservations (holds with an expiry) | Relational DB, one row per (SKU, warehouse); reservation rows with TTL (time-to-live) |
| Carrier capacity service | Remaining pickup slots per carrier per warehouse per day | Counters in an in-memory store (Redis or similar) with atomic decrement, re-synced from carrier APIs every few minutes |
| Rate and transit-time cache | Price and transit-time distribution per (carrier, origin zone, destination zone, service level) | Loaded from rate cards and historical delivery data into memory |
| Rules and overrides | Business rules and operator overrides, versioned | Relational DB, cached in the decider with change notifications (the database tells the decider the moment a row changes, instead of the decider polling for updates) |
| Network planner (batch, every 5 min) | Solves a network-level optimization and publishes shadow prices (see the worked $0.80 example below) | Warehouse for history; outputs to a small key-value table |
| Decision log | Every decision with its inputs, for audit, replay and learning | Append-only stream plus warehouse |
Coordination between services: the decider calls inventory, capacity and rules synchronously, but only against local or in-memory data. Carrier APIs are never called on the per-order path: they are slow and unreliable, so capacity is mirrored locally and reconciled asynchronously.
The matching algorithm
- Enumerate options: warehouses that hold every item (plus a small set of two-warehouse splits if no single warehouse can), crossed with carriers that serve the destination. Typically 5 warehouses × 6 carriers = 30 options.
- Filter by hard rules (see precedence below): hazmat restrictions, delivery time window, carrier capacity left.
- Score each remaining carrier by expected cost:
Here pon time is the probability the option arrives by the promise date (from the historical transit-time distribution for that lane), λ is what the business says a late order costs (refunds, support contacts, churn), and the shadow price is the planner's estimate of what one more unit of a scarce resource is worth right now (a nearly full carrier at one warehouse gets a positive price, so orders drift elsewhere before the carrier runs out).
4. Reserve: atomically hold inventory and decrement carrier capacity. If either fails (someone else took the last unit), move to the next-best option. If all fail, fall back to the pre-agreed default (the most reliable carrier from the nearest warehouse with stock) and flag the order.
Worked example. Late penalty λ = $20. Three feasible options:
| Option | Cost | P(on time) | Score |
|---|---|---|---|
| A: East warehouse, carrier X | $6.10 | 0.97 | 6.10 + 20 × 0.03 = 6.70 |
| B: East warehouse, carrier Y | $5.40 | 0.91 | 5.40 + 20 × 0.09 = 7.20 |
| C: Central warehouse, carrier Y | $4.90 | 0.88 | 4.90 + 20 × 0.12 = 7.30 |
A wins although it is the most expensive to ship, because the lateness risk of C costs more than the $1.20 it saves. Now carrier X at East is at 90% of today's capacity and the planner publishes a shadow price of $0.80: A becomes 6.70 + 0.80 = 7.50 and B (7.20) wins. The planner has steered volume off X before X runs out and later, more urgent, orders find nothing.
Concretely, where that $0.80 comes from: the planner solves a linear (network-flow) optimisation over remaining capacity and forecast demand, and a shadow price is that optimisation's dual value on one resource's capacity constraint, i.e., how much total network cost would fall with one more unit of it. If committing carrier X's last slot to this order means a later order on the same lane must fall back to a standby carrier at $6.90 instead of X's own $6.10 base rate, that $6.90 - $6.10 = $0.80 gap is exactly the shadow price the planner publishes for X, refreshed every planning cycle as forecast demand and remaining capacity shift.
Why this meets the 95% SLA: the planner monitors the running on-time rate of committed decisions (the average of pon time over today's orders) and raises λ if it drifts toward 95%. A per-order floor (never choose an option with P(on time) below 0.85) prevents trading away an individual customer for a cheap label.
Why not solve every order jointly? A global optimization across the day's orders is better in theory but cannot run in 200 ms, and orders arrive one at a time. Shadow prices give the per-order decision most of the network-level information at a fraction of the cost. I would switch to micro-batching (collect orders for a few seconds and solve together) only for a fulfillment model where orders are not promised a date at checkout.
Business-rule precedence, rule representation and operator override
Rules are evaluated in a fixed precedence, from strongest to weakest:
- Safety and legal (hazmat, i.e. hazardous materials that need special handling and a certified carrier; restricted destinations): filters, never overridable.
- Time windows (the promised date, carrier cutoff times at the warehouse): filters.
- Capacity (warehouse throughput, carrier slots): filters, with the planner's shadow price as a soft pressure before the hard limit.
- Priority (premium customers, perishable goods): adjusts λ or restricts to faster services.
- Cost: the objective among whatever survives.
Representation: rules are data, not code. Each rule is a row with a scope (SKU category, warehouse, destination region, customer tier), a kind (filter or score adjustment), a precedence level, an effective time range and a version. The decider loads them into an in-memory decision table indexed by scope, so evaluating 30 options against the relevant rules is a few lookups. A rule change is validated by replaying the last day's decision log against the new rule set (how many decisions would change, and at what cost and on-time impact) before it is activated.
Safe manual override: operators sometimes need "send everything from West via carrier Y today, carrier X has a strike". An override is a rule at its own precedence level, above priority and cost but below safety and legal, so it can never route hazmat by a forbidden carrier. Each override carries its author, reason, scope and a mandatory expiry; it is logged, shown on a dashboard with its measured cost impact, and can be put in shadow mode first (evaluated and logged but not applied). An override with no expiry is how a one-day workaround becomes a permanent, forgotten cost.
Caching strategy
- Rates and transit-time distributions: in-process memory in the decider, refreshed hourly; they change rarely.
- Rules: in-process, invalidated on change notification plus a 60 s maximum staleness.
- Inventory: not cached for the decision. Available-to-promise counts (the stock not yet committed to any order, i.e. what can still be promised to a new customer) are cached for display on product pages, but the reservation always goes to the source of truth, because a stale cache there creates oversell.
- Carrier capacity: authoritative counters in memory, since the carrier API is too slow to be the source of truth at decision time; a reconciliation job compares counters with carrier-reported bookings every few minutes and corrects drift.
Latency budget (200 ms at the 99th percentile)
| Step | Budget |
|---|---|
| Load order, candidate warehouses from inventory index | 25 ms |
| Rules and rate lookup (in memory) | 5 ms |
| Scoring 30 options | 5 ms |
| Inventory reservation (conditional update: a write that only succeeds if the stock row still has enough units) | 40 ms |
| Capacity decrement | 10 ms |
| Retry on reservation conflict (one) | 50 ms |
| Write decision and emit event | 25 ms |
| Headroom | 40 ms |
Retries, fallbacks and scaling
- Retries: a reservation conflict retries with the next option, at most twice; any dependency timeout sends the order to the default option and flags it for review, rather than holding the order. The 200 ms budget above is sized for the common case of at most one retry (its "Retry on reservation conflict" row); a second retry only happens when the first two candidate options are both taken in the same instant, which is rare, and is allowed to run past the p99 target rather than fail the order, since a slightly late routing decision still beats none.
- Idempotency: decisions are keyed by order ID, so a retried request returns the stored decision instead of reserving twice.
- Reservations expire (for example 30 minutes) if the warehouse never confirms the pick, so crashed flows release stock.
- Scaling: the decider is stateless and scales horizontally; inventory is partitioned by warehouse; capacity counters by carrier and warehouse. At about 139 orders/s the hot rows (the database rows many transactions try to update at once, and so the ones most likely to queue behind each other) are the best-selling SKUs at one warehouse, so reservations there use per-SKU row locks (the database blocks other writers from touching that same row while one reservation is mid-update, so two orders cannot claim the same unit of stock) with short transactions.
Success metrics
- On-time rate (target at least 95%) and the gap between predicted and realized on-time probability (calibration).
- Cost per order and split-shipment rate.
- Decision latency at the median and the 99th percentile (p50/p99), fallback rate, reservation conflict rate.
- Override count, age and measured cost impact.
Pitfalls
- Calling carrier APIs synchronously: their latency and outages become yours.
- Optimizing only cost: the cheapest option is often the one that breaks the SLA.
- Rules in code: every rule change becomes a deploy, and nobody can audit which rule fired.
You detect upstream traffic provider latency spikes. Propose a graceful degradation strategy for ETA computation that maintains availability and communicates uncertainty to clients. How does the fallback hierarchy work (historical averages, aggregated driver speeds, coarser tiles), and how do you ensure safe user experience?
Sample Answer
Direct answer
First, stop the provider's slowness from becoming my slowness: put a strict timeout and a circuit breaker (a switch that stops calling a failing dependency for a while) on the traffic call so ETA (estimated time of arrival) requests never wait on it. Then compute each road segment's speed from the best source still fresh, in order: the provider's live speeds, our own drivers' recent speeds, historical averages for that hour of the week, coarser area-level speeds, and finally a city default. Return the ETA as a range whose width grows as we move down the list, with a quality flag, and have clients change what they show and promise accordingly. The goal is that riders and drivers see a slightly vaguer ETA, never a missing one or a confidently wrong one.
Step 1: contain the latency spike
- Latency budget. Say ETA must answer within 300 ms at P99 (the 99th percentile) because dispatch calls it while matching. Give the provider call a fixed slice, for example a 120 ms timeout.
- Do not call the provider per request at all, if you can avoid it. Better architecture: a background job pulls provider speeds into a local speed table every minute. Then a provider spike only makes the table older; it never adds latency to user requests. The rest of this answer assumes that design, with the on-request call as a legacy path protected by the timeout.
- Circuit breaker. If more than half of recent calls time out, stop calling for 30 seconds, then let a few trial calls through before resuming. This prevents piling thousands of waiting requests onto a struggling provider (and onto our own threads).
Step 2: the fallback hierarchy
The key idea is that the choice is per road segment, not global. A spike may leave most of the table fresh but some areas stale.
| Level | Source | Use when | Uncertainty |
|---|---|---|---|
| 1 | Provider live speed | Segment updated within the freshness limit (for example 5 minutes) | narrow |
| 2 | Aggregated speeds from our own drivers on that segment in the last 10 minutes | Provider stale; enough of our vehicles passed recently | narrow to medium, depending on sample count |
| 3 | Historical average for this segment and hour of the week | Too few recent probe samples | medium; blind to today's incidents |
| 4 | Coarser tile speed (average over a map area, for example a few km²) | Segment has no reliable history (new or rarely driven road) | wide |
| 5 | City-wide default speed for the road class | Nothing else available | widest |
Blending instead of switching. Our own driver speeds (level 2) are noisy when few cars passed. These are called probe speeds: each of our vehicles passing a segment acts as a moving "probe" reporting how fast that road is actually flowing, as opposed to a fixed roadside sensor. Rather than a hard cut-over, shrink the probe estimate towards the historical one (pull the raw probe reading part of the way back toward what history says, instead of trusting either source outright), weighting by sample count n with a prior weight k (a tuning number that acts like k imaginary extra historical-only readings added into the blend by default, so history keeps some pull even before any real samples arrive):
v=n+knvprobe+kvhist
With few samples the answer stays close to history; with many it follows today's traffic.
Worked example
A 6 km route while the provider is stale, with k=5:
| Segment | Length | Recent probe samples | Probe speed | Historical speed | Blended speed | Time |
|---|---|---|---|---|---|---|
| A | 2.0 km | 12 | 24 km/h | 30 km/h | (12×24 + 5×30)/17 = 25.76 km/h | 4.66 min |
| B | 1.5 km | 3 | 18 km/h | 30 km/h | (3×18 + 5×30)/8 = 25.50 km/h | 3.53 min |
| C | 2.5 km | 0 | none | 40 km/h | 40.00 km/h (history only) | 3.75 min |
Total: 4.66 + 3.53 + 3.75 = 11.94 minutes, about 12. Segment B shows why blending matters: three cars at 18 km/h might be one delivery van and two drivers stopping for pickups; a raw probe average would have made the segment take 5 minutes and overreacted.
The quality flag for the response is the worst level used on a meaningful share of the route (here level 3, since segment C's 3.75 of the 11.94 total minutes is about 31%). The displayed range should come from that level's measured error, not intuition: while the provider is healthy, continuously compute what levels 2-5 would have said for a sample of trips and record how far off each level's estimate ran versus the actual arrival, as a percentage. Suppose that backtesting shows level-3 estimates typically run 15% low to 20% high versus the actual arrival. Applied to this trip's 11.94 minutes, that is roughly 11.94 x 0.85 ≈ 10 minutes on the low side and 11.94 x 1.20 ≈ 14 minutes on the high side, so the client would show "10-14 min" instead of "12 min", a range derived from measured error rather than a made-up width.
Step 3: communicate uncertainty to clients
Responses carry eta_seconds, eta_low, eta_high and quality. Clients:
- show a range or "about" wording once quality drops,
- stop "arriving in 1 min" notifications, which are the ones that break trust when wrong,
- keep upfront prices locked to the quote the rider accepted; the ETA degradation must not silently change what they pay,
- give drivers pickup windows with buffer rather than a hard minute.
Step 4: safe user experience
- No flip-flopping. Apply hysteresis: once a segment falls back, require the provider to be fresh for a few consecutive refreshes before switching back, and smooth the displayed ETA so it moves at most a minute or so per update.
- Closures still apply. Degrading speeds must not degrade the closure list; a road closed an hour ago stays closed regardless of which speed source is used.
- Matching adapts. When ETAs are wide, dispatch should rank drivers using the lower-uncertainty component (distance along the road network) more heavily, rather than trusting small ETA differences between candidates.
- Operational visibility. Alert on the share of segments at each level per city, not just provider errors; a quiet shift to level 3 across a city is itself an incident.
When the central routing service itself is down: the client-side fallback
If the phone cannot reach our ETA service at all, the client computes a coarse estimate on its own:
- It already has the active route polyline (the ordered list of map coordinates that traces the route's shape) and per-segment times from the last successful response.
- Remaining time = remaining distance along that polyline divided by an exponentially weighted moving average (a running average that favours recent readings) of the vehicle's own recent speed, bounded by the cached segment speeds so a car stopped at a light does not produce a 40-minute ETA.
- The UI shows the last known ETA counting down with an "updating" marker and switches to range wording after a timeout. It never invents a new route; it keeps following the cached one until the service returns.
Trade-offs and pitfalls
- Fail fast vs accuracy. A tighter timeout falls back more often; a looser one lets the spike leak into dispatch latency. Because dispatch is latency-critical and our fallback is reasonable, lean towards failing fast.
- Self-reinforcing probe bias. Our drivers are not a random sample of traffic (they stop for pickups, avoid certain roads). Filter probe points while the vehicle is stopped for a pickup and use speeds only from vehicles moving along the segment.
- Hidden global state. A single "degraded mode" flag for the whole city throws away good data; per-segment selection keeps accuracy where it still exists.
Discuss trade-offs between deterministic heuristics (rule-based) and machine-learned ETA estimators in a latency-sensitive API. Consider accuracy, explainability, maintainability, inference cost, and operational complexity. Propose a hybrid approach and when to use each component.
Sample Answer
Direct answer
For an ETA (estimated time of arrival) API, I would not choose one: I would use the graph-based route time as the base and an ML model that predicts the correction (the residual between what the graph says and what actually happens), clamped to a sane range and with the graph answer as the fallback when the model is slow or unavailable. Rule-based and graph methods are explainable, cheap and predictable but systematically miss things like pickup friction and local driving patterns; a model learns those, but costs inference time, needs a feature pipeline, and fails in less obvious ways. The hybrid keeps the explainable skeleton and uses ML where the rules are known to be wrong.
The two approaches
- Deterministic heuristics: compute a route on the road graph (A* or a precomputed hierarchy), sum edge travel times from live and historical speeds, then add hand-written rules ("add 90 s for airport pickups", "multiply by 1.1 in heavy rain").
- Machine-learned estimator: a model (gradient-boosted trees, an ensemble of small decision trees where each new tree corrects the previous ones' errors, or a neural network) takes features (route distance, graph time, time of day, area, weather, recent observed speeds, pickup location type) and predicts the ETA or the error of the graph ETA. Trained on completed trips.
Trade-offs on the named criteria
| Criterion | Heuristic / graph | ML estimator | Hybrid (graph + ML residual) |
|---|---|---|---|
| Accuracy | Good on the driving part; misses systematic effects the rules do not name | Learns systematic bias per area, hour, pickup type; can be poor on situations rare in training data | Graph handles geometry and live traffic; model fixes bias |
| Explainability | Every minute traces to a road segment or a rule | Needs feature attribution tools (methods such as SHAP that estimate how much each input feature pushed one specific prediction up or down); hard to explain one prediction to a support agent | "Route time 14 min, plus 2 min typical pickup delay at this venue" |
| Maintainability | Rules accumulate and interact; nobody dares delete one | Retraining pipeline, feature store (a shared service that computes and serves the model's input features consistently to both training and live requests), drift monitoring (watching whether live inputs or predictions are sliding away from what the model was trained on) | Fewer rules; one model with a clear, bounded job |
| Inference cost | Graph search already paid for | Feature fetch plus model evaluation per request, multiplied by fan-out (dispatch scores many candidates) | Same as ML, but can be skipped under load |
| Operational complexity | Low: one code path, deterministic | High: model versions, feature freshness, training/serving skew (the features computed offline for training not exactly matching what gets computed live, so the model sees different inputs than it learned from) | Medium: fallback path must be tested regularly |
Why the residual framing
Predicting the residual rather than the full ETA keeps the model's job small and bounded. The route geometry and live traffic are already in the graph time, so the model only learns what the graph systematically gets wrong. This has three practical benefits: the model can be smaller (cheaper to run inside the latency budget), its output can be clamped (for example, never adjust by more than 30% of graph time), and when the model fails, dropping back to the graph time loses only the correction, not the whole answer.
Where each piece runs in a latency-sensitive API
- Graph time: always computed; it is the answer of last resort.
- Features: fetched in one batched read from an online key-value feature store with a short timeout.
- Model: evaluated with a hard deadline (say 15 ms). On timeout, return graph time plus a static per-area bias table (a rule, refreshed daily from the same training data).
- Guardrails: clamp the correction; reject if features are older than their freshness limit.
Use the pure heuristic path for: cold-start cities (new markets with little or no historical trip data yet to train or calibrate on), dispatch fan-out when the system is under load, and any context requiring an explanation traceable to the map (disputes). Use the ML correction for: rider-facing ETAs and pricing inputs where accuracy is worth the cost.
Worked example
A pickup at a stadium on match night:
- Graph time from driver to pickup: 14.0 min.
- Rule-based adjustment: none exists for this venue.
- The residual model, having seen that pickups at this venue on event nights run long (crowds, closed curb lanes), predicts +3.5 min.
- Clamp at 30% of 14.0 = 4.2 min: +3.5 is within range, so the ETA is 17.5 min.
- If the model misses its 15 ms deadline, the fallback is graph time plus this area's static evening bias (say +1.0 min): 15.0 min, less accurate but never absurd.
For inference cost, note the fan-out: suppose a metro's dispatch peaks at around 800,000 ride requests in its busiest hour, that is 800,000 / 3,600 ≈ 222 requests per second (an illustrative peak for this calculation, not a measured figure); if dispatch scores 20 candidate drivers per request at that rate, that is 20 x 222 = 4,440 model evaluations per second before rider-facing ETAs are counted. Batch the 20 candidates into one model call, so the per-call overhead (network hop, serialization, feature fetch) is paid once rather than 20 times.
Pitfalls
- Training on ETAs you displayed rather than on actual trip outcomes teaches the model to agree with itself.
- Letting rules and model both correct the same effect (a rain rule and a rain feature) double-counts it.
- No holdout of the heuristic path: a holdout here means deliberately keeping a small slice of live traffic on the older path on purpose, to prove it still works; skip that and, if the fallback is never exercised, it rots and fails the day it is needed. Serve a small percentage of traffic on it continuously.
- Unbounded model output lets a bad feature (a stale traffic value of zero) produce a 3-hour ETA for a 10-minute trip.
Build a high-level design for a priced-transaction audit pipeline that consumes events from the pricing API, enriches them with order and inventory data, and stores them for compliance queries and forensic analysis. Specify event schema, enrichment flow, storage tiering (hot/warm/cold), and query patterns.
Sample Answer
Direct answer
I would build it as an append-only event log with one enrichment stage and three storage tiers. The pricing API emits one immutable price_decision event per quote to a durable log; a stream processor (a service that consumes events continuously, one at a time as they arrive, instead of running on a schedule) joins each event with the order and inventory state it refers to and writes an enriched record; the enriched records land in a hot columnar store (columnar: storing each field in its own column on disk, which compresses repetitive data well and makes scanning one field at a time fast) for recent interactive queries (30 days), a warm open-format table (a table stored as plain files in a documented, open format, so any query engine can read it rather than only one vendor's) on object storage for everything within 13 months, and a cold write-once archive for the multi-year retention period. The two properties that matter more than any tool choice: records are never updated in place (corrections are new records), and the raw event is kept alongside the enriched one, so enrichment bugs can be fixed by replaying.
Requirements I am designing to
- Compliance queries: "every price shown to customer X in March and what they paid", "prove the price for order Y was produced by an approved model version". Must be answerable for years.
- Forensic analysis: "which quotes did pricing version v42 produce between 14:00 and 16:00 on 3 September, by region, and how many converted?" Large scans, rare, must not affect production.
- Integrity: an auditor must be able to trust that records were not altered after the fact.
Volume, with assumptions: 40M pricing decisions per day, about 1.2 KB per enriched record as JSON.
| Quantity | Arithmetic | Result |
|---|---|---|
| Event rate | 40,000,000 / 86,400 | about 463 per second average; assume 3x at peak, about 1,390 per second |
| Raw enriched volume | 40M × 1.2 KB | 48 GB per day |
| Hot tier, 30 days, assuming 5x compression in a columnar store | 48 / 5 × 30 | about 288 GB |
| Warm tier, 13 months, assuming 8x compression in Parquet (a column-oriented file format built for compression and fast scanning) | 48 / 8 × 395 | about 2.4 TB |
| Cold tier, 7 years, same 8x | 48 / 8 × 365 × 7 | about 15.3 TB |
The compression ratios are assumptions (repetitive JSON commonly compresses well in columnar formats); measure on real data before sizing. The conclusion does not depend on them: throughput is modest, so the design problem is retention, integrity and query shape, not ingest scale.
Architecture
flowchart LR
API[Pricing API] --> Log[Durable event log]
Orders[Order DB change stream] --> Log
Inv[Inventory change stream] --> Log
Log --> Enrich[Stream enrichment job]
Enrich --> Hot[Hot: columnar OLAP, 30 days]
Enrich --> Warm[Warm: Parquet table on object storage, 13 months]
Log --> RawArch[Raw events archive]
Warm --> Cold[Cold: write-once archive, 7 years]
Hot --> Q[Compliance and forensic queries]
Warm --> Q
Event schema
The pricing event is written by the pricing API at decision time and never changes:
| Field | Example | Why |
|---|---|---|
event_id | pd_01J9ZM... (unique, time-sortable) | Deduplication on replay |
schema_version | 3 | Lets the schema evolve without breaking old readers |
quote_id | q_77 | Join key to orders |
decided_at | 2026-09-03T14:02:11.412Z | Event time, set by the producer |
customer_ref | tok_c58812 (tokenized: a random reference standing in for the real customer ID, with the mapping to their identity kept in a separate service) | Customer lookups without storing raw identity |
item_id, item_params | listing:L-812, {nights: 2} | What was priced |
region, geo_cell | eu-west, cell_8a1f... | Forensic slicing |
price_components | {base: 40000, surge_mult: 1.2, fees: 4320, tax: 3456} minor units (40000 × 1.2 = 48000, plus fees and tax = 55776) | Reconstructs the total |
total_minor, currency | 55776, USD | The number disputed |
pricing_version | surge-v42 | Which model or rule set decided |
inputs_digest | SHA-256 hash of the feature vector (the list of numeric inputs the pricing model used to decide) | Proves which inputs were used without storing them all |
prev_hash | hash of the previous record in this partition | Tamper evidence (see integrity) |
The enrichment stage adds, never overwrites:
| Added field | Source |
|---|---|
order_id, order_status, booked_total_minor, captured_minor | Order change stream, joined on quote_id |
inventory_state_at_decision (available units, hold IDs) | Inventory change stream, as of decided_at |
enrichment_status | complete, no_order_yet, late_order, inventory_missing |
enriched_at, enricher_version | For replays and bug tracing |
Enrichment flow
- Ingest: the pricing API writes to the log synchronously before responding with the quote (or writes to an outbox table, a table updated in the same database transaction as the quote record and later relayed to the log, so a crash between commit and publish cannot silently drop the event). An audit pipeline that can silently drop events is not an audit pipeline, so this write is on the critical path and the log is replicated.
- Join with order state: most quotes never become orders. The job keeps each quote in keyed state (an in-memory record per
quote_idthat the stream processor updates as related events arrive) for a window (say 24 hours, matching quote validity plus slack). If an order event for thatquote_idarrives, it emits an enriched record withcomplete; when the window closes with no order, it emitsno_order_yet. An order arriving after the window produces a separatelate_orderrecord rather than rewriting the earlier one. - Join with inventory state as of decision time: this is a temporal join (look up the inventory row version valid at
decided_at, not the current one), which is why inventory is consumed as a change stream and kept as versioned state rather than queried live. Querying the live inventory database would give today's state, which is forensically wrong, and would put audit load on a production database. - Exactly-once effect by deduplication: the stream job may reprocess events after a restart (at-least-once delivery, meaning an event can be delivered more than once but never lost). Writes are keyed by
event_idso a duplicate overwrites itself or is dropped, giving the same end result as processing once. - Replay: because the raw log is archived, a bug in the enricher is fixed by deploying a new
enricher_versionand replaying a time range into a new partition, then switching readers. Old records stay for comparison.
Storage tiering
The specific products named in this table are interchangeable examples of each category, not requirements: ClickHouse and Druid are both columnar OLAP engines, Iceberg and Delta Lake are both open table formats, Trino and Athena are both SQL engines that query files in object storage, and Object Lock is one vendor's name for a write-once retention lock. Use whichever your organization already operates.
| Tier | Store | Holds | Serves | Why this store |
|---|---|---|---|---|
| Hot | Columnar OLAP database (ClickHouse, Druid, or a cloud warehouse; OLAP means online analytical processing) | 30 days, all fields | Interactive queries by customer, order, region, version in seconds | Fast aggregation and filtering on recent data |
| Warm | Parquet files in an open table format (Apache Iceberg or Delta Lake: a metadata layer on top of the Parquet files that adds transactions, schema changes over time, and point-in-time reads, on plain object storage) on object storage, queried in place by a SQL engine such as Trino or Amazon Athena (both run SQL directly over files in object storage) | 13 months | Compliance lookups and forensic scans in tens of seconds | Cheap per GB, partition pruning (skipping whole files that can't match the query's filters instead of scanning everything), no always-on cluster |
| Cold | Object storage archive class with write-once retention locks (for example Object Lock in compliance mode on Amazon S3, AWS's object storage service) | 7 years | Restores for audits and legal holds, hours to retrieve | Lowest cost, and the lock makes deletion or overwrite impossible before the retention date |
Warm partitions: by decision_date then region, with files sorted by customer_ref and quote_id so point lookups read few files. Records move tiers by age with an automated job; there is no manual copy.
Query patterns and how each is served
| Query | Example | Tier and access path |
|---|---|---|
| Point lookup by order or quote | "Show the audit trail for order Y" | Hot if recent, else warm, pruned by date and sorted quote_id |
| Customer history | "All prices shown to customer X in March" | Warm, pruned to March, filtered on tokenized customer_ref |
| Version forensics | "All v42 decisions 14:00 to 16:00 on 3 Sept, by region, with conversion rate" | Hot or warm scan pruned by date, aggregated by region |
| Reconstruction | "Recompute the price from components and confirm it equals total_minor" | Any tier: the components are in the record |
| Legal hold | "Freeze all records for customer X" | Place a legal hold on the relevant cold objects and a hold flag in the catalogue (the table format's own index of which files make up which table, e.g. Iceberg's or Delta Lake's metadata layer) |
Integrity and privacy
- Tamper evidence: each record carries
prev_hash, the hash of the previous record in its partition, forming a hash chain. Daily, the job publishes the head hash of each partition to a separate write-once location. Altering any past record changes every later hash and no longer matches the published head. - Personal data: store a token for the customer, with the token-to-identity mapping in a separate service. A deletion request under privacy law then deletes the mapping (the audit records become unlinkable) while the financial record is retained under its own legal basis. Confirm that approach with legal counsel for your jurisdictions rather than assuming it.
- Access: the audit store is read-only for everyone except the pipeline's own identity, and every query against it is itself logged.
Trade-offs and pitfalls
- Enriching by calling production services per event (order API, inventory API) couples audit throughput to production health and returns current, not historical, state. Consume change streams instead.
- Updating records when an order arrives late breaks the append-only guarantee auditors rely on. Emit a new record.
- One tier for everything either costs too much (seven years in a hot OLAP cluster) or answers too slowly (interactive investigations against cold archive).
- What would change the design: if regulators required real-time surveillance (flagging discriminatory pricing within minutes), I would add a streaming rule engine on the enriched stream, rather than relying on batch queries over the warm tier.
Provide a migration plan for a customer currently using a batch-based nightly pricing recalculation to move to a near-real-time dynamic pricing service with <1 minute freshness. Include data migration steps, dual-running strategy, consistency checks, and rollback criteria.
Sample Answer
Direct answer
I would migrate in five phases and never switch everything at once: define what "correct" and "fresh" mean and measure the batch system against it; build the streaming pipeline and backfill its state from the batch output; dual-run with batch still serving while the new service computes prices in shadow (running in parallel and writing its own output, but nothing reads or acts on that output yet); canary the new prices market by market (release to a small slice of markets first, watch the guardrail metrics, then expand only if they hold); then cut over while keeping the nightly batch running as a fallback for a few weeks. The key idea for consistency checks is to separate two questions: does the new code compute the same price from the same inputs (logic parity, which must match almost exactly) and how much do prices differ because the new system sees fresher data (freshness divergence, which is expected and should be explainable). Rollback is a feature flag per market (a per-market on/off switch that can be flipped instantly, without a code deploy) that points the read path back at the batch table, decided by pre-agreed numeric criteria rather than a debate during an incident.
The starting point and the target
Assume a booking marketplace (holiday rentals): 40,000 listings, each priced for the next 180 nights, so 40,000 × 180 = 7.2 million price points. Today a nightly job reads the day's bookings, searches and competitor rates, recomputes every price point and overwrites a nightly_price table the website reads.
Target: when demand changes (a booking, a burst of searches, a competitor rate update), affected prices update within 1 minute, measured from the triggering event to the price being readable.
Load, from assumed volumes: 30,000 bookings/day is 30,000 / 86,400 ≈ 0.35 bookings/s. If each booking changes the occupancy of its market for that night and triggers repricing of about 2,000 listings in the same market and night (illustrative: with 40,000 listings spread over roughly 20 markets, that is about 40,000 / 20 = 2,000 listings sharing each market, and a demand-based price for one listing is set by comparing it against every other listing in its own market for that night, so one booking's occupancy change can move all of them), that is 0.35 × 2,000 ≈ 700 price recomputes/s on average. Searches at 2 million/day are about 23/s and feed demand counters. Both are modest for a stream processor (software that consumes an unbounded, continuously arriving event feed and updates its results incrementally, instead of running once over a finished batch of data); the design risk is correctness, not throughput.
Target architecture
flowchart LR
DB[Bookings DB] --> CDC[Change-data-capture]
CDC --> BUS[Event stream]
SR[Search events] --> BUS
CR[Competitor feed] --> BUS
BUS --> SP[Streaming pricer]
SP --> ST[Keyed state per market-night]
SP --> PT[price_current table]
PT --> API[Pricing read API]
NB[Nightly batch] --> NPT[nightly_price table]
NPT --> API
Change-data-capture (CDC) means reading the database's own change log so every booking insert becomes an event without changing the booking application. The streaming pricer keeps per-market-night state (occupancy, search counts in rolling windows, a moving lookback range that always covers, say, the most recent 7 days and slides forward as time passes) and writes to a new price_current table with one row per listing-night, carrying computed_at, input_watermark (the time of the newest event included) and pricer_version. The read API chooses between the two tables per market using a flag.
Phase 0: Define correctness and freshness first (1 week)
- Freshness SLI (service-level indicator, the measured quantity a target is set on): per price update,
computed_atminus the triggering event's time. Target: p99 (99th percentile) under 60 s. - Parity metric: share of price points where the new and old price differ by more than max(1%, 1 USD).
- Business guardrails: conversion (bookings per search), revenue per available night, and cancellation rate, measured per market.
- Refactor the pricing formula into one shared library used by both the batch job and the streaming pricer. If the two systems use two implementations, parity failures will be real disagreements about the formula, and you will spend weeks deciding which one is right.
Phase 1: Build and backfill (2 to 4 weeks)
- Stand up CDC on the bookings database and publish booking, search and competitor events to the stream.
- Data migration: create
price_currentwith the new schema. Seed it from the latestnightly_pricerun (7.2 million rows, loaded in batches of 10,000 as a bulk copy), tagging each rowsource = batch_seed. - Backfill state: replay the last 14 days of events into the streaming pricer from the stream's retention (how far back the stream keeps old events before discarding them; most streaming platforms default to a few days) (or from the warehouse if retention is shorter) so rolling windows such as "searches in the last 7 days" are full on day one. A pricer that starts with empty windows will under-price everything.
- Record the stream offset (every event on the stream has a position number; the offset marks exactly which position replay reached) where replay ended and switch the pricer to live consumption from exactly there. This is what prevents both failure modes: resuming from the recorded offset, not from "now", means no event between the backfill and the switch is skipped (a gap), and not from the start again means no event already applied during backfill is replayed a second time (a double count).
Phase 2: Dual-run in shadow (2 weeks minimum)
Batch keeps serving; the streaming pricer writes price_current, which nobody reads yet. Two consistency checks run every night:
Check A, logic parity. Take the batch job's exact input snapshot for the night, feed it through the streaming pricer's code in replay mode, and compare output with nightly_price. Same inputs must give the same prices. Pass: fewer than 0.01% of the 7.2 million points (under 720) differ beyond tolerance, and every difference has a known cause (typically rounding or event ordering).
Check B, freshness divergence. Compare live price_current with nightly_price at the moment the batch finishes. Differences are expected, because streaming has seen the day's events as they happened. The check is that the differences are explainable: for a sample of 500 differing points, the new price must be reproducible from the events logged since the batch input cut-off. Unexplained differences are bugs.
Also measure: the freshness SLI, the stream consumer lag (how far the pricer is behind the newest event), and dropped or late events (events arriving after their window closed).
Phase 3: Canary (2 to 3 weeks)
Flip the read flag for one small market, then 5% of markets, then 25%, holding each step for at least 7 days so a full weekly booking cycle is observed. Compare guardrail metrics with markets still on batch, matched on season and size.
Phase 4: Cutover and decommission
Flip the remaining markets. Keep the nightly batch running and writing nightly_price for 30 days so rollback stays one flag away and the fallback is never more than a day stale. Then stop the batch, keeping its code runnable for another quarter.
Rollback criteria
Decided before canary starts, evaluated automatically, per market:
| Signal | Threshold | Action |
|---|---|---|
| Freshness p99 | Above 60 s for 15 consecutive minutes | Alert; above 10 min, roll back the market |
| Stream consumer lag | Above 5 min | Roll back all streaming markets (prices are stale) |
| Logic-parity check | Above 0.01% of points, or any unexplained difference | Halt rollout until explained |
| Price sanity | Any price outside the listing's min/max bounds, or a market's median moving over 15% within an hour without a matching demand event | Roll back that market |
| Conversion | Down more than 5% against matched control markets over 3 days | Roll back that market and investigate |
| Pricer error rate | Over 0.1% of recomputes failing | Roll back that market |
Rollback path: set the market's flag back to batch. The read API immediately serves nightly_price, which the still-running batch refreshed last night. No data migration is needed to roll back, which is the whole reason for keeping the batch alive.
Trade-offs and pitfalls
- Freshness is not free: a price that changes every minute can change while a guest is on the checkout page. Honour the price shown at checkout for a short hold window (for example 15 minutes), or near-real-time pricing will generate complaints the batch never did.
- Out-of-order and duplicate events: CDC and streams deliver at least once (an event can arrive twice) and not always in order. Make the pricer idempotent per event ID (processing the same event twice has the same effect as processing it once) and use event time (when the booking or search actually happened), not arrival time (when the event reached the pricer, which lags behind and varies), for windows.
- The last write must win correctly: if the batch seed and a live update race on the same row during Phase 1, the row with the newer
input_watermarkmust win. A plain overwrite would let the seed clobber a fresher live price. - What would change the plan: if the business needs freshness in seconds, not a minute, the read path should push updates into a cache instead of reading a table; for 1 minute, a table read is fine and much simpler.
Unlock Full Question Bank
Get access to all Marketplace, Dispatch, and Logistics System Design interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.