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.
You need to combine multiple traffic data providers with differing latencies, costs, and historical accuracies to produce a single ETA. Describe an algorithm to weight and fuse these sources in real time, including handling missing or conflicting data and scoring provider reliability over time.
Sample Answer
Direct answer
Fuse at the level of road segments (or corridors), not whole-trip ETAs (estimated times of arrival), and treat every provider as a noisy sensor with a learned bias (does it run systematically fast or slow?) and a learned error variance (how wrong is it typically?). Combine the bias-corrected estimates with inverse-variance weighting, where a source's weight is 1 divided by its expected squared error (statisticians call this the variance: the average of the squared gap between what a source reports and the truth, so a source that is occasionally very wrong scores worse than one that is mildly wrong just as often), and inflate a source's variance by how old its data is, so stale data automatically counts for less. Score reliability continuously against ground truth from our own fleet: the travel times our drivers actually take on those segments a few minutes later. Missing sources simply drop out of the weighted sum; conflicting sources are checked against the consensus of the others and excluded when they disagree far beyond their own stated error.
Why segments, and why inverse-variance
Providers differ in coverage (one is strong on highways, another on downtown streets), latency (seconds to minutes) and price. Fusing per segment lets each provider win where it is actually good. Inverse-variance weighting is the natural rule because, for independent unbiased estimates, it produces the combined estimate with the smallest possible variance, and it gives a fused uncertainty for free, which the ETA service can turn into a confidence range.
For segment travel time, provider i reports an estimate e_i. With learned bias b_i, learned error variance σ_i², and data age a_i seconds:
σi,eff2=σi2+(κai)2 wi=σi,eff21,t^=∑iwi∑iwi(ei−bi),σt^=∑iwi1κ (seconds of error added per second of data age) is itself learned: fit how fast a provider's error grows with the age of its reading. Our own fleet's live probe data (map-matched traversal times, meaning each driver's raw GPS trace has already been snapped onto the road segment it most likely followed, from drivers on the road right now) enters the same formula as one more source, usually the best one on busy segments and absent on quiet ones.
Worked example
One downtown segment, κ = 0.1 s per second of age:
| Provider | Reported (s) | Age | Learned σ | Learned bias | Corrected (s) | Effective σ (s) | Weight share |
|---|---|---|---|---|---|---|---|
| A | 120 | 30 s | 15 s | 0 | 120 | √(225 + 9) = 15.3 | 76.9% |
| B | 150 | 5 min | 25 s | +10 s (runs slow) | 140 | √(625 + 900) = 39.1 | 11.8% |
| C | 100 | 10 s | 40 s | 0 | 100 | √(1600 + 1) = 40.0 | 11.2% |
Fused estimate: 120.1 s, fused σ = 13.4 s. Note that the fused σ is smaller than the best single source (15.3 s): B and C add information even though each alone is poor. B's five-minute-old reading contributes little because age inflated its variance from 625 to 1,525.
Missing data. If provider A times out, fuse B and C alone: 120.5 s with σ = 27.9 s. The estimate barely moves but the uncertainty doubles, and that uncertainty should flow through: the rider sees a wider ETA range, and dispatch adds margin. When every provider is missing, fall back to the historical profile for that segment, time of day and day of week, with its historical variance.
Conflicting data. For each source, compute how far it sits from the fused value of the other sources, in units of its own effective σ: this ratio, the gap divided by σ, is the source's z-score. In this example, all three are within about half a σ, so nothing is excluded. If provider C had instead reported 280 s (implausibly slow, for example a feed bug replaying a stale road-closure or detour reading), compare it against the fused value of A and B alone: their weights are 1/15.3² ≈ 0.00427 and 1/39.1² ≈ 0.00065, giving a fused estimate of (0.00427×120 + 0.00065×140) / (0.00427+0.00065) ≈ 122.7 s. C's z-score, using its own effective σ of 40.0 s, is (280 − 122.7) / 40.0 ≈ 3.9: past the 3-sigma cutoff, so it is excluded for this cycle. A milder miss does not necessarily clear that bar: if C had reported 20 s instead, the same calculation gives (122.7 − 20) / 40.0 ≈ 2.6, below 3, so it would not be excluded by this rule alone. That is a real limitation worth stating plainly: a provider with a wide effective σ, from a history of being consistently unreliable, is hard to catch on any single bad reading, because the exclusion rule is scaled by exactly the noisiness that makes it unreliable in the first place. Repeated exclusions trip a per-provider circuit breaker (after enough consecutive exclusions, stop calling that feed and fall back to the others for a cooldown period) so a broken feed stops being called even when no single reading clears the 3-sigma bar.
Scoring reliability over time
Ground truth arrives later: once our drivers traverse the segment, the map-matched traversal time is the truth for that time window. For each provider, per road class and time-of-day bucket, update exponentially weighted moving averages (EWMA: a running average where each new observation gets a fixed share α and older ones decay):
- Bias: b ← (1 − α) b + α r, where r is the provider's error on that observation.
- Variance: σ² ← (1 − α) σ² + α r².
Example with α = 0.05: provider A starts with σ = 15 s and bias 0. A single 40 s miss raises its variance from 225 to 0.95 × 225 + 0.05 × 1,600 = 293.75, so σ rises from 15.0 s to 17.1 s. Separately, one observation where A said 130 s and truth was 100 s (a 30 s overestimate) moves its bias from 0 to 0.05 × 30 = 1.5 s. With α = 0.05 an observation's influence halves after about 13.5 further observations, so a provider that degrades is down-weighted within a busy hour, while one bad reading cannot wreck its score.
Guard the scoring loop:
- Only score where truth is solid: segments with enough of our own traversals in the window; otherwise skip rather than learn from noise.
- Exclude our own probe data from the truth it is scored against, or the fleet source always looks perfect.
- Keep per-bucket scores: a provider good on highways at night can be poor downtown at rush hour.
Cost and latency
Providers differ in price per request, so do not poll every provider for every segment. Poll the cheap or streaming sources broadly; call an expensive source only for segments on active routes (segments that some in-flight trip or pending dispatch will traverse in the next 15 minutes) where the fused σ is above the target. That is an example of a value-of-information rule: pay only when the extra source would materially shrink the uncertainty that users actually see, since the added accuracy is worth its cost only in that case.
For latency, fusion must never wait for the slowest provider: use each provider's last good reading, with its age reflected through κ, and update asynchronously as new data lands. The ETA request path reads the already-fused segment table.
Trade-offs and pitfalls
- Averaging without bias correction: a provider that is consistently 10% slow drags every estimate; bias correction fixes that, weighting alone does not.
- Assuming independence: two providers that license the same upstream feed have correlated errors; inverse-variance weighting then double-counts them. Detect it from the correlation of their residuals and merge them into one source.
- Ground truth selection bias: our drivers avoid segments we believe are jammed, so jammed segments get fewer truth samples. Weight the scoring or supplement with provider-independent sources.
- Recommendation: inverse-variance fusion with EWMA-learned bias and variance is simple, explainable and debuggable. Move to a learned model (gradient-boosted trees: an ensemble of many small decision trees, each trained to correct the errors the previous trees left behind, over provider readings, ages and context) only when you have enough truth data to beat it on held-out traffic (real segments and time windows kept aside from training, used only to check whether the model generalizes rather than having memorised the training data), and keep the simple fusion as the fallback.
Drivers are moving objects sending location updates. How would you decide the location update frequency, and what client- and server-side strategies can you use to reduce update volume while preserving matching quality? Explain trade-offs between freshness, battery/network use, and compute load.
Sample Answer
Direct answer
Derive the update rate from how much position error matching can tolerate, not from habit. A car at 10 m/s (36 km/h) moves 40 m between 4 s updates; if dispatch compares drivers who are typically 1 to 3 km from the rider, 40 m of staleness barely changes the ranking, while 300 m (30 s updates) sometimes picks the wrong driver. So the rate should follow the driver's state and speed: frequent when a rider is watching or a pickup is close, sparse when idle or parked. On the phone, send on movement rather than on a timer and batch fixes into fewer uploads; on the server, estimate between updates (dead reckoning) and only touch the geo index when a driver changes cell: the service area is divided into a grid of cells, and the geo index is the lookup that maps each cell to the drivers currently inside it, so a ping that stays inside the same cell needs no index update.
Deciding the frequency
Work backwards from the error budget:
| Update interval | Distance moved at 10 m/s | Pings per hour | Suits |
|---|---|---|---|
| 1 s | 10 m | 3,600 | Final 200 m of a pickup, live navigation |
| 4 s | 40 m | 900 | En route to pickup, rider watching the car |
| 10 s | 100 m | 360 | On trip (rider is inside the car) |
| 30 s | 300 m | 120 | Idle and waiting for a request |
Two tests confirm the choice: replay historical dispatch decisions with positions artificially aged by the candidate interval and measure how often the chosen driver changes (matching quality); and measure the ETA (estimated time of arrival) error at pickup (did the driver arrive when promised). Pick the sparsest interval where both stay within tolerance for each state.
Client-side strategies
- State-driven rate: idle, en route to pickup, on trip and offline each get their own interval (as in the table). The server tells the app which state it is in, so the rate changes instantly when a dispatch offer is accepted.
- Movement triggers instead of a pure timer: send when the driver has moved more than a distance threshold (say 50 m), when the heading has changed by more than 30 degrees (a turn), or when a maximum silence (say 15 s) has passed, whichever comes first. A parked driver then sends almost nothing, and a driver taking a turn is reported promptly.
- Batching: record fixes frequently but upload them together, for example a fix every 2 s uploaded in one message every 10 s. The expensive part on a phone is waking the cellular radio, not taking a GPS fix, so batching cuts battery and data far more than it cuts accuracy, and it gives the server a dense trail for map-matching (snapping points to roads).
- Use the OS location modes: lower-accuracy or "significant change" modes when idle; high accuracy only when en route or near pickup.
- Compact payloads: small binary encoding and deltas from the previous fix keep each upload tiny.
Server-side strategies
- Dead reckoning: estimate the current position from the last fix plus speed and heading (optionally snapped to the road), so the server can answer "where is the driver now" between sparse updates. Keep an uncertainty radius that grows with time since the last fix, and prefer drivers with fresh fixes when the ranking is close.
- Index only on cell change: overwrite the latest position in memory on every ping, but update the spatial index (cell to drivers) only when the driver crosses into a new cell.
- Drop and coalesce: discard duplicate or out-of-order pings by sequence number, and if processing falls behind, keep only each driver's newest ping.
- Request a fresh fix on demand: when a driver becomes a top candidate for a dispatch and their fix is stale, push a "send location now" message instead of raising everyone's rate.
Worked example
A city with 100,000 online drivers:
- Fixed 4 s for everyone: 100,000 / 4 = 25,000 updates per second.
- State-driven, using the table's own intervals: 45% idle at 30 s, 20% en route at 4 s, 35% on trip at 10 s:
45,000 / 30 + 20,000 / 4 + 35,000 / 10 = 1,500 + 5,000 + 3,500 = 10,000 updates per second.
That is a 60% cut in server load, and it lands on the drivers who matter least for matching quality (idle ones already far from any active decision; on-trip ones whose position the rider sees from inside the car). Drivers en route keep the 4 s rate because both the rider's map and the pickup ETA depend on them.
Trade-offs
| Force | More frequent | Less frequent |
|---|---|---|
| Freshness and matching quality | Better, especially near pickup | Wrong-driver choices, ETA surprises |
| Phone battery and data | Worse: radio wake-ups dominate | Better |
| Server compute and storage | Linear increase in ingest, index work, storage | Lower |
| Map smoothness for the rider | Smoother | Needs client-side interpolation |
Recommendation: state-driven intervals, movement-triggered sends with a maximum silence, batching, and on-demand refresh for dispatch candidates. It captures most of the savings while protecting the two moments users notice: choosing the driver and watching them arrive.
Pitfalls
- Setting one global rate: it is either too expensive for idle drivers or too stale for pickups.
- Treating a missing update as "not moving" rather than "unknown": the uncertainty must grow with silence.
- Throttling so hard that the OS or the app loses the connection in the background, which looks like the driver went offline.
How would you shard and replicate data for a high-scale marketplace where listings, bookings, and availability checks have very different access patterns? Explain your partition key choices, how you would avoid hotspots on popular listings or destinations, and how you would handle resharding or replica lag.
Sample Answer
Direct answer
I would not pick one partition key for the whole marketplace. Bookings and availability share a key, listing_id, so that "is this listing free for these nights, and if so book it" is a single-shard transaction. Listings are read-mostly, so their source-of-truth rows are also sharded by listing_id, but almost all listing reads are served from a separate search index and caches, not from the shards. Guest-side views ("my trips") use a second copy of bookings keyed by guest_id, built asynchronously. Hotspots are treated by what is hot: popular listings are a read hotspot (solved with caching and replicas), a sold-out hotel room type is a write-contention hotspot (solved by splitting the counter into unit rows), and a hot destination is a search hotspot (solved by not partitioning the search index by destination).
First, what each data set actually does
Some vocabulary. Sharding (partitioning) means splitting one logical table across many database servers, each holding a subset of rows chosen by a partition key. Replication means keeping copies of a shard on other servers; a replica that receives changes asynchronously can be behind the primary, and that delay is replica lag. A hotspot is one shard (or one row) receiving far more traffic than the others.
Worked sizing, with assumptions stated (a mid-size lodging marketplace):
| Quantity | Assumption | Arithmetic | Result |
|---|---|---|---|
| Listings | 7M active | 7,000,000 | |
| Availability, one row per listing per night | 1 year horizon, about 24 bytes per row | 7M × 365 × 24 B | 2.56B rows, about 61 GB |
| Availability as a bitmap (1 bit per night) | 365 bits is 46 bytes | 7M × 46 B | about 322 MB |
| Bookings | 2M per day, peak 5x average | 2,000,000 / 86,400 × 5 | about 23/s average, about 116/s peak |
| Searches | assumed 20,000 per second at peak | 20,000 QPS (queries per second) |
The numbers say something important before any design: booking writes are tiny (about 116 per second at peak); reads and search are the load. A design that optimises write sharding and ignores the read path solves the wrong problem.
| Data | Dominant access pattern | Consistency need | Partition key | Where reads are served |
|---|---|---|---|---|
| Listings (title, photos, price rules, location) | Read by id; read in bulk by search | Stale by seconds is fine | listing_id (hash) | CDN (content delivery network) for photos, cache for detail pages, search index for discovery |
| Availability (per listing, per night) | Filtered by search across many listings; checked and changed by booking for one listing | Search may be stale; the booking check must be exact | listing_id (same shard as bookings) | Search index holds a stale bitmap copy; booking reads the primary |
| Bookings | Written by the booking flow for one listing; read by host (by listing) and guest (by guest) | Strong for the write, read-your-writes for the guest who just booked | listing_id primary; guest_id secondary copy | Primary for the booking; guest view from the guest_id copy |
The design I would commit to
flowchart LR
Guest[Guest app] --> Search[Search index: sharded by listing hash]
Guest --> BookAPI[Booking API]
BookAPI --> Router[Shard router: listing_id to logical shard]
Router --> Shard[Shard primary: availability plus bookings]
Shard --> Rep[Read replicas]
Shard --> CDC[Change stream]
CDC --> Search
CDC --> GuestView[Bookings by guest_id]
Guest --> Cache[Listing cache and CDN]
- Hash
listing_idinto 4,096 logical shards, and map logical shards to physical database servers in a small lookup table. (A logical shard is a fixed slice of the hashed key space, always 4,096 of them; a physical server is an actual database machine, and how many logical shards live on a given server can change over time without changing anyone's hash.) Hashing spreads listings evenly regardless of city, so a city being popular does not concentrate rows on one server. - Availability and bookings for a listing live on the same logical shard. Booking is then one local transaction: lock the listing's calendar rows for the requested nights, verify they are free, insert the booking, mark the nights taken, commit. No cross-shard two-phase commit (a protocol that coordinates a commit across several databases and blocks if the coordinator fails) is ever needed on the hot path.
- The guest view is a derived copy. A change-data-capture stream (CDC: reading the database's committed change log and publishing each change as an event) writes each booking into a
bookings_by_guesttable sharded byguest_id. It is eventually consistent, typically behind by well under a second, which is fine for a list of trips as long as the confirmation page does not depend on it (see replica lag below). - Search never scans the shards. The search index holds, per listing, its attributes, geo point and an availability bitmap updated from the same CDC stream. It answers "listings in Lisbon, 2 guests, free 2 to 4 October" by bitmap AND-ing across candidates: each listing's per-night availability is one bit per day (1 means free), so checking "free 2 to 4 October" builds a 2-bit mask for the nights of 2 and 3 October, both required free, written
11. A listing with bits11at those two positions ANDs to11, matches the mask, and passes through; a listing with bits10(free the 2nd, already booked the 3rd) ANDs to10, does not match11, and is filtered out before the city and guest-count filters even run. Because the bitmap is only about 46 bytes per listing, the whole year for 7M listings is about 322 MB, small enough to keep in memory on every search node.
Hotspots: three different problems
A viral listing (read hotspot). Suppose one listing gets 50,000 detail-page views per second after going viral. Writes to it are still bounded (it can only be booked a handful of times per day), so this is purely a read problem. Serve the detail page from the cache and CDN with a short TTL (time-to-live, how long a cached copy is served before refetching), and collapse concurrent cache misses into one database read (request coalescing). The shard itself only sees the booking attempts, which are rare.
A hotel room type on a peak night (write-contention hotspot). A hotel with 200 identical "Deluxe King" rooms modelled as one row available = 200 makes every booking attempt for that night update the same row, so attempts queue behind one row lock. The fix is to model inventory as 200 unit rows and have each booking claim any free one:
SELECT unit_id FROM room_units
WHERE room_type_id = $1 AND night = $2 AND booking_id IS NULL
LIMIT 1
FOR UPDATE SKIP LOCKED;
FOR UPDATE locks the row it selects until the transaction ends, so no other transaction can also claim it before this one commits or rolls back. SKIP LOCKED (PostgreSQL and MySQL 8 both support it) then makes concurrent attempts pick different free rows instead of queuing behind the same one: each attempt skips past any row another transaction already has locked and grabs the next free one instead, so contention drops from "one lock for the whole room type" to "one lock per unit".
A hot destination (search hotspot). If the search index were partitioned by city, New Year's week in one city could send a large share of all searches to one partition group. Partitioning the search index by listing hash instead means every query fans out to all index shards (scatter-gather) and each does a small slice of the work, so no single shard is hot. The cost is fan-out, which is paid for with a geo filter pushed down to each shard (each index shard evaluates the "is this within range of Lisbon" check itself, on its own slice of listings, in parallel, instead of shipping every candidate to one place to filter) and more replicas during seasonal peaks. I accept that cost because a destination's popularity is unpredictable and a hash layout never needs rebalancing when it changes.
Resharding
Resharding is changing which server owns which data, usually because you add servers. The 4,096 logical shards are what make it cheap:
- Going from 16 to 20 servers moves logical shards, not rows chosen by a new hash. Each server should end up with 4,096 / 20 ≈ 205 logical shards, so about 4,096 × 4 / 20 ≈ 819 logical shards (20% of the data) move, all onto the new servers.
- With naive
hash(listing_id) mod N, changing N from 16 to 20 moves every key whose remainder changes. Over the integers 1 to 1,000,000 that is 80% of keys (computed directly by counting keys wherek mod 16differs fromk mod 20), so almost everything would be copied.
Moving one logical shard: (1) bulk-copy it to the destination while it keeps serving; (2) tail its change log (keep streaming every write that happens after the bulk copy started, in commit order, using the same change-data-capture mechanism described earlier in this design) onto the destination until the copy is caught up; (3) briefly block writes to that one logical shard (a few seconds), apply the last changes, flip the lookup table entry, and unblock. Only 1/4,096 of listings see the pause at a time, and a booking that hits the pause gets a retryable error that the client retries with the same idempotency key (a value the client generates once per booking attempt and resends on every retry, so the server can recognise the retry as the same attempt rather than a new one).
Replica lag
Each read decides whether it can tolerate stale data:
| Read | Can it be stale? | Where it goes |
|---|---|---|
| Search results, listing detail | Yes, seconds | Replicas and caches |
| The availability check inside a booking | No | Primary, inside the booking transaction |
| "Your booking is confirmed" and the next page load | Must reflect the guest's own write (read-your-writes) | Primary, or a replica known to have caught up |
For read-your-writes, the booking response carries the commit position of the write (in PostgreSQL, the WAL position from pg_current_wal_lsn(), where WAL is the write-ahead log and LSN is log sequence number, the byte offset into that log, which only ever increases, so comparing two LSNs tells you which one happened first). The next read sends it back; the router picks a replica whose pg_last_wal_replay_lsn() is at or past that position, or falls back to the primary. Replicas lagging beyond a threshold (say 5 seconds) are removed from the read pool automatically so a slow replica cannot serve very stale availability.
Search showing a listing as free when it was just booked is acceptable, because the booking transaction re-checks on the primary and returns "no longer available". What is not acceptable is the reverse check being done on a replica: that is how double bookings happen.
Trade-offs and pitfalls
- Partitioning bookings by
guest_idfirst makes "my trips" a single-shard read but turns every booking into a cross-shard operation against the listing's calendar. The correctness-critical path should get the locality. - Partitioning by geography feels natural but creates permanent imbalance (one city can have 50 times the listings of another) and forces a painful move when a listing's region boundary changes. Hash plus a geo filter in search is simpler to operate.
- Hosts with thousands of listings (property managers) make host-dashboard reads scatter across shards. That is acceptable for a dashboard; if it is not, add a
host_idderived view the same way asguest_id. - What would change my choice: if most inventory were fungible units (interchangeable stock where any one unit satisfies a request equally well, like any of 200 identical "Deluxe King" rooms, unlike a one-of-a-kind home listing) at large hotels rather than unique homes, I would model inventory per room type and night with unit rows as the primary entity and shard by
property_id, because then the property, not the listing, is the unit of contention.
Design the architecture for a delivery matching service that must handle 100k concurrent drivers, 10M orders/day, average match latency < 200ms, and geographic locality. Sketch the major components, partitioning approach, communication patterns, how state is managed, and how you'd ensure scalability and fault tolerance.
Sample Answer
Direct answer
Partition by geography: split the service area into zones (groups of H3 hexagonal cells, H3 being Uber's open-source grid that divides the map into hexagons), and give each zone exactly one matcher shard that holds the live driver state for that zone in memory. Driver locations flow in through a partitioned stream, orders are routed to the shard that owns their pickup zone, and the shard picks a driver and commits the assignment with an atomic compare-and-set on the driver's record. The load is small per shard, so the hard parts are not throughput but zone boundaries, hot spots, and recovering a shard without losing or doubling assignments.
The load, per shard
| Quantity | Arithmetic | Result |
|---|---|---|
| Average orders | 10,000,000 / 86,400 s | about 116/s |
| Peak orders (assume 3 times average) | 3 × 115.7 | about 347/s |
| Location updates (one ping per driver every 4 s) | 100,000 / 4 s | 25,000/s |
| Largest shard (a big metro with 15% of drivers) | 0.15 × 100,000 / 4 s | 3,750 updates/s |
| In-memory driver state (200 bytes per driver: id, position, status, version, vehicle) | 100,000 × 200 B | 20 MB |
The whole fleet's live state is 20 MB, and the biggest shard handles a few thousand updates per second. One process per zone can do that comfortably; we shard for locality and failure isolation, not raw capacity.
Components
flowchart LR
DA[Driver app] --> GW[Connection gateway]
CA[Customer app] --> OS[Order service]
GW --> LS[Location stream partitioned by zone]
LS --> MS[Matcher shard per zone]
OS --> ROUTER[Zone router]
ROUTER --> MS
MS --> DS[Driver assignment store]
MS --> GW
COORD[Shard coordinator] --> MS
- Connection gateway: holds a persistent connection (WebSocket, a two-way channel that stays open) to each driver app; receives pings, pushes offers. Stateless apart from the open sockets; drivers reconnect to any instance.
- Location stream: a distributed log such as Kafka (an ordered, replayable stream of messages, split into partitions so many consumers can process different partitions in parallel while each partition itself stays strictly ordered), with the partition key = zone ID, so all pings for one zone land on one partition and reach one consumer in order.
- Zone router: maps an order's pickup point to its H3 cell, then to the owning zone and shard.
- Matcher shard: in-memory index of drivers in its zone (a dictionary from H3 cell to the set of available drivers), plus matching logic.
- Driver assignment store: the durable truth of "driver D is assigned to order O" (a key-value or relational table keyed by driver ID with a version number).
- Shard coordinator: assigns zones to shard instances using leases (time-limited ownership that must be renewed), through a coordination service such as etcd or ZooKeeper (small, strongly consistent key-value stores built specifically to hand out this kind of exclusive, renewable ownership correctly, even when a node crashes mid-renewal).
How matching works inside a shard
- Order arrives with pickup point P. Compute P's H3 cell and a ring of neighbouring cells (a "k-ring": the cell plus all cells within k steps). At resolution 8, cells average about 0.74 km² with edges about 0.53 km. Neighbouring cell centres are therefore about 0.53 x sqrt(3), roughly 0.92 km, apart (the standard spacing between adjacent regular hexagons of that edge length), so k = 2 (two rings out) reaches roughly 1.8 to 2 km from the pickup point, not the width of a single cell.
- Collect available drivers from those cells; if fewer than a minimum count, widen k.
- Rank by estimated time to pickup (from a routing service, one batched call), not straight-line distance, because a river or a one-way street makes the nearest driver slow.
- Commit: conditional write on the driver's record, "set assigned = O, version = v+1 only if version = v and assigned is empty". If it fails, take the next driver.
- Push the offer through the gateway. If the driver declines or the offer times out (say 15 s), release and repeat for the next candidate.
Latency: steps 1 and 2 are in-memory (well under 5 ms), step 3 is one network call, step 4 is one write; 200 ms average is comfortable, with room to keep p99 (the latency that 99% of matches beat) under the same bar.
Partitioning approach and boundary effects
- Zones follow demand, not a fixed grid. A dense downtown gets small zones; a suburb gets large ones. The coordinator can split a zone that gets hot (a stadium emptying) into two and move one half to another shard.
- Boundaries: an order 300 m from a zone edge has good drivers on the other side. Two options:
- Halo replication: each shard also receives location updates for a band of cells just outside its zone, read-only. It can see those drivers but must commit through the driver's owning record (the assignment store), so ownership stays single.
- Scatter-gather: ask the neighbour shard for candidates. Simpler data flow but an extra network hop.
I would use halo replication: it keeps the common case to one shard, and correctness still rests on the single conditional write.
- Why the assignment store is separate from the shard: a driver moving across a boundary briefly appears in two shards' views. If each shard trusted its own memory, both could assign the same driver. The conditional write on one durable record is what makes "one driver, one order" true regardless of which shard wins.
Communication patterns
| Flow | Pattern | Why |
|---|---|---|
| Driver pings | Asynchronous stream | High volume, losing one ping is harmless (the next arrives in 4 s) |
| Order to shard | Synchronous request | The customer is waiting for "finding your driver" |
| Assignment commit | Synchronous conditional write | Must be decided before the offer is sent |
| Offer to driver | Push over the open connection | Low latency; the app acknowledges |
| Assignment events to other services (tracking, billing) | Asynchronous events via an outbox (the event is written in the same database transaction as the assignment, then published) | Other services must not be able to miss or invent an assignment |
State management and fault tolerance
- Driver positions are soft state: if a shard dies, its replacement rebuilds the index simply by consuming the zone's partition, and because every driver re-pings every 4 s, the index is complete within about one ping interval even without a snapshot.
- Assignments are hard state: they live only in the durable store, so a shard crash loses nothing that was committed.
- Split brain (two processes both believing they own a zone): the coordinator's lease makes it rare, and a fencing token makes it harmless. Each lease grant comes with an increasing number, every assignment write carries it, and the store rejects writes carrying an older token than the latest it has seen for that zone. A paused old owner that wakes up cannot commit.
- Orders in flight during failover: the order service retries after a timeout with the same order ID, and the matcher first checks "is this order already assigned?", so the retry cannot create a second assignment.
- Backpressure (slowing producers when consumers cannot keep up): if a shard falls behind on pings, it drops stale pings for a driver in favour of the newest one, since only the latest position matters.
Scaling
- More drivers or orders: more, smaller zones; shards are cheap.
- More regions: each region runs its own set of shards for its cities, with no cross-region traffic on the matching path.
- The assignment store is partitioned by driver ID; at about 347 commits/s at peak it is lightly loaded.
Trade-offs and pitfalls
- Straight-line nearest is not nearest: ranking by distance instead of travel time is the most common quality bug.
- Fixed grid shards: equal-area shards put a downtown and a farm on equal footing; hot zones overload while others idle.
- Trusting in-memory state for exclusivity: the shard's view is a cache; exclusivity comes from the conditional write.
- Greedy per-order matching is what I would ship first for 200 ms; batching orders for a second or two and solving them together improves total pickup time in dense zones, and is the next step if measured pickup times show greedy choices stealing drivers that a later order needed more.
Design the booking and reservation flow for a marketplace where multiple guests can attempt to reserve the same item or time slot at the same time. The system must prevent double booking, support retries from mobile clients, and recover cleanly from partial failures. Include how you would model holds, expiration, idempotency, and state transitions.
Sample Answer
Direct answer
Make the inventory's database the only referee. A booking starts as a hold: a row with status held and an expiry, created by a single atomic insert that the database itself refuses when it would overlap another live hold or booking. Every client request carries an idempotency key, so a mobile retry returns the original outcome instead of creating a second hold. Confirmation is a conditional state transition (held to confirmed only if the hold is still alive), payment is authorised against the hold and captured only after confirmation, and a reconciliation job repairs every half-finished combination a crash can leave behind.
Terms used below
- Hold: a short-lived reservation that blocks the item while the guest pays.
- Idempotency key: a unique id the client generates once per user intent (one tap of "Reserve") and resends on every retry; the server stores it with the result so a repeat returns the same result.
- Exclusion constraint: a PostgreSQL rule that rejects a row if it "conflicts" with an existing row under chosen operators; here, same listing and overlapping dates. It is backed by a GiST index (generalized search tree, an index type that supports range overlap).
- tstzrange: a PostgreSQL range type holding two timestamps. Written
[start, end): the square bracket means the start is included, the round bracket means the end is excluded, so a checkout on one day and a check-in on that same day do not count as overlapping. - The
&&operator: true when two ranges share any point in time. This is the "conflicts" test the exclusion constraint uses on thestaycolumn below. - btree_gist: exclusion constraints need a GiST index, and by default GiST only knows how to compare range values against each other. The
btree_gistextension teaches it to also compare a plain equality column, which the constraint below needs for itslisting_id WITH =clause. - Authorisation and capture: authorisation reserves money on the guest's card without taking it; capture actually takes it. A PSP (payment service provider, such as a card processor) exposes both as separate calls.
- Reconciliation: a periodic job that compares two systems' records (here, bookings and payments) and fixes disagreements.
State machine
stateDiagram-v2
[*] --> held: place_hold succeeds
held --> confirmed: payment authorised and hold still alive
held --> expired: hold_expires_at passes
held --> cancelled: guest abandons
confirmed --> cancelled: guest or host cancels, refund issued
expired --> [*]
cancelled --> [*]
confirmed --> [*]: stay completed
| Transition | Guard (checked atomically in the database) | Side effect |
|---|---|---|
none to held | no live row overlaps the dates | start 10-min expiry |
held to confirmed | status is held and expiry is in the future | capture payment |
held to expired | expiry passed; done lazily by the next conflicting hold, or by a sweeper | void the authorisation (tell the card network to release the hold; unlike a refund, no money ever moved, so there is nothing to pay back) |
confirmed to cancelled | cancellation policy allows it | refund per policy |
The core, as runnable SQL (PostgreSQL 16)
CREATE EXTENSION IF NOT EXISTS btree_gist;
CREATE TABLE reservation (
id bigserial PRIMARY KEY,
listing_id bigint NOT NULL,
stay tstzrange NOT NULL, -- [check-in, check-out)
guest_id bigint NOT NULL,
status text NOT NULL CHECK (status IN ('held','confirmed','expired','cancelled')),
hold_expires_at timestamptz,
idempotency_key text NOT NULL,
UNIQUE (guest_id, idempotency_key),
-- no two live reservations may overlap on the same listing
EXCLUDE USING gist (listing_id WITH =, stay WITH &&)
WHERE (status IN ('held','confirmed'))
);
-- place_hold: idempotent on (guest, key); reclaims expired holds; the constraint arbitrates races
CREATE FUNCTION place_hold(p_listing bigint, p_stay tstzrange, p_guest bigint, p_key text, p_retries int DEFAULT 3)
RETURNS TABLE (reservation_id bigint, outcome text) LANGUAGE plpgsql AS $$
DECLARE r reservation;
BEGIN
SELECT * INTO r FROM reservation WHERE guest_id = p_guest AND idempotency_key = p_key;
IF FOUND THEN RETURN QUERY SELECT r.id, 'replayed:' || r.status; RETURN; END IF;
UPDATE reservation SET status = 'expired'
WHERE listing_id = p_listing AND stay && p_stay
AND status = 'held' AND hold_expires_at < now();
BEGIN
INSERT INTO reservation (listing_id, stay, guest_id, status, hold_expires_at, idempotency_key)
VALUES (p_listing, p_stay, p_guest, 'held', now() + interval '10 minutes', p_key)
RETURNING * INTO r;
RETURN QUERY SELECT r.id, 'held'::text;
EXCEPTION WHEN exclusion_violation OR unique_violation THEN
-- either a concurrent retry with the same key won the insert, or the dates are taken
SELECT * INTO r FROM reservation WHERE guest_id = p_guest AND idempotency_key = p_key;
IF FOUND THEN RETURN QUERY SELECT r.id, 'replayed:' || r.status;
ELSE RETURN QUERY SELECT NULL::bigint, 'unavailable'::text;
END IF;
WHEN deadlock_detected THEN
-- two inserts landing at the true same instant on the same listing can make Postgres
-- pick this one as the deadlock victim instead of cleanly losing the exclusion check
-- (measured below); the failed attempt already rolled back with this subtransaction, so
-- retry from the top, which re-resolves against whatever the other transaction committed
IF p_retries <= 0 THEN
RETURN QUERY SELECT NULL::bigint, 'unavailable'::text;
ELSE
RETURN QUERY SELECT * FROM place_hold(p_listing, p_stay, p_guest, p_key, p_retries - 1);
END IF;
END;
END $$;
-- confirm only a live hold; a replayed confirm is a no-op; anything else means the hold was lost
CREATE FUNCTION confirm(p_id bigint) RETURNS text LANGUAGE plpgsql AS $$
BEGIN
UPDATE reservation SET status = 'confirmed', hold_expires_at = NULL
WHERE id = p_id AND status = 'held' AND hold_expires_at > now();
IF FOUND THEN RETURN 'confirmed'; END IF;
IF EXISTS (SELECT 1 FROM reservation WHERE id = p_id AND status = 'confirmed') THEN
RETURN 'confirmed (replay)';
END IF;
RETURN 'hold lost: void the payment authorization';
END $$;
Design choices in that code:
- Reading the constraint aloud.
EXCLUDE USING gist (listing_id WITH =, stay WITH &&)means: reject a new row if a live row already exists with the samelisting_id(the=check) and an overlappingstayrange (the&&check).stayis atstzrange, so&&is testing whether the two half-open date ranges share any point in time. - Two different collisions land in the same handler. In the
EXCEPTION WHEN exclusion_violation OR unique_violationblock,exclusion_violationmeans the dates are genuinely taken by someone else;unique_violationmeans a concurrent request with the same idempotency key won the race to insert first. The handler tells them apart by re-reading the row for that key: if it is there, this was a retry (replayed:...); if it is not, the dates were unavailable. - The constraint is the lock. Two concurrent inserts for overlapping dates cannot both commit; the database serialises them on the index. No distributed lock, no "check then insert" race.
- A serialisation failure is not an error the caller should ever see. PostgreSQL can resolve two truly simultaneous inserts on the same listing by aborting one with
deadlock detected(SQLSTATE40P01) rather than by cleanly losing the exclusion check, because the check on each side waits on the other side's not-yet-committed row.place_holdcatchesdeadlock_detectedthe same way it catchesexclusion_violation, and retries itself (bounded,p_retries) so the caller still gets a plainheldorunavailable, never a raw database error. Measured below. - Expired holds are reclaimed lazily inside the same transaction, so a crashed sweeper never blocks inventory. A background sweeper (a small job that runs on a timer, independent of any single request) still runs every minute to void authorisations and free rows for display.
- The idempotency key is scoped to the guest and enforced by a unique constraint, so even two retries racing each other produce one row.
- A rejected attempt stores nothing, so retrying the same key after the dates free up can succeed. If your product needs "same key, same answer forever", store the rejection too, with a short TTL (time-to-live).
Worked example: the flow, retries and a late payment
\pset footer off
\echo '1) guest 1 holds 10-12 Oct'
SELECT * FROM place_hold(7, '[2026-10-10,2026-10-12)', 1, 'k-aaa');
\echo '2) mobile client retries the same request (same key)'
SELECT * FROM place_hold(7, '[2026-10-10,2026-10-12)', 1, 'k-aaa');
\echo '3) guest 2 wants 11-13 Oct (overlaps)'
SELECT * FROM place_hold(7, '[2026-10-11,2026-10-13)', 2, 'k-bbb');
\echo '4) guest 1 hold expires (simulated by backdating), guest 2 retries (same key: a rejected attempt stores nothing)'
UPDATE reservation SET hold_expires_at = now() - interval '1 second' WHERE idempotency_key = 'k-aaa';
SELECT * FROM place_hold(7, '[2026-10-11,2026-10-13)', 2, 'k-bbb');
\echo '5) guest 1 payment callback arrives late and tries to confirm the expired hold'
SELECT confirm(1);
\echo '6) guest 2 confirms'
SELECT confirm(3);
\echo '7) the confirm response was lost on a flaky network; the app retries it'
SELECT confirm(3);
SELECT id, guest_id, stay, status FROM reservation ORDER BY id;
Output:
1) guest 1 holds 10-12 Oct
reservation_id | outcome
----------------+---------
1 | held
2) mobile client retries the same request (same key)
reservation_id | outcome
----------------+---------------
1 | replayed:held
3) guest 2 wants 11-13 Oct (overlaps)
reservation_id | outcome
----------------+-------------
| unavailable
4) guest 1 hold expires (simulated by backdating), guest 2 retries (same key: a rejected attempt stores nothing)
UPDATE 1
reservation_id | outcome
----------------+---------
3 | held
5) guest 1 payment callback arrives late and tries to confirm the expired hold
confirm
-------------------------------------------
hold lost: void the payment authorization
6) guest 2 confirms
confirm
-----------
confirmed
7) the confirm response was lost on a flaky network; the app retries it
confirm
--------------------
confirmed (replay)
id | guest_id | stay | status
----+----------+-----------------------------------------------------+-----------
1 | 1 | ["2026-10-10 00:00:00+00","2026-10-12 00:00:00+00") | expired
3 | 2 | ["2026-10-11 00:00:00+00","2026-10-13 00:00:00+00") | confirmed
Id 2 is missing because the rejected insert in step 3 consumed a sequence value (the next number handed out by the auto-incrementing counter behind bigserial, given to every insert attempt whether it succeeds or not); sequences are not rolled back, which is harmless.
Two guests at the same instant. Running the same place_hold for the same listing and dates in two sessions at once, each inside a transaction that stays open for 2 seconds:
-- race.sql, run in two terminals at once:
-- psql -v guest=21 -v key=r-1 -f race.sql and psql -v guest=22 -v key=r-2 -f race.sql
BEGIN;
SELECT * FROM place_hold(9, '[2026-11-01,2026-11-03)', :guest, :'key');
SELECT pg_sleep(2);
COMMIT;
Most of the time this behaves exactly as it looks like it should: one session prints 4 | held, the other waits on the first transaction and then prints unavailable.
But run the same pair of sessions repeatedly against the original two-branch handler (the one without the deadlock_detected arm above) and it does not resolve that cleanly every time. Across 16 truly concurrent pairs (2-second overlap window, a fresh listing each run), 2 of the 16 came back as a raw psql error instead of a held/unavailable split:
ERROR: deadlock detected
DETAIL: Process 128 waits for ShareLock on transaction 748; blocked by process 129.
Process 129 waits for ShareLock on transaction 750; blocked by process 128.
CONTEXT: while checking exclusion constraint on tuple (0,7) in relation "reservation"
That is PostgreSQL's own concurrency control, not a bug in the exclusion constraint: when two sessions insert conflicting rows at nearly the same instant, each one's constraint check can end up waiting on the other's not-yet-committed row, and the two waits form a cycle that Postgres breaks by aborting one side. The exclusion constraint still guarantees no two overlapping rows are ever both committed; it does not guarantee the loser gets a clean answer back from place_hold instead of an unhandled exception. A caller that only expects held or unavailable, as the earlier examples show, would see this as a request that failed for no visible reason and, if it does not know to retry a 40P01, could surface a false "something went wrong, try again" to a guest who was never actually going to get the booking anyway.
With the deadlock_detected arm added above, the same test resolves cleanly every time: 20 more truly concurrent pairs, 20 clean held/unavailable splits, zero raw errors reaching the client. Exactly one guest wins the constraint on every individual insert attempt, as before; the fix is making sure the losing side's last attempt is always one that returns an answer instead of occasionally being the one Postgres chose to abort outright.
The same script run twice at once for one guest with one key (a double-tapped button, or a retry fired while the first request was still in flight) printed 7 | held in one session and 7 | replayed:held in the other: one row, and both callers learn its id. (The id numbers in these race runs depend on how many sequence values earlier attempts consumed; the pattern of outcomes is what repeats.) That is why the exception handler looks the key up before answering unavailable.
Recovering from partial failures
| What failed | What the client sees | Recovery |
|---|---|---|
| Hold created, response lost | timeout | client retries with the same key and gets replayed:held |
| Payment authorised, then the hold expired | "Sorry, the dates were released" | confirm returns "hold lost"; void the authorisation immediately; reconciliation re-checks voids |
| Confirm committed, response lost | timeout | client retries; confirm returns confirmed (replay) instead of an error |
| Crash between PSP capture and database update | booking stuck in held with money captured | reconciliation queries the PSP by reservation id (sent as the PSP's own idempotency key and reference) and completes or refunds |
| Event to host/guest notifications lost | none | write events to an outbox table (a table in the same database, written in the same transaction as the state change, holding events still waiting to be sent out) in the same transaction as the state change; a background relay (a process that reads new outbox rows and publishes them, then marks them sent) publishes them |
Payment ordering matters: authorise during the hold, capture after the state flips to confirmed. Capturing first means every lost hold turns into a refund, which is slower for the guest and costs fees.
The client side of idempotency: the mobile app creates the key when the guest taps "Reserve" and persists it until it gets a definitive answer, including across app restarts. A key generated per HTTP attempt instead of per intent defeats the whole mechanism.
Scale and trade-offs
- Shard by
listing_id(split the reservation table across multiple database servers, routing each listing's rows to one server by hashing or ranging its id). Every conflict is within one listing, so all checks stay on one shard and never need a cross-shard transaction. - Why not a distributed lock (for example a Redis lock) around check-then-insert? A lock with a timeout can expire during a long pause in its holder, for example a garbage-collection pause, a slow disk write, or a network stall that cuts it off from everyone including the lock service, and the holder, unaware that time has passed, still proceeds as if it holds the lock; then two writers act at once. The constraint in the system of record has no such window: the database itself is the referee on every write, not a timer. What would flip it: inventory that is not in a database that can enforce the rule, for example a third-party channel manager, where you need a lock plus a fencing check (an increasing number issued with every lock grant, carried on every write, so the external system can reject a write from a holder whose number is no longer the latest) at the external system.
- Hold length: 10 minutes balances payment flows that include bank verification against inventory blocked by abandoned carts. For high-demand inventory, shorten it and show a countdown.
- Counted inventory is different. For "12 identical rooms of type X" or seats in a section, use a per-date counter with a conditional decrement (
UPDATE ... SET available = available - 1 WHERE available > 0) instead of range exclusion. - Pitfall: checking availability in the application, then inserting. It passes every test with one user and double-books under load.
- Pitfall: relying on a sweeper for correctness. If expiry only happens when the sweeper runs, a sweeper outage looks like sold-out inventory.
Unlock Full Question Bank
Get access to all 19 Marketplace, Dispatch, and Logistics System Design interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.