Design a Fair, Real-Time Pricing Engine for a Ride Platform
System DesignModel answerLast updated
Design the components, data flows, and core pricing logic for a ride platform that handles surge, carpooling, fairness constraints, and live experimentation at scale.
The Problem
You're designing the pricing engine for a large ride-hailing platform. The system must compute upfront prices in real time, support both solo and shared rides, stay fair to riders across different neighborhoods, and give the business a lever for running controlled pricing experiments.
Functional requirements
- Accept a ride request (origin, destination, product type, pool opt-in) and return several route options — each with a price and an itemized breakdown.
- Price each route using at minimum: distance, trip duration, supply/demand conditions, pickup wait time, and driver incentives.
- For pooled rides, calculate each rider's share based on which segments they actually share and any detour added to their trip.
- Enforce hard fairness rules: cap how high surge can go, prevent price discrimination by rider identity, surface transparent breakdowns, and keep pricing equitable across neighborhoods.
- Support A/B testing of pricing parameters with automatic rollback if safety metrics are violated.
- Reflect changes in driver availability and demand in near real time.
Non-functional requirements
- ~20 million rides per day; quoting runs roughly 10× bookings, so you need to handle ~20k quote requests per second at peak with 3 route options each.
- Driver location updates arrive at ~250k events/second.
- Quote API p99 latency under 300 ms end-to-end; the pricing function itself should run in under 10 ms.
- Prices are locked for 2–5 minutes after a quote is issued.
- Every computed price must be reproducible for auditing.
What's expected
Walk through your high-level architecture (components, data flows, storage choices), then write pseudocode or working code for the core price calculation function — including how pooling and surge feed into it. Call out trade-offs, constraints you're assuming, and how you'd validate that the fairness rules are actually working.
Hints
Hint 1
Start by pinning down the numbers: 20k quotes/s means ~60k price computations/s. That rules out anything slow in the hot path — the pricing function itself needs to be stateless and read only from a pre-warmed local cache. What does that imply about how you feed it surge data?
Hint 2
Surge needs smoothing in two dimensions: time (to avoid oscillations) and space (to avoid jarring price cliffs at cell boundaries). H3 hexagons and neighbor blending are a natural fit. Think about what happens when the surge feed goes stale — what's the safe default?
Hint 3
Pool pricing has a bootstrapping problem: at quote time you don't know who your co-riders will be. Model occupancy as an expected value per segment, quote that upfront, and decide what happens when no match materializes. Also consider: is proportional cost splitting the right model, or is there a fairer one?
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. Scope and Scale
Before drawing any boxes, anchor the design with numbers.
Traffic math: 20M rides/day ≈ 230 rides/s average, ~2k/s at peak. Quoting runs about 10× bookings, so ~20k quote requests/s. With 3 route options per quote, that is ~60k individual price computations/s.
Driver telemetry: 1M online drivers pinging every 4 seconds = ~250k location events/s.
Key constraints derived from this:
- The pricing function must be stateless and read from memory — no synchronous DB calls in the hot path.
- Surge state must be pre-computed and pushed to a low-latency cache (Redis), not pulled per request.
- Quotes must store their input snapshot so the booking honors the original price even if surge moves.
Assumptions worth stating: upfront (not metered) pricing; prices are a function of the trip and market state only, never of rider identity; pricing rules are per-city and versioned.
2. API Contract
POST /v1/quotes
Body: { rider_id, origin, destination, product, pool_opt_in, seats }
Response: {
quote_id, expires_at,
options: [{
option_id, route_id, polyline,
distance_m, duration_s, pickup_eta_s,
price_cents, currency,
breakdown: { base, distance, time, surge, wait_adj, pool_discount, fees },
max_detour_s? // only present for pool options
}]
}
POST /v1/rides { quote_id, option_id } → locks price, starts dispatch
GET /v1/quotes/{id}/explain → human-readable breakdown for transparency
Exposing /explain is not cosmetic — it is how you satisfy the transparency fairness requirement and how your support team debugs complaints.
3. Architecture Overview
Rider app → API GW → Quote Service ──► Routing Service (k routes + ETAs)
│ ──► Pool Matcher (candidate co-riders, detour estimate)
▼
Pricing Service (stateless, in-process config)
│ reads surge
▼
Surge Cache (Redis) ◄── Surge Calculator ◄── Flink ◄── Kafka
(driver pings, new requests)
│
Quote Store (DynamoDB, TTL) + Audit Log (Kafka → S3)
↓
Fairness & experiment analytics
Real-time surge pipeline: Driver pings and open ride requests flow into Kafka. A Flink job aggregates idle drivers and unmatched requests per H3 cell (resolution 8, ~0.7 km²) over 1-minute sliding windows. The Surge Calculator smooths those ratios and writes multipliers to Redis. The Pricing Service reads the relevant cell on each request in O(1).
Staleness rule: if a cell's Redis entry is older than 2 minutes, decay the multiplier toward 1.0. This fails safe for riders — stale data means you default to no surge rather than artificially high surge.
4. Core Price Calculation
from dataclasses import dataclass, field
@dataclass
class Segment:
distance_km: float
duration_min: float
expected_occupants: float # ≥ 1.0; probabilistic at quote time
@dataclass
class PriceInput:
distance_km: float
duration_min: float
surge: float # smoothed cell multiplier, already clamped
pickup_eta_min: float
incentive_pass_through: float = 0.0
pool_segments: list = field(default_factory=list) # empty → solo
detour_min: float = 0.0
@dataclass
class Config:
base: float = 2.50
per_km: float = 1.10
per_min: float = 0.30
min_fare: float = 6.00
surge_cap: float = 2.5
long_wait_threshold_min: float = 5.0
long_wait_discount_rate: float = 0.02 # per minute above threshold
incentive_pass_through_cap: float = 0.10
min_pool_discount: float = 0.15
pool_floor_ratio: float = 0.50 # pool price ≥ solo × floor_ratio
def compute_price(inp: PriceInput, cfg: Config) -> dict:
# --- 1. Base trip cost ---
trip_cost = cfg.base + inp.distance_km * cfg.per_km + inp.duration_min * cfg.per_min
# --- 2. Apply surge (already smoothed and spatially blended upstream) ---
effective_surge = min(inp.surge + inp.incentive_pass_through, cfg.surge_cap)
surged_cost = trip_cost * effective_surge
surge_adj = surged_cost - trip_cost
# --- 3. Long pickup wait discount ---
excess_wait = max(0.0, inp.pickup_eta_min - cfg.long_wait_threshold_min)
wait_discount = -excess_wait * cfg.long_wait_discount_rate * trip_cost
# --- 4. Pool adjustment ---
pool_discount = 0.0
if inp.pool_segments:
# Rider pays their proportional share of each segment
shared_cost = sum(
(cfg.per_km * s.distance_km + cfg.per_min * s.duration_min) / s.expected_occupants
for s in inp.pool_segments
)
# Credit back detour time
detour_credit = inp.detour_min * cfg.per_min
pool_price_raw = cfg.base + shared_cost - detour_credit
# Guarantee pool is cheaper than solo by at least min_pool_discount
solo_price = max(surged_cost + wait_discount, cfg.min_fare)
pool_ceiling = solo_price * (1.0 - cfg.min_pool_discount)
pool_floor = solo_price * cfg.pool_floor_ratio
final_pool = max(min(pool_price_raw, pool_ceiling), pool_floor)
pool_discount = final_pool - surged_cost # negative value = savings
total = max(final_pool, cfg.min_fare)
else:
total = max(surged_cost + wait_discount, cfg.min_fare)
# --- 5. Platform fee (fixed percentage, shown separately) ---
fee = round(total * 0.05, 2)
total_with_fee = total + fee
return {
"price_cents": round(total_with_fee * 100),
"breakdown": {
"base": cfg.base,
"distance": inp.distance_km * cfg.per_km,
"time": inp.duration_min * cfg.per_min,
"surge_adj": round(surge_adj, 2),
"wait_adj": round(wait_discount, 2),
"pool_discount": round(pool_discount, 2),
"fee": fee,
}
}
Complexity: O(S) where S is the number of pool segments (typically 2–4). In practice this is O(1) per computation. At 60k/s this is comfortably under 1 ms on a single core.
5. Surge Smoothing
Raw ratio r = demand / max(supply, ε) is noisy. Apply three layers:
- Temporal EWMA: blend each new reading with the previous multiplier to dampen oscillations.
- Spatial blending: average a cell's multiplier with its H3 neighbors. This prevents a rider being quoted $12 on one block and $6 on the next.
- Rate limiting: cap change at ±0.2 per minute so rapid swings don't shock riders.
- Hard cap: clamp to
[1.0, surge_cap]. Lower the cap during declared emergencies.
Driver incentive bonuses (quests, area boosts) may pass through to the rider price at most incentive_pass_through_cap (e.g., 10%). The rest is platform-funded. This prevents incentives from masquerading as invisible surge.
6. Pool Pricing Trade-offs
At quote time you do not yet have confirmed co-riders. Options:
- Expected-value occupancy (chosen here): estimate occupancy probabilistically, quote that price, and let the platform absorb variance if no match happens. Simpler, more explainable.
- Shapley value allocation: distributes the combined cost "fairly" across all co-riders based on marginal contributions. More theoretically correct, but hard to explain to a rider on a phone screen and requires knowing all riders simultaneously.
For a consumer product, the proportional split with a guaranteed max detour is the better default. Shapley is worth mentioning as a future fairness improvement.
7. Fairness Guardrails
These run as the final layer and are not overridable by experiments:
- Surge cap — hard ceiling, no exceptions.
- No rider-level features — price must not depend on device type, trip history, battery level, or any demographic signal.
- Neighborhood equity — monitor price-per-km variance by census tract. Spatial blending helps, but run a periodic offline check. Flag areas where the disparity exceeds a threshold.
- Driver earnings floor — minimum payout per engaged minute regardless of pool complexity.
- Transparent breakdown — every quote exposes the full breakdown;
/explainmakes it human-readable.
8. Experimentation
Rider-level A/B tests are biased in a two-sided marketplace because both arms compete for the same driver supply. Use switchback experiments instead: assign treatment by (city region, time block) and alternate assignments over time. This keeps supply/demand balanced.
Experiments may only modify whitelisted parameters within schema-validated bounds. Guardrail metrics are monitored automatically — a breach in cancellation rate, driver earnings per hour, or neighborhood price disparity triggers an automatic rollback. This is how you run fast without exposing riders to runaway pricing.
Common Mistakes to Avoid
- Calling the surge cache or config store synchronously per price computation — it won't meet the 10 ms budget at scale.
- Treating pool pricing as simply "solo × 0.8" — you lose the fairness properties and the ability to pass savings from genuine sharing back to riders.
- Running rider-level A/B tests without accounting for cross-arm interference — you'll measure noise, not lift.
- Forgetting to snapshot the config version in the quote record — without it, you cannot reproduce a price for an audit or a dispute.