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.
Describe how external traffic providers (third-party APIs) should be integrated into a production ETA pipeline. Discuss polling vs streaming, freshness handling, confidence scoring of sources, API rate limits, and how to fall back when a provider is slow or unavailable.
Sample Answer
Direct answer
Keep third-party traffic providers off the request path. A background ingestion service pulls (or receives) provider data, normalises it onto our own road segments, stamps every value with its observation time, and writes it into a fast "current traffic" table. The ETA (estimated time of arrival) service only ever reads that table, so a slow or dead provider makes ETAs a little less accurate, never slower or failing. Prefer streaming when a provider offers it, poll on a schedule that fits inside the rate limit when it does not, attach a confidence score to each source that decays with age, and fall back in a fixed order: other live provider, our own fleet's recent speeds, then historical speeds for that time of day.
The pipeline
flowchart LR
P1[Provider A stream] --> ING[Ingest adapters]
P2[Provider B polled API] --> ING
FLEET[Own fleet speeds] --> ING
ING --> NORM[Map to our road segments]
NORM --> FUSE[Freshness and confidence scoring]
HIST[Historical speed profiles] --> FUSE
FUSE --> TBL[(Current traffic table)]
TBL --> ETA[ETA service]
One adapter per provider isolates that provider's format, auth and quirks. Normalisation matters because each provider describes roads in its own way (its own segment IDs, or map tiles, or location references); mapping everything onto our segment IDs once, at ingest, means the rest of the system never sees provider formats.
Polling versus streaming
| Streaming (provider pushes updates, for example over a persistent connection or a message feed) | Polling (we call the API on a schedule) | |
|---|---|---|
| Freshness | Seconds after the provider observes a change | At best the poll interval |
| Rate limits | Usually not per update | Every call counts against the quota |
| Failure detection | Silence is ambiguous: no traffic change, or a dead connection? Needs heartbeats | Obvious: the call fails or times out |
| Operational cost | Long-lived connections, reconnect and resume logic | Simple, stateless workers |
Choice: stream when offered, with a heartbeat check (no message for, say, 60 s means treat the feed as down and reconnect). Poll otherwise, and spend the rate limit where it matters.
Worked example: fitting polling inside a rate limit. A provider allows 10 requests per second and returns one map tile per request. The city is covered by 400 tiles.
- Uniform refresh every 60 s: 400 / 60 = 6.7 requests per second, inside the limit but with little headroom for retries.
- Tiered refresh: the 100 tiles where most active trips are refresh every 30 s (100 / 30 = 3.3 per second) and the other 300 every 120 s (300 / 120 = 2.5 per second), for 5.8 per second in total. Busy areas get fresher data and the quota keeps about 40% headroom for retries and bursts.
Enforce the budget client-side with a token bucket (a counter that refills at the allowed rate and is spent one token per call), and honour the provider's own throttling responses (typically HTTP 429 "too many requests", often with a Retry-After header) by backing off rather than retrying immediately.
Freshness and confidence
Every value carries the time the provider observed it, not the time we received it. A reading's confidence decays with age: for example full weight when under 2 minutes old, linearly down to zero at 10 minutes, and ignored after that. Also score each provider's accuracy over time by comparing its speeds against our own drivers' actual travel times on the same segments later, so a provider that is fresh but systematically wrong is trusted less.
Two providers that disagree. Say provider A says a segment moves at 15 km/h and B says 45 km/h. Do not average blindly (30 km/h is what neither observed). Prefer the one with the higher confidence score (fresher and historically more accurate); if our own fleet has recent traversals of that segment, use them as a tie-breaker; if they still disagree and neither is clearly better, use the slower value for dispatch decisions (under-promising is cheaper than a missed pickup) and widen the ETA range shown to the rider.
Protecting against noisy or stale data from a single provider. Validate each value on ingest: reject speeds above the road's plausible maximum, reject values older than the previous one for that segment (out-of-order data), and flag a provider whose readings do not change at all for an unusually long time (a frozen feed looks fresh by timestamp but is not). Clamp how fast a segment's speed can change between consecutive updates unless several sources agree, which stops one glitchy reading from rerouting a whole city.
Fallback when a provider is slow or down
- Timeouts and circuit breakers on the ingest side: each call has a strict timeout (say 2 s); after repeated failures the circuit opens (stop calling for a cool-off period, then probe with a single call), so a sick provider does not tie up workers.
- Last good value, with decaying confidence: the table keeps serving the last reading, and its falling confidence shifts weight to other sources automatically.
- Fallback order per segment: another live provider, then our own fleet's speeds from the last few minutes, then the historical profile for that segment, day of week and time of day.
- Tell downstream about degraded mode: the ETA response carries a confidence flag, so the app can show a range ("12 to 18 min") instead of a precise number, and dispatch can add margin.
Cache provider responses at ingest with a short time-to-live (TTL) tied to their freshness window, so retries and multiple consumers never re-spend quota for data we already have.
Pitfalls
- Calling a provider inside the ETA request: the provider's slowest response becomes your p99 (99th-percentile latency), and its outage becomes yours.
- Using receive time instead of observation time, which makes a delayed batch look fresh.
- Silent quota exhaustion: alert on the rate-limit headroom, not only on errors.
- Treating historical fallback as good as live data during incidents or events; always surface lower confidence.
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.
Describe map-matching: algorithms to snap raw GPS traces to road segments, how to handle low-frequency telemetry, GPS noise and multipath, and tradeoffs between accuracy and compute cost for real-time ingestion at city scale.
Sample Answer
Direct answer
Map-matching turns a noisy sequence of GPS points into the sequence of road segments the vehicle actually drove. The simple method snaps each point to the nearest road, which is cheap but breaks at parallel roads, intersections and overpasses. The robust method is a hidden Markov model (HMM): each point has a few candidate road positions, and the best path is the one that balances "close to the GPS point" against "reachable from the previous candidate by a plausible drive", decoded with the Viterbi algorithm. At city scale I would run two tiers: a cheap incremental matcher on the live path (dispatch and ETA (estimated time of arrival) only need "which road is the driver on right now") and a windowed HMM matcher asynchronously for anything that needs the whole trail, such as trip distance and fares.
What goes wrong with raw GPS
A phone reports latitude, longitude, a timestamp and an accuracy radius. Three kinds of error matter:
- Random noise: typically a few metres to a couple of tens of metres in open sky, so a point often lands on the wrong side of a divided road.
- Multipath: in dense downtowns the satellite signal bounces off buildings before reaching the phone, so a single point can jump 50 to 200 m onto a parallel street and then jump back.
- Low frequency: to save battery and data, a driver app might send one point every 5 to 30 s. At 15 m/s (54 km/h) a 20 s gap is 300 m, which can span two or three intersections. Between the points you do not know which turn was taken.
The algorithms, from cheapest to most robust
| Method | How it works | Where it fails | Cost per point |
|---|---|---|---|
| Nearest segment (point-to-curve) | Find road segments within a radius using a spatial index (an R-tree: a tree of nested bounding boxes that answers "what is near here" quickly) and pick the closest | Parallel roads, overpasses, points near intersections; ignores the previous point entirely | One index lookup, microseconds |
| Incremental (geometric plus topological, whether one road segment actually connects to another, not just how close it looks on the map) | Score candidates by distance, by how well the segment's bearing (the compass direction the road segment points) matches the vehicle's heading, and by whether the segment connects to the previously matched one | Can lock onto a wrong road and never recover, because it commits point by point | Index lookup plus a few neighbour checks |
| HMM with Viterbi | Keep several hypotheses and choose the globally most likely path | Needs shortest-path computations between candidates, so it is the expensive one | k squared route queries per point, for k candidates |
How the HMM works, in plain terms
A hidden Markov model describes a process where you cannot see the true state (which road the car is on) but you see noisy observations (GPS points) that depend on it.
- Candidates: for each GPS point, take the k road positions within a search radius (say k = 5 to 8 within 50 m; widen the radius when the phone's reported accuracy is poor).
- Emission probability ("how well does this candidate explain the point"): a Gaussian in the distance between the GPS point and the candidate. A candidate 5 m away is far more likely than one 40 m away. The Gaussian's width is estimated from data, robustly, from the typical distance between GPS points and their true roads.
- Transition probability ("how plausible is it to drive from candidate A to candidate B in the elapsed time"): compare the straight-line distance between the two GPS points with the driving distance along the road network between the two candidates. For a real drive these are close; a candidate that needs a 2 km detour to connect a 150 m hop gets a tiny probability. This is the formulation from Newson and Krumm (2009) and it is the reason the HMM copes with multipath: a jump onto a parallel street needs an implausible route to reach and leave, so it loses.
- Viterbi decoding: a dynamic program that keeps, for each candidate of the current point, the best-scoring path that ends there. When the next point arrives it extends each of those paths by every transition and keeps the best again. At the end you backtrack to read the single most likely sequence of segments.
A concrete step, with numbers. Say a delivery van is on Main St approaching a T-junction with 5th Ave. GPS point 1 matched cleanly to Main St. Point 2 arrives 25 m further along by straight-line GPS distance, and, because of a multipath bounce off a building at the corner, its raw reading sits closer to 5th Ave's line than you might expect: 6 m from Main St's line, 9 m from 5th Ave's.
With GPS noise sigma = 8 m, emission probability (proportional to exp(-0.5 x (distance / sigma) squared)):
- Main St: exp(-0.5 x (6/8) squared) = exp(-0.281) ≈ 0.75
- 5th Ave: exp(-0.5 x (9/8) squared) = exp(-0.633) ≈ 0.53
On distance alone, Main St is only about 1.4x more likely (0.75 / 0.53), not a decisive win. This is where the transition term breaks the tie: staying on Main St means driving 25 m, matching the 25 m straight-line GPS distance exactly. Reaching the 5th Ave candidate means driving up to the junction and turning, a 35 m route for the same 25 m of straight-line movement, a 10 m mismatch. With a transition tolerance beta = 12 m, transition probability (proportional to exp(-|route distance - straight-line distance| / beta)):
- Main St: exp(-|25-25|/12) = exp(0) = 1.0
- 5th Ave: exp(-|35-25|/12) = exp(-0.833) ≈ 0.43
Multiplying emission by transition, Main St scores about 0.75 x 1.0 = 0.75 and 5th Ave about 0.53 x 0.43 = 0.23, a 3.3x margin, comfortably enough for the Viterbi step to keep Main St. The single extra piece of information, that the timing does not fit a turn, is what turns a coin-flip-ish 1.4x edge into a clear win. This is exactly the mechanism that lets the HMM resist multipath bounces that point-to-curve snapping cannot: point-to-curve only ever sees the 6 m versus 9 m distances and has no way to weigh in the drive.
Handling low-frequency telemetry
Low frequency is where the HMM earns its cost, because the transition step computes the actual route between candidates, so the matched output includes the road segments driven between points, not just the points. Three practical rules:
- Bound the route search by the time gap: the car cannot have travelled faster than, say, 1.5 times the road speed limit, so the shortest-path search stops at that distance.
- Break and restart when no candidate of the new point is reachable from any candidate of the old one (a tunnel, a long signal loss, or a U-turn in a car park). Start a new match segment rather than forcing an absurd route.
- Ask the client for batches, not fewer fixes: the phone can record a fix every 1 to 2 s and upload them in a batch every 10 s. Upload cost barely changes, but the matcher gets dense points and most of the ambiguity disappears.
Handling noise and multipath before matching
- Drop points whose implied speed from the previous point is physically impossible (for example over 60 m/s in a city).
- Use the phone's reported accuracy to widen the candidate radius and flatten the emission probability for that point, so a poor fix is trusted less.
- Optionally smooth with a Kalman filter (a recursive estimator that blends a motion prediction with each new measurement) before matching; it removes jitter but can round off real turns, so tune it conservatively.
Real-time at city scale: accuracy versus compute
Online versus offline. Full Viterbi needs the whole trace before it can backtrack. For live use, run a fixed-lag version (one that commits to a match a few points behind the newest point, once later points have had a chance to confirm it, rather than waiting for the whole trip to finish): decide the matched segment for the point from, say, 3 points ago, once later points have confirmed it. That adds latency equal to the lag (3 points at 5 s each is 15 s), so the live answer for the newest point comes from the incremental matcher and gets corrected when the lagged HMM decision lands.
Worked example: why the HMM cannot sit naively on the hot path. Take a city with 50,000 online drivers, each sending a point every 4 s:
- Points per second: 50,000 / 4 = 12,500.
- With k = 5 candidates per point, each step needs k squared = 25 route queries: 12,500 × 25 = 312,500 shortest-path queries per second.
- With k = 8 it is 12,500 × 64 = 800,000 per second.
Even at bounded search sizes, that is a large routing fleet for one city. The standard fixes:
- Precompute short shortest paths: an upper-bounded origin-destination table stores, for every road node, the shortest paths to all nodes within a few kilometres, so a transition becomes a hash lookup (near-instant retrieval from a precomputed table by key, no search needed) instead of a Dijkstra search (an algorithm that finds the shortest path between two points in a graph by exploring outward step by step from the start, more expensive than looking up a precomputed answer). This precomputed-table approach is what the open-source FMM "fast map matching" library does. It trades memory (gigabytes for a large city) for CPU.
- Prune candidates with heading: if the vehicle is travelling north, a southbound one-way segment is dropped before any route query.
- Match only what the hot path needs. Dispatch and ETA need the current segment and direction, which the incremental matcher gives in microseconds. The HMM runs per trip in a streaming job keyed by trip ID: a stream processor (a system such as Flink or Kafka Streams that continuously processes a flow of incoming events) groups every GPS point by which trip it belongs to and runs the HMM over each trip's own stream, where a few seconds of lag is fine.
Recommendation
For a ride-hailing or delivery platform: incremental matching with heading and connectivity on the live path, a fixed-lag HMM with precomputed transitions in the stream processor for the authoritative trail, and a full offline HMM over the finished trip for fare distance and disputes. Put the accuracy budget where money changes hands (fares, courier pay), and put the latency budget where the user is waiting (dispatch and the live map).
Trade-offs and pitfalls
- Nearest-segment on the fare path undercharges or overcharges on every divided highway; it is fine for "draw the car on a road" but not for billing.
- Ignoring road direction and turn restrictions lets the matcher route the car the wrong way down a one-way street to explain noise.
- A stale road graph (new roads, closures) produces systematic mismatches in one area. Monitor the rate of match breaks and high emission distances per map tile; a spike in one tile usually means the map is wrong, not the GPS.
- Over-tight search radius loses the true road when accuracy is poor; over-wide multiplies k and therefore the k squared transition cost.
- Treating fixed-lag output as final in the UI makes the car appear to jump roads; animate corrections or show only the confirmed trail.
You observe sudden ETA increases for many users in a single city. Walk through a root cause analysis plan: which services and metrics to inspect (telemetry ingestion rate, traffic feed freshness, routing engine latency/errors, recent deployments), immediate mitigation steps to reduce user impact, and how to capture evidence for a postmortem.
Sample Answer
Direct answer
The first question is whether trips are actually taking longer or whether only our predictions went up. If actual trip durations rose too, something happened on the roads (an accident, a storm, an event) and the ETA (estimated time of arrival) system is probably right. If actual durations are flat while predictions jumped, our system is wrong, and I check the usual suspects in order of how often they cause sudden, single-city jumps: a recent deployment or config change, stale or broken traffic data, a drop in driver telemetry, and routing engine errors or fallbacks. I mitigate by rolling back or switching the city to a known-good data source first and finishing the diagnosis afterwards, and I capture evidence as I go so the postmortem does not depend on memory.
Triage flow
flowchart TD
A[ETA spike in one city] --> B{Actual trip durations up too?}
B -->|Yes| C[Real-world event: confirm, widen ranges, no rollback]
B -->|No| D{Deploy or config change in the last hours?}
D -->|Yes| E[Roll back, compare replayed ETAs]
D -->|No| F{Traffic data age above normal?}
F -->|Yes| G[Switch city to historical speeds, fix feed]
F -->|No| H{Telemetry ingestion rate dropped?}
H -->|Yes| I[Check ingestion pipeline and app release]
H -->|No| J[Routing engine errors, fallbacks, map version]
What to inspect, and what each finding means
| Signal | Healthy looks like | Suspicious looks like | Likely cause |
|---|---|---|---|
| Predicted vs actual duration for completed trips, last few hours | ratio near its usual value | predictions up, actuals flat | our system, not the roads |
| Recent deployments (ETA model, routing, feature pipeline, map data, client app) and feature-flag changes (toggles that turn a code path on or off for some users without a full deploy) | nothing in the window | a change minutes before onset | the change |
| Traffic feed freshness: age of the newest speed data per city | refreshed every minute or two | minutes or hours old | stuck ingestion or provider problem |
| Telemetry ingestion rate (also called the probe rate: how many location pings per second are arriving from the city's drivers) | follows its usual daily curve | sudden drop | ingestion outage, or an app release that broke location upload |
| Routing engine latency and errors | stable P99 (99th percentile) latency, low error rate | timeouts, rising fallback rate | overloaded or crashing routing nodes, serving coarse fallback ETAs |
| Map data version in use | same as other cities' rollout plan | new version only in this city | bad map edit (a closed bridge, wrong speed limits) |
| Share of ETAs by quality tier / fallback level | mostly top tier | shift to lower tiers | a dependency is failing and fallbacks are pessimistic |
Worked example: the stale traffic table
At 11:00 the ETA for a typical 6 km cross-town trip in one city is 20 minutes instead of the usual 12. Completed trips are still taking about 12 minutes, so predictions are wrong. No deploy happened. The traffic-data age panel shows the city's speed table was last updated at 08:55.
That explains the number exactly. The table froze during rush hour, when this corridor averaged 18 km/h. At midday it normally runs at 30 km/h:
18 km/h6 km×60=20 min,30 km/h6 km×60=12 min
Every route in the city is being computed at 8:55 a.m. congestion levels, two hours after the congestion cleared. Only this city is affected because each city's table is built by its own job, and that job has been failing silently (for example, an upstream file format change that its parser rejects).
Immediate mitigation (minutes, not hours)
- Switch the city to the fallback speed source: historical average speed per road segment for this hour of the week. This brings ETAs back to roughly normal immediately.
- If a deploy is implicated, roll it back rather than fixing forward (pushing a new patch on top of the broken change instead of reverting it) during the incident.
- Widen displayed ETA ranges and pause "arriving in 1 minute" notifications for the city while quality is uncertain.
- Protect downstream decisions: surge pricing (the temporary price multiplier that rises when nearby demand outstrips available drivers, meant to pull more drivers into the area) and dispatch both read ETAs, because "how far away is the nearest driver" is itself computed from predicted travel time. Inflated ETAs can make dispatch think all drivers are far away and push surge up; freeze surge at its current cap (stop the multiplier from climbing any further, but leave it wherever it already is) or switch it to a supply-based signal only (compute the demand-supply imbalance from a raw count, open ride requests versus available drivers in the area, that does not depend on ETA at all), until ETAs are fixed.
- Then fix the root cause (restart or patch the feed job) and let the city return to live speeds once data is fresh for several consecutive refreshes.
Automated remediation, so next time it fixes itself
- Freshness watchdog per city. If the table normally refreshes every 2 minutes, page at 10 minutes of age (five missed refreshes) and automatically fall back to historical speeds at 15 minutes. An hour-plus stale table would then never be served.
- Prediction-vs-reality guard. Continuously compare the median ratio of predicted to actual duration for trips completed in the last 30 minutes. If it moves beyond a set band (for example 20% above normal for 15 minutes with enough trips), trigger the fallback and page.
- Automated rollback triggers. Any ETA model, feature or map release is rolled out city by city with the same guard; tripping it reverts the release automatically.
Capturing evidence for the postmortem
- Start an incident timeline immediately: first alert, each check, each action, with timestamps.
- Snapshot the dashboards (freshness, ingestion rate, latency, fallback share, predicted vs actual) covering an hour before onset through recovery; dashboard data may be downsampled (older points get averaged into coarser buckets to save storage, so minute-by-minute detail is lost) or expire.
- Save a sample of affected requests with their full inputs: route, traffic snapshot ID or timestamp, model and map versions, output. These let you replay the bad ETAs later.
- Preserve the failing job's logs and the offending input file before anyone retries or cleans up.
- Record the impact: number of trips shown inflated ETAs, cancellation rate vs baseline, any pricing effect.
- In the postmortem, the key question is not "why did the job fail" but "why could a stale table be served for two hours": the missing freshness check is the real defect.
Trade-offs and pitfalls
- Rolling back real events. If actual trip times are up (a storm), "fixing" the ETA back down makes it wrong. Always check actuals first.
- Over-sensitive guards. An automatic fallback that triggers on every small wobble swaps good live data for coarser history too often; require sustained deviation and minimum trip counts.
- Fixing only the ETA. Check what else consumed the bad numbers (pricing, dispatch, promised delivery windows) during the incident and whether any customers need remediation.
Explain the difference between Dijkstra's algorithm and A* for pathfinding in routing. Describe when you would choose A* over Dijkstra in an ETA / routing service and what properties the heuristic must satisfy for correctness.
Sample Answer
Direct answer
Both algorithms find the cheapest path from a start to a goal on a graph with non-negative edge weights (for routing, weights are travel times). Dijkstra grows outward from the start in rings of increasing cost, so it explores in every direction, including away from the goal. A* ranks each node by cost so far plus a heuristic estimate of the remaining cost, which steers the search toward the goal and settles fewer nodes. A* returns the same optimal answer as Dijkstra only if the heuristic never overestimates the true remaining cost (it is admissible); in practice you also want it consistent, so each node is settled once. In an ETA (estimated time of arrival) service I use A* (or a stronger goal-directed technique) for single point-to-point queries, and plain Dijkstra when I need costs from one point to many.
How they differ
- Dijkstra keeps a priority queue (a data structure that always hands back its smallest-cost item next, instead of needing a full scan) ordered by g(n), the best known cost from the start to node n. It pops the cheapest node, marks it settled (its cost is final), and relaxes its outgoing edges (checks whether going through it gives a neighbour a cheaper cost).
- A* orders the queue by f(n) = g(n) + h(n), where h(n) estimates the cost from n to the goal. With h(n) = 0 for every node, A* is Dijkstra.
What the heuristic must satisfy
Admissible:h(n)≤d(n,goal)for every node n Consistent:h(u)≤w(u,v)+h(v)for every edge (u,v),h(goal)=0Here d(n, goal) is the true cheapest cost from n to the goal and w(u, v) is the edge weight. Consistency implies admissibility and guarantees a node is never re-opened after it is settled, so the search stays as efficient as Dijkstra's bookkeeping. An admissible but inconsistent heuristic is still correct if you allow re-opening, but can do extra work.
For travel-time routing, the standard admissible heuristic is straight-line distance to the goal divided by the fastest speed allowed anywhere on the network. No real route can be shorter than a straight line or faster than the top speed, so this can never overestimate. Using a typical speed instead (say 50 km/h) would overestimate on motorways and break optimality.
Worked example (runnable)
A 60 x 60 grid of intersections 1 km apart, each road segment randomly assigned a speed class between 30 and 100 km/h, seed pinned. It compares Dijkstra, A* with the admissible heuristic, and A* with the same heuristic multiplied by 4 (which overestimates).
import heapq, math, random
random.seed(7)
N = 60 # 60 x 60 grid of intersections, 1 km apart
MAX_KMH = 100.0 # fastest speed any road segment allows
def node(r, c): return r * N + c
coords = {node(r, c): (c * 1.0, r * 1.0) for r in range(N) for c in range(N)}
graph = {v: [] for v in coords}
for r in range(N):
for c in range(N):
for dr, dc in ((0, 1), (1, 0)):
r2, c2 = r + dr, c + dc
if r2 < N and c2 < N:
kmh = random.choice([30, 50, 50, 80, 100]) # road class speed
minutes = 1.0 / kmh * 60 # 1 km segment
a, b = node(r, c), node(r2, c2)
graph[a].append((b, minutes)); graph[b].append((a, minutes))
def search(src, dst, h):
dist = {src: 0.0}; settled = set(); pq = [(h(src), 0.0, src)]
while pq:
f, g, u = heapq.heappop(pq)
if u in settled: continue
settled.add(u)
if u == dst: return g, len(settled)
for v, w in graph[u]:
ng = g + w
if ng < dist.get(v, math.inf):
dist[v] = ng; heapq.heappush(pq, (ng + h(v), ng, v))
return math.inf, len(settled)
src, dst = node(5, 5), node(40, 50)
def straight_line_minutes(v):
(x1, y1), (x2, y2) = coords[v], coords[dst]
return math.hypot(x2 - x1, y2 - y1) / MAX_KMH * 60 # never overestimates
for name, h in [("Dijkstra (h = 0)", lambda v: 0.0),
("A* admissible", straight_line_minutes),
("A* inflated x4", lambda v: 4 * straight_line_minutes(v))]:
cost, n = search(src, dst, h)
print(f"{name:18s} travel={cost:6.2f} min nodes settled={n}")
Output:
Dijkstra (h = 0) travel= 63.95 min nodes settled=3159
A* admissible travel= 63.95 min nodes settled=2121
A* inflated x4 travel= 71.85 min nodes settled=81
What it shows:
- The admissible A* returns exactly Dijkstra's 63.95 minutes while settling 2,121 nodes instead of 3,159 (33% fewer).
- The saving is modest because the heuristic assumes 100 km/h everywhere while most roads are slower, so it underestimates a lot. The closer h(n) is to the true remaining time, the more A* saves.
- The inflated heuristic settles only 81 nodes but returns a 71.85 minute route, 7.9 minutes worse than optimal. That is what an overestimating heuristic does: it charges straight at the goal and ignores the faster road nearby.
When I choose which in an ETA service
| Situation | Choice | Reason |
|---|---|---|
| One origin to one destination (a rider's trip ETA) | A*, or a precomputed speed-up | Goal direction pays off on a single target |
| One origin to many destinations (a driver's ETA to every waiting rider; the resulting map of "everywhere reachable within X minutes" is called an isochrone) | Dijkstra | It computes all costs in one pass; A* has no single goal to steer toward |
| Many candidate drivers to one pickup | Dijkstra on the reverse graph from the pickup | One search yields every driver's time |
| Production-scale point-to-point on a country graph | Precomputation (contraction hierarchies: offline shortcuts that skip over unimportant intersections so a live query touches far fewer nodes, or landmark-based ALT) | Plain A* on a big graph still settles far too many nodes for a tight latency budget |
Why the reverse graph turns one-to-many into many-to-one: build a copy of the graph with every edge's direction flipped, so an edge that let traffic flow from X to Y now lets the search move from Y to X. Running Dijkstra from the pickup on this flipped graph finds, in one pass, the cost from the pickup to every driver on the original graph, because a path from pickup to driver on the reversed graph is exactly a path from driver to pickup on the real one, walked backward. That turns 30 separate one-to-one searches, one per candidate driver, into a single one-to-many search.
ALT (A*, Landmarks, Triangle inequality) is the natural next step: precompute exact travel times from a few landmark nodes to all nodes, then use the triangle inequality (in any triangle, one side is never longer than the sum of the other two, so combining two landmark distances still gives a valid lower bound) to get a much tighter lower bound than straight-line distance, while staying admissible.
Trade-offs and pitfalls
- Learned heuristics (an ML model predicting remaining time) are tighter but not guaranteed to be lower bounds, so the route may be suboptimal, and you cannot bound how much. If you use one, clamp it below a provable lower bound, or accept bounded suboptimality explicitly: weighted A* multiplies the heuristic by a factor w > 1 to push the search harder toward the goal, and guarantees a route at most w times the optimum when the base heuristic is admissible.
- Heuristic cost matters: a heuristic that is expensive to compute can eat the savings from settling fewer nodes. Straight-line distance is a few arithmetic operations; a landmark lookup is a few memory reads.
- Weights that change with time of day need an admissible heuristic valid at every time: use the minimum possible travel time, not the current one.
- Negative edge weights break both algorithms; travel times are never negative, but penalties or rewards added to weights can make them so.
Unlock Full Question Bank
Get access to all 24 Marketplace, Dispatch, and Logistics System Design interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.