Real-Time Ranking Service for Delivery Couriers
System DesignModel answerLast updated
Design a high-throughput system that ingests courier ratings and serves a low-latency top-K leaderboard under eventual consistency.
Context
A logistics platform tracks courier performance through post-delivery ratings. You have been asked to design the backend service that powers a courier rankings page, updated in near real-time.
What You Need to Support
Ingestion
record_rating(courier_id, rating) — accepts a numerical score (1 through 5) after a delivery is completed.
Query
top_couriers(K) — returns the K highest-ranked couriers by average rating, in descending order.
Scale and Quality Targets
- Volume: 1 million active couriers; up to 10,000 ratings per second at peak.
- Freshness: The leaderboard does not need to reflect every rating the instant it arrives. An update delay of a few seconds is acceptable.
- Availability: Read queries must stay up even if parts of the write pipeline are degraded.
What to Cover in Your Answer
- API design — endpoints, request/response shapes, and any relevant HTTP semantics.
- Storage choices — compare relational databases, NoSQL stores, and in-memory caches for different parts of the system; justify your picks.
- Data flow — walk through how a rating moves from ingestion all the way to influencing the leaderboard.
- Hot-key and skew handling — some couriers receive far more ratings than others; explain how your design holds up.
Example
record_rating("courier_42", 5)
record_rating("courier_7", 4)
record_rating("courier_7", 5)
top_couriers(2)
→ [
{ courier_id: "courier_7", avg_rating: 4.5, review_count: 2 },
{ courier_id: "courier_42", avg_rating: 5.0, review_count: 1 }
]
(Ranking order assumes the composite scoring rule you define.)
Hints
Hint 1
Start with a back-of-envelope calculation. How large is 1 million courier aggregates in memory? The answer changes how aggressively you need to shard the leaderboard store.
Hint 2
Think about what you actually store per courier. If you keep a running sum and count rather than a pre-computed average, incremental updates are exact and O(1). What does that mean for the schema?
Hint 3
The Redis sorted set is not your source of truth — it is a derived view you can always rebuild. How does that framing change your availability and consistency strategy?
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Clarify Before Designing
A few minutes of scoping prevents hours of rework.
- Ranking metric: lifetime average, or a recent window like the last 60 days? A lifetime average is simpler; a windowed average is fairer but requires background re-scoring as old ratings expire.
- K range: top 10 to top 100 is typical. Cap at around 1,000 to keep reads cheap.
- Idempotency key: can only the completing customer rate, and only once per delivery? If so, a
delivery_idbecomes a natural deduplication key. - Scope: global ranking, or broken out by city or region? This is a common follow-up, so design with it in mind.
Back-of-envelope
| Quantity | Estimate |
|---|---|
| Peak writes | 10,000 ratings/s |
| Raw rating record | ~100 B → ~50 GB/day |
| Per-courier aggregate | sum + count + metadata ≈ 50 B → 50 MB for 1M couriers |
| Redis sorted set (1M members) | ~100–150 B/member → ~150 MB |
| Read QPS | 1,000–10,000 (read-heavy but small K) |
The key insight: the entire leaderboard fits in a single Redis instance with memory to spare. The hard problems are write throughput, idempotency, and read availability — not raw storage.
2. API Design
POST /v1/couriers/{courier_id}/ratings
Body: { delivery_id, customer_id, score: 1..5, submitted_at }
→ 202 Accepted (async; idempotent on delivery_id)
GET /v1/leaderboard?k=10[®ion_id=nyc]
→ {
as_of: "2024-05-01T12:00:01Z",
couriers: [
{ courier_id, rank, avg_rating, review_count },
...
]
}
Return 202 because aggregation is asynchronous. Include as_of in the response so clients can display a "last updated" timestamp and reason about staleness.
3. Data Model
ratings table — append-only source of truth.
delivery_id (PK),courier_id,customer_id,score,submitted_at- Partitioned by
courier_idin Cassandra or DynamoDB. A unique constraint ondelivery_idenforces one rating per delivery.
courier_rating_agg table — per-courier running totals.
courier_id (PK),rating_sum,rating_count,updated_at,last_kafka_offset- Store sum and count, never a pre-computed average. This keeps updates incremental and exact, and lets you recompute the average at query time without losing precision.
Redis sorted set lb:global — the serving layer.
- Member:
courier_id, Score: composite ranking score (see §5). ZADDis O(log N);ZREVRANGE 0 K-1is O(log N + K). With 1M members at 150 MB, one instance handles this comfortably.- Treat it as a rebuildable derived view, not the source of truth.
Comparison of storage options
| Option | Write throughput | Global ordering | Notes |
|---|---|---|---|
| Relational only | Degrades under 10k writes/s; B-tree contention | ORDER BY avg DESC LIMIT K works at small scale | Lock contention is the bottleneck |
| NoSQL (Cassandra/Dynamo) | Excellent for append-heavy loads | No native global sort | Good for raw ratings and per-courier aggregates |
| Redis sorted set | O(log N) per ZADD | Native, O(log N + K) reads | In-memory only; needs a durable backing store |
4. Data Flow
Customer app
→ API Gateway
→ Rating Ingestion Service
→ validate (delivery completed, customer matches, score 1–5)
→ write to Kafka topic "ratings" (partitioned by courier_id)
→ return 202
Kafka
→ Persister consumer: upserts into ratings table (idempotent on delivery_id)
→ Aggregator (Flink or Kafka Streams):
per partition, maintains in-memory map: courier_id → (Δsum, Δcount)
flushes every 1–2 s:
1. UPDATE courier_rating_agg: sum += Δsum, count += Δcount
(commit Kafka offset in the same transaction)
2. Pipelined ZADD to Redis lb:global
Leaderboard Service
→ primary Redis (+ read replicas)
→ local in-process snapshot of top-1000, refreshed every ~1 s
→ most GET /leaderboard calls never touch Redis
Why buffer writes: 10,000 ratings/second collapse to at most one update per distinct courier per flush window — typically far fewer. Batched ZADDs and bulk DB writes cut round-trips by roughly 100x.
Exactly-once semantics: commit the Kafka offset atomically with the aggregate update (Flink checkpoints, or store last_kafka_offset in the same DB transaction). Without this, a consumer restart double-counts. The delivery_id unique constraint protects the raw log independently.
5. Scoring, Ties, and Cold Start
A raw average puts many couriers at 5.0 after a single perfect rating. Use a Bayesian average to pull new couriers toward the population mean:
bayes_avg = (rating_sum + m * C) / (rating_count + m)
where C is the global mean rating and m is a confidence weight (e.g., 10). Break ties by volume:
score = round(bayes_avg, 4) * 1e6 + min(rating_count, 999999)
This ensures a courier with 1,000 ratings at 4.8 ranks above one with 3 ratings at 4.8.
6. Handling Skew and Hot Keys
Write skew (popular courier, or a replay bug flooding ratings):
- Pre-aggregation absorbs N ratings into one update per flush window.
- Rate-limit at ingestion: one rating per customer per delivery.
- For extreme cases, use two-stage aggregation: partial sums per Kafka partition, then a merge consumer.
Partition skew in Kafka: 64–128 partitions, hashed on courier_id. Monitor consumer lag per partition.
Read hot key: a single lb:global ZSET is the real bottleneck, not individual couriers. Solve it with the local in-process top-K snapshot and Redis read replicas, not by splitting the set across shards.
7. Read Availability and Rebuilding
- During normal operation, the Leaderboard Service serves reads from a local cache refreshed every ~1 second.
- Redis has replicas with Sentinel or Cluster failover.
- If Redis is lost, rebuild
lb:globalby scanningcourier_rating_agg— 1M rows, typically done in seconds to low minutes. - Serve the stale local snapshot during the rebuild. Under the agreed eventual-consistency SLA, this is acceptable.
Common Mistakes to Avoid
- Storing a pre-computed average instead of sum + count — this makes it impossible to update correctly without reading the old value first.
- Making Redis the source of truth — it is in-memory and can be lost; always back it with a durable store you can replay from.
- Skipping idempotency — at 10k writes/s, retries and consumer restarts are not edge cases; they are routine.
- Prematurely sharding Redis — the math shows 150 MB fits in one instance. Over-engineering here adds operational complexity for no gain.
Follow-Up: Per-Region Leaderboards
Add one ZSET per region (lb:region:{region_id}). The aggregator looks up the courier's home region from a cached profile store and runs ZADD on both the regional and global keys in the same pipeline. Redis Cluster distributes region keys across shards naturally. A courier who operates in multiple regions needs a row in each relevant regional aggregate.