Design a Real-Time Ride-Matching Platform and a Price-Alert Service
System DesignModel answerLast updated
Architect two scalable backend platforms: a low-latency, geo-partitioned ride-hailing system and an asynchronous, queue-decoupled price tracking and notification pipeline.
This system design problem requires you to architect two distinct, large-scale distributed systems. Treat each part as an independent design while applying consistent architectural principles around latency, availability, fault tolerance, and data integrity.
Core Operating Assumptions & Constraints
- Scale: Multi-million daily active users. Systems must scale horizontally by expanding compute and storage tiers rather than relying on vertical capacity limits.
- Geographic Scope: Multi-region, global deployment footprint with regional user traffic patterns.
- Client Topology: Mobile clients interacting via short-lived HTTPS REST/gRPC for transactional commands, paired with persistent multiplexed channels (WebSocket, gRPC streaming, or MQTT) when foregrounded for real-time streaming.
- Latency SLAs:
- Part 1 (Ride Matching): $p95 < 300,\text{ms}$ total response time to surface candidate drivers and assign requests.
- Part 2 (Price Tracking): Alert delivery within 3–5 minutes of a verified price drop.
- Availability Target: $\ge 99.99%$ availability for real-time dispatch and price monitoring components. Graceful degradation mechanisms must absorb localized regional or network failures.
- Consistency Models:
- Financial & Booking State: Strict serializability / strong ACID guarantees (trips, ledger transfers, user balances).
- Spatial & Monitoring Telemetry: Eventual consistency (driver positions, ETAs, aggregate surge metrics, price snapshots).
Part 1: Real-Time Ride-Hailing Platform
Design a distributed backend connecting riders and service drivers in real time.
Core Functional Capabilities
- Ingest driver location updates every 2–5 seconds with minimal overhead.
- Index current driver positions to serve spatial radius queries with sub-300ms $p95$ latency.
- Manage the end-to-end ride lifecycle: request, driver matching/offering, acceptance, trip start, trip completion, and cancellation.
- Calculate localized surge pricing based on real-time spatial supply/demand imbalance.
- Guarantee idempotent transaction processing to eliminate double-assignments or duplicate billing.
Key Architectural Requirements
- Outline the high-level system architecture, service boundaries, and data stores chosen for specific read/write patterns.
- Detail the geospatial indexing scheme (e.g., Geohash vs. Google S2) and explain the nearest-driver query flow (candidate retrieval, filtering, ranking).
- Explain the locking/reservation strategy used during match acceptance to prevent race conditions across concurrent dispatch workers.
Part 2: Product Price Tracking and Alert System
Design an asynchronous, high-throughput backend that monitors external product prices and fires notifications when trigger criteria are satisfied.
Core Functional Capabilities
- Allow users to register monitored items via URL or standardized Product Identifiers.
- Support configurable condition rules (e.g., price drop below fixed value $X$, or percentage drop $\ge Y%$ relative to a rolling baseline).
- Ingest price telemetry via scheduled Web crawling and external partner API feeds.
- Store durable, append-only price history for analytical reporting and baseline calculations.
- Send multi-channel notifications (Push, SMS, Email) with idempotency guarantees.
Key Architectural Requirements
- Provide a end-to-end architecture diagram or flow detailing ingestion, history persistence, rule evaluation, and notification delivery.
- Explain how the ingestion layer respects target site rate limits (politeness) while prioritizing high-demand items.
- Detail the data modeling for rule evaluation at scale (millions of rules against thousands of price updates per minute).
- Explain how notification duplication and alert fatigue are avoided during transient price volatility.
Hints
Hint 1
Break data pipelines into clear read, write, and background execution stages; never use transactional RDBMS instances for high-frequency location or price telemetry streams.
Hint 2
For spatial searching, use hierarchical cell indexes like Google S2 or H3 over standard 2D R-Trees to allow simple key-value lookups and ring expansions across spatial boundaries.
Hint 3
Prevent race conditions during driver assignment by employing atomic lock-and-set operations (e.g., Redis Lua scripts or conditional SQL updates) with short-lived TTL reservations.
Hint 4
Decouple price fetching from rule evaluation using event streams (e.g., Kafka); group rule evaluations by product ID so a single price update triggers a single batch cache lookup.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. Architectural Strategy & Consistency Matrix
Building high-throughput real-time systems requires matching data consistency models to domain requirements. Both systems combine strongly-consistent transaction layers with highly available, eventually consistent event streams.
| Subsystem Concern | Data Store Type | Primary Model | Rationale |
|---|---|---|---|
| Ride Lifecycle & Billing | Relational DB (PostgreSQL / Spanner) | Strong ACID | Financial states, trip records, and payment settlements demand serializability. |
| Driver Location Ingest | In-Memory Geo Store (Redis / MemoryDB) | Eventual Consistency | Transient telemetry. Dropping a single update does not corrupt state. |
| Price History Logging | Time-Series DB (TimescaleDB / Cassandra) | Append-Only / Eventual | High write volumes; reads consist of range scans for baseline analysis. |
| Alert Rules Registry | Key-Value / Document (DynamoDB / MongoDB) | Read-Heavy / Strong Read | Low write-volume per user; ultra-fast lookup by product_id. |
Part 1: Real-Time Ride-Hailing Platform
High-Level System Architecture
+-----------------------+
| Mobile Clients / Gateway
+-----------+-----------+
|
+---------------+---------------+
| (HTTPS / REST)| (gRPC Stream / WSS)
v v
+-----------------+ +----------------------+
| Trip & Booking | | Real-Time Location |
| Management Svc | | Ingestion Gateway |
+--------+--------+ +----------+-----------+
| |
| v
| +-------------------+
| | In-Memory Spatial |
| | Cache (Redis/S2) |
| +---------+---------+
v |
+-----------------+ |
| Dispatch engine | <-------------+
+--------+--------+
|
v
+-----------------+
| PostgreSQL/ACID |
+-----------------+
Core Components & End-to-End Workflow
- Location Ingestion Gateway: Receives gRPC/MQTT streams of driver lat/long pings every 3 seconds. Updates the current location in an in-memory spatial cache and publishes events to an Apache Kafka cluster (
driver-telemetry). - Geospatial Indexing Engine: Organizes geography using Google S2 (Level 13 cells $\approx 0.5,\text{km}^2$ or Level 14 cells $\approx 0.1,\text{km}^2$) or Uber H3.
- Driver coordinates are mapped to an S2 Cell ID.
- In-memory state uses a spatial key structure in Redis:
s2_cell:<cell_id> -> SET(driver_ids). - A reverse map
driver:<driver_id> -> {lat, lon, status, last_ping_ts, s2_cell}ensures updates remove drivers from old cells when crossing boundaries.
- Dispatch & Matching Service:
- Step 1 (Candidate Retrieval): Given a pickup coordinate, compute its S2 Cell ID. Query the cell and its 8 immediate surrounding cells (k-ring 1). If candidate counts fall below threshold $N$, expand to k-ring 2.
- Step 2 (Filtering): Filter out inactive drivers, drivers with pending offers, or drivers lacking required vehicle traits.
- Step 3 (Ranking): Compute true road-network Routing ETAs using a graph-based routing service for top candidate drivers.
- Race-Free Match Assignment (Distributed Lock & State Machine):
- To prevent two concurrent dispatch jobs from matching the same driver, the system executes an atomic CAS (Compare-And-Swap) operation in Redis via Lua Scripting:
-- KEYS[1]: driver_status_key, ARGV[1]: expected_state ("IDLE"), ARGV[2]: new_state ("OFFERED"), ARGV[3]: offer_ttl (15s)
if redis.call("GET", KEYS[1]) == ARGV[1] then
redis.call("SET", KEYS[1], ARGV[2], "EX", ARGV[3])
return 1
else
return 0
end
- If lock acquisition succeeds, a match offer is dispatched to the driver via persistent WebSocket/gRPC streams.
- If the driver accepts, the
Trip Management Servicemoves the transaction to PostgreSQL inside a serializable transaction block (UPDATE trips SET status='ACCEPTED', driver_id=... WHERE id=... AND status='SEARCHING'). - If the 15-second TTL expires without acceptance, the Redis lock reverts to
IDLE, and dispatch retries with the next best candidate.
Dynamic Surge Pricing Architecture
- Aggregation: Flume/Spark Streaming workers evaluate driver count (supply) vs unfulfilled trip requests (demand) per S2 Cell (Level 12) over 1-minute rolling windows.
- Multiplier Calculation: $$\text{Surge Multiplier} = \max\left(1.0, \alpha \times \frac{\text{Demand}}{\text{Supply + } \epsilon}\right)$$
- Smoothing: Spatial and temporal smoothing functions prevent sudden surge cliffs between adjacent cells or rapid oscillating spikes.
Part 2: Product Price Tracking and Alert System
High-Level System Architecture
+-------------------+ +------------------------+
| Web Crawlers / | | Partner APIs / Feeds |
| Ingestion Workers | +-----------+------------+
+---------+---------+ |
| |
+--------------+---------------+
|
v
+------------------------+
| Kafka: `price-updates` |
+------------+-----------+
|
+---------------+---------------+
v v
+------------------------+ +------------------------+
| History Log Engine | | Rule Evaluation Engine |
| (TimescaleDB / Cassandra) | | (Flink / Go Workers) |
+------------------------+ +-----------+------------+
|
v
+------------------------+
| Redis Rule Cache |
+-----------+------------+
|
v
+------------------------+
| Kafka: `alert-dispatch` |
+-----------+------------+
|
v
+------------------------+
| Notification Gateways |
| (Push / SMS / Email) |
+------------------------+
Core Components & End-to-End Workflow
- Polite Ingestion Pipeline:
- Queue Distribution: Priority-based scheduling queue (e.g., RabbitMQ or Kafka). Popular items are refreshed frequently (every 15–30 mins); low-demand items are refreshed less frequently (6–12 hours).
- Rate Limiter / Politeness: Token-bucket algorithm partitioned by
domain_name. Crawlers execute requests under standard concurrency limits to adhere torobots.txtdynamic guidelines and prevent HTTP 429 response rate-limits.
- Price Snapshot Stream:
- Output normalized payload:
{ product_id, timestamp, price_cents, currency, availability_status }. - Published to Kafka topic
price-updatessharded byproduct_id.
- Output normalized payload:
- Storage Tier Architecture:
- History Store: TimescaleDB / Cassandra storing append-only rows. Partitioned by
(product_id, time_bucket). Optimized for continuous analytical historical scans. - Rule Store: DynamoDB storing rules defined as:
{ rule_id, user_id, product_id, rule_type: ["BELOW_ABSOLUTE", "PERCENT_DROP"], target_value, baseline_price, status: "ACTIVE" }
- History Store: TimescaleDB / Cassandra storing append-only rows. Partitioned by
- Scalable Rule Evaluation Engine:
- High-performance Go or Apache Flink workers read from
price-updates. - Workers query an in-memory Redis cluster populated with rules indexed by
product_id(product_rules:<product_id> -> SET(rule_ids)). - Evaluation Rules logic:
- Absolute Threshold: Fire alert if $\text{Price}_{\text{new}} \le \text{Threshold}$.
- Percentage Drop: Compare $\text{Price}{\text{new}}$ against $\text{Baseline Price}$ recorded when the user established the alert. Fire if: $$\frac{\text{Baseline} - \text{Price}{\text{new}}}{\text{Baseline}} \ge \text{Target Discount Percentage}$$
- High-performance Go or Apache Flink workers read from
Notification Dispatch, Idempotency, and Alert Suppression
- Deduplication Strategy: To prevent repeated notifications during transient price updates, write an event lock key in Redis prior to emitting:
alert_lock:<rule_id>:<price_cents>with a TTL of 24 hours. - Delivery Workers: Read from
alert-dispatchKafka topic and deliver via vendor APIs (APNs, Firebase, Twilio, SendGrid). - Failure Handling:
- Retry transient downstream failures with exponential backoff and jitter.
- Move unsendable payloads to a Dead-Letter Queue (DLQ) after 5 failed delivery attempts for investigation.
Key Trade-Offs & Failure Scenarios
1. Geohash vs. Google S2 / H3 Indexing
- Geohash: Simple base32 strings, but suffers from edge boundary issues where neighboring physical locations cross different string prefix prefixes.
- Google S2 / H3: Mathematical sphere mapping that guarantees consistent cell area sizes and simple geometric ring transformations without boundary anomalies. Selected: S2/H3.
2. Network Partition in Ride Matching (Split-Brain Mitigation)
- In the event of a network partition disconnecting an isolated driver ingestion node from the central database, local Redis caches might show stale driver locations.
- Mitigation: Driver location keys have short TTLs (10 seconds). If pings drop, keys automatically expire out of spatial availability sets, preventing the dispatch system from offering rides to non-responsive or disconnected drivers.
3. Crawling Throttling & Anti-Bot Mitigations
- Targeted merchant domains may block raw crawler IP blocks.
- Mitigation: Fall back to proxy pools with automated IP rotation and utilize structured commercial API partnerships where available. Ingestion tasks dynamically fall back to lower query rates when receiving backpressure signals (e.g., HTTP 429 or 503 response codes).