Questions 61–80 of 100 · 0 of 20 on this page marked learned
61.system-design-0061Hardsenior
Design an ad click aggregation system that counts 2 billion clicks per day per ad per minute, for billing and dashboards, with exactly-once results.
Click events go into a partitioned log such as Kafka; a stream processor such as Flink groups them by ad ID into one-minute event-time windows, using watermarks for late events, and writes aggregates to an OLAP store. Exactly-once comes from deduplicating click IDs plus transactional or idempotent writes of window results. A daily batch job recomputes from raw events to reconcile billing.
Full answer
Requirements
Functional:
Count clicks per ad per minute (and roll up to hour and day).
Query: clicks for ad X between two times; top 100 ads in the last hour.
Filter invalid clicks (bots, duplicates).
Non-functional:
Counts are correct for billing: no double counting, no loss.
Dashboards update within about a minute.
Handle bursts and late events (mobile clients send clicks minutes late).
Capacity estimates
Assumptions: 2B clicks per day, peak factor 3, 200 bytes per raw event, 1M active ads.
Clicks: 2B / 86,400 = about 23,000 per second; about 69,000 per second at peak.
Raw data: 2B x 200 bytes = 400 GB per day, kept for audit and reprocessing.
Aggregates: at most 1M rows per minute (one per active ad that got a click), usually far fewer.
API
POST /v1/clicks (from ad servers) {"click_id", "ad_id", "user_hash", "ts", "ip", "ua"}
GET /v1/ads/{ad_id}/clicks?from=2026-12-01T10:00Z&to=2026-12-01T11:00Z&granularity=minute
GET /v1/ads/top?window=1h&limit=100
Data model
Raw events: Kafka topic partitioned by ad_id, then archived to object storage (Parquet, partitioned by date and hour).
Aggregates table: (ad_id, minute) primary key, clicks, valid_clicks, updated_at, in an OLAP store such as ClickHouse, Druid or Pinot.
Dedup state: recent click_ids within the stream processor's keyed state (with a TTL of a few hours).
High-level design
mermaid
flowchart LR
AS[Ad servers] --> K[(Kafka: clicks)]
K --> F[Stream processor]
F --> AGG[(OLAP aggregates)]
K --> ARC[(Raw archive)]
ARC --> B[Daily batch recompute]
B --> REC[Reconciliation]
AGG --> REC
AGG --> Q[Query service]
Q --> D[Dashboards and billing]
Stream processing details
Key by ad_id so all clicks of one ad go to one task.
Event-time windows of one minute, using the click's own timestamp, not arrival time.
Watermarks declare "events older than T are complete", typically T = now minus 2 minutes. A window is emitted when the watermark passes its end. Events later than that update the window again (allowed lateness) or go to a side output for the batch job.
Deduplicate click_id in keyed state before counting, since ad servers may retry.
Exactly-once output: the processor checkpoints its state and Kafka offsets together. Window results are written with an upsert keyed by (ad_id, minute), so replaying after a failure overwrites the same row instead of adding twice.
Hot ads (a viral campaign) can be split with a two-stage aggregation: count per (ad_id, random 0 to 9) first, then sum the ten partial counts.
Bottlenecks and trade-offs
Lateness versus freshness. A longer watermark delay catches more late events but delays dashboards.
Lambda-style reconciliation. Streaming gives fast numbers; the daily batch over raw events is the billing truth. Differences above a threshold raise alerts.
Invalid click filtering (bots, click farms) needs features over time; run a quick rule filter in the stream and a deeper model in batch, adjusting bills later.
Kafka partitions set the parallelism ceiling; choose enough (for example 256) for growth.
OLAP store pre-aggregates minute rows into hours and days to keep queries fast.
By level
Fresher: Describe clicks flowing through a queue into a job that counts them per minute and stores the results. A fresher should know why duplicates must be removed for billing.
Mid: Design event-time windows with watermarks, deduplication and idempotent writes, and do the capacity math. Add an OLAP store for queries.
Senior: Discuss lateness trade-offs, two-stage aggregation for hot ads, reconciliation with batch, invalid traffic and replay after bugs. Expect a precise account of how exactly-once is achieved end to end.
Key points
Partitioned log in, stream processor out
Event-time windows with watermarks for late clicks
Deduplicate click IDs and upsert window results for exactly-once
Two-stage aggregation for hot ads
Batch recompute from raw events reconciles billing
Common mistakes
Counting by arrival time instead of event time
Incrementing counters in a database on every click
Ignoring retries that duplicate click events
Having no raw archive to recompute from
Follow-ups
How would you handle a click that arrives two hours late?
How would you compute unique users per ad?
How do you recover if the stream job has a bug for a day?
Tips
Explain event time and watermarks with a timeline
Show how upserts make replays safe
Mention reconciliation for billing
Evaluation rubric
Correct pipeline design
Correct windowing and late-event handling
Exactly-once reasoning
Hot keys and reconciliation covered
62.system-design-0062Mediummid
Design a metrics and monitoring system like Prometheus or Datadog that collects metrics from 100,000 hosts and alerts on problems within a minute.
Agents on each host collect metrics and push them (or are scraped) into an ingestion tier that writes to a time-series database partitioned by series. Samples are compressed with delta-of-delta timestamps and XOR-encoded values to about 1.4 bytes each, which turns 13.8 TB per day of raw samples into about 1.2 TB. Downsampling keeps old data cheap, and a separate alerting service evaluates rules on recent data every 30 seconds.
Full answer
Requirements
Functional:
Collect counters, gauges and histograms with labels (service, host, region).
Query and graph any metric over time; aggregate across labels.
Alert rules (for example "error rate above 2% for 5 minutes") that notify on-call staff.
Non-functional:
Alerts within about a minute of a problem.
Ingestion keeps working during incidents, when load spikes.
Recent data (two weeks) at full resolution; a year at lower resolution.
Capacity estimates
Assumptions: 100,000 hosts, 1,000 active series per host, one sample every 10 seconds, 16 bytes per raw sample (8-byte timestamp, 8-byte value), about 1.37 bytes per sample after compression.
Active series: 100,000 x 1,000 = 100M.
Samples: 100M / 10 = 10M per second.
Raw volume: 10M x 16 bytes x 86,400 = about 13.8 TB per day.
Compressed: 10M x 1.37 x 86,400 = about 1.2 TB per day, about 17 TB for 14 days of full resolution.
API
POST /v1/write (batched, compressed) [{"series": "http_requests_total{service=api,code=500}", "samples": [[ts, value], ...]}]
GET /v1/query?expr=sum(rate(http_requests_total{code="500"}[5m])) by (service)&start=..&end=..&step=30s
POST /v1/alerts/rules {"expr": "...", "for": "5m", "severity": "page", "route": "team-payments"}
Data model
Series ID = hash of metric name plus sorted labels.
Inverted index: label value to list of series IDs, so service=api finds all matching series.
Chunks: per series, blocks of about 2 hours of compressed samples.
Downsampled tables: 5-minute and 1-hour averages, min, max and count.
High-level design
mermaid
flowchart LR
AG[Host agents] --> ING[Ingestion tier]
ING --> K[(Write-ahead buffer)]
K --> TS[(TSDB shards by series hash)]
TS --> DS[Downsampler]
DS --> COLD[(Object storage, downsampled)]
Q[Query service] --> TS
Q --> COLD
AL[Alert evaluator] --> Q
AL --> NT[Notifier: pager, chat, email]
UI[Dashboards] --> Q
Key techniques
Compression (Gorilla style). Timestamps arrive at regular intervals, so the delta of deltas is usually 0 and takes 1 bit. Values change slowly, so XOR with the previous value leaves mostly zero bits. Together this averages around 1.37 bytes per sample.
Sharding by series hash spreads writes; queries fan out to shards and merge.
Write-ahead buffer (Kafka or an internal log) protects against TSDB node loss and absorbs spikes.
Alerting runs rules every 30 seconds on in-memory recent data, with a for duration to avoid flapping, and routes and groups notifications so one outage creates one page, not 500.
Bottlenecks and trade-offs
Cardinality explosions. A label such as user_id or request_id creates millions of new series and can take down the system. Enforce per-tenant series limits and reject high-cardinality labels.
Push versus pull. Pull (scraping) makes target health visible and simple to control; push works better for short-lived jobs and across firewalls.
Monitoring must outlive what it monitors. Run the alerting path separately from the main system and have a "dead man's switch" alert that fires if no data arrives.
Downsampling loses spikes shorter than the step; keep max values in rollups.
By level
Fresher: Explain metrics as numbers over time with labels, collected by agents and shown on graphs. A fresher should describe a simple alert rule with a threshold and a duration.
Mid: Size ingestion and storage, explain compression and downsampling, and design the alert evaluator with routing. Mention the label index.
Senior: Discuss cardinality control, push versus pull, monitoring independence, histogram storage and multi-tenancy. Expect a plan for the dead man's switch.
Key points
About 100M series and 10M samples per second
Gorilla-style compression to about 1.4 bytes per sample
Shard by series hash with an inverted index on labels
Downsample old data and keep max values
Alerting runs separately with for-durations and grouping
Common mistakes
Allowing unbounded label cardinality
Storing each sample as a database row
Running alerting on the same cluster it monitors with no fallback
Downsampling with averages only and losing spikes
Follow-ups
How would you store histograms for latency percentiles?
How would you support multi-tenant limits?
How do you alert if the monitoring system itself is down?
Tips
Do the samples per second math first
Explain cardinality risk with a bad label example
Mention compression to justify storage
Evaluation rubric
Correct capacity math
Time-series storage and compression
Alerting design with noise control
Cardinality and reliability trade-offs
63.system-design-0063Mediummid
Design a distributed job scheduler that runs 100 million cron-style and one-off jobs per day at their scheduled time, even when scheduler machines fail.
Store job definitions durably and keep an index of next run times bucketed by minute. Scheduler workers each own a set of time-bucket partitions through leases, pick up due jobs, and push run requests to a queue that executor workers consume. Each run has a unique run ID so retries are idempotent. Delivery is at-least-once, the top of every minute is a hot spot, and jitter spreads the 1 million jobs that all say "every hour at :00".
Full answer
Requirements
Functional:
Create one-off jobs ("run at 2026-12-05 09:00 UTC") and recurring jobs (cron expressions).
Run each job on time, retry failures with backoff, and record run history.
Pause, update and delete jobs.
Non-functional:
Jobs start within a few seconds of their time.
A scheduler crash does not skip jobs; duplicates are possible but rare and detectable.
Scale to 100M runs per day.
Capacity estimates
Assumptions: 100M runs per day, 1M jobs scheduled for the start of the same minute at peak, 1 KB per job definition, 50M job definitions.
Average: 100M / 86,400 = about 1,160 runs per second.
Peak minute: if 1M jobs fire in one minute and are spread across it, that is about 16,700 per second; if they all fire in the first second, it is 1M per second, which is why spreading matters.
Definitions: 50M x 1 KB = 50 GB, which a sharded relational or key-value store holds easily.
flowchart LR
U[Clients] --> API[Job API]
API --> DB[(Jobs and due index)]
SCH[Scheduler workers with leases] --> DB
SCH --> Q[(Run queue)]
Q --> EX[Executor workers]
EX --> T[Targets: HTTP, functions, scripts]
EX --> RUNS[(Run history)]
CO[Coordination service] --> SCH
How a job fires
Each scheduler worker holds leases (in etcd or ZooKeeper) on a set of shards of the due index.
Every second it reads jobs in the current and previous minute bucket for its shards whose next_run_at has passed.
For each job, it inserts a run with run_id = hash(job_id, scheduled_time) (unique, so a second scheduler doing the same work fails the insert), enqueues the run, and moves next_run_at to the next cron time in one transaction.
Executors take runs from the queue, call the target, and record results. Failures go back to the queue with exponential backoff until the retry limit.
If a scheduler dies, its leases expire and another worker takes over its shards; it rescans recent buckets, so missed jobs fire late but are not skipped.
Bottlenecks and trade-offs
Top-of-minute and top-of-hour spikes. Add a stable jitter per job (for example hash(job_id) mod 60 seconds) for jobs that allow it, and pre-load the next minute's bucket into memory.
At-least-once. A run can execute twice if an executor crashes after calling the target. Pass run_id to targets so they can deduplicate.
Time zones and daylight saving time. Store the time zone with the job and compute next times in it; decide whether a skipped or repeated local hour runs zero, one or two times, and document it.
Long jobs need heartbeats so the system can tell a slow job from a dead executor.
Polling versus timers. Polling minute buckets is simple and durable; in-memory timer wheels are faster but must be rebuilt after a crash.
By level
Fresher: Explain that jobs are stored with their next run time and workers pick up the ones that are due. A fresher should know that failed jobs need retries.
Mid: Design the bucketed index, lease-based ownership, deterministic run IDs and a queue for executors. Do the peak-minute math and add jitter.
Senior: Cover failover gaps, time zones, heartbeats for long jobs, tenant limits, dependencies and polling versus timer wheels. Expect clear at-least-once reasoning.
Key points
Index next run times in minute buckets, partitioned across schedulers
Leases assign shards and move them on failure
Run ID from job ID and scheduled time makes duplicates detectable
At-least-once delivery; targets deduplicate by run ID
Jitter spreads top-of-minute spikes
Common mistakes
One scheduler process with no failover
Scanning the whole jobs table every second
No idempotency, so failover causes duplicate side effects
Ignoring time zones and daylight saving changes
Follow-ups
How would you support job dependencies, such as B runs after A?
How would you cap concurrent runs per tenant?
How do you run a job exactly at 09:00:00.000?
Tips
Separate scheduling from execution
Explain the deterministic run ID
Discuss the top-of-hour spike with numbers
Evaluation rubric
Durable job storage and due index
Failover with leases
Idempotent runs and retry policy
Capacity math and spike handling
64.system-design-0064Easyfresher
Design an API gateway that sits in front of 200 microservices and handles authentication, rate limiting and routing for 200,000 requests per second at peak.
Run a fleet of stateless gateway nodes behind a load balancer. Each request goes through a chain of filters: TLS termination, authentication (verify a JWT locally or check a cached session), rate limiting against a shared counter store, routing by path to the right service, and logging. Routes and policies are loaded from a configuration store and refreshed without restarts. At 10,000 requests per second per node, 200,000 requests per second needs 20 nodes, or 30 with headroom.
Full answer
Requirements
Functional:
Route /v1/orders/* to the orders service, /v1/users/* to users, and so on.
Authenticate callers, apply rate limits per key or user, and add request IDs.
Transform or aggregate in simple cases (for example strip internal headers).
Non-functional:
Adds only a few milliseconds of latency.
Highly available: if the gateway is down, everything is down.
Configuration changes take effect within seconds without restarts.
Capacity estimates
Assumptions: 200,000 requests per second at peak, 10,000 requests per second per gateway node, 95% of token checks served from a local cache when tokens are opaque.
Nodes: 200,000 / 10,000 = 20 nodes; 30 with 50% headroom for failures and spikes.
Auth service load with opaque tokens: 5% misses x 200,000 = 10,000 lookups per second. With signed JWTs verified locally, this drops to almost zero.
Rate-limit store: one counter update per request, 200,000 per second, which a Redis cluster with several shards handles.
API
The gateway exposes the services' APIs. Its own admin API:
PUT /admin/routes/orders {"match": "/v1/orders/*", "upstream": "orders.svc:8080",
"auth": "jwt", "rate_limit": {"per_user": "100/m"}, "timeout_ms": 2000}
GET /admin/routes
Every proxied response carries X-Request-Id; limited requests get 429 with Retry-After.
Data model
Route table: path pattern, methods, upstream service, auth policy, limits, timeouts, retry policy. Stored in a configuration store (etcd, a database) and cached in every node's memory.
Rate-limit counters in Redis, keyed by (policy, caller, window).
Public keys for JWT verification fetched from the identity provider and cached.
Match the route (a prefix tree on paths gives fast lookup across hundreds of routes).
Authenticate: verify the JWT signature and expiry with cached keys; reject with 401 if invalid.
Authorise coarse rules (for example "admin routes need the admin scope"); fine-grained checks stay in services.
Rate limit; reject with 429 if over.
Forward to a healthy service instance with a timeout; retry only idempotent methods.
Emit access logs, metrics and a trace span.
Bottlenecks and trade-offs
Single choke point. Keep nodes stateless, run them across zones and keep the logic small; heavy business logic in the gateway makes every deploy risky.
Rate-limit store outage. Fail open with local per-node limits so a Redis problem does not block all traffic, or fail closed for sensitive endpoints.
JWT versus opaque tokens. JWTs avoid a lookup per request but cannot be revoked instantly; short expiry times (5 to 15 minutes) limit the risk.
One gateway or several. A separate gateway per client type (web, mobile, partners) lets each evolve independently, at the cost of more components.
Configuration push must be validated and rolled out gradually; a bad route table is an outage for everyone.
By level
Fresher: Explain that the gateway is the single front door that checks who you are, limits how often you call and forwards you to the right service. A fresher should sketch the route table.
Mid: Size the fleet, design the filter chain, choose JWT verification, and handle rate-limit store failure. Mention timeouts and safe retries.
Senior: Discuss blast radius, staged config rollout, per-client gateways, token revocation and zero-trust between gateway and services. Expect clear limits on what belongs in the gateway.
Calling the auth service on every request with no caching
Retrying non-idempotent requests
Having no plan for rate-limit store failure
Follow-ups
How would you do canary routing of 5% of traffic?
How do you revoke a JWT before it expires?
Should services trust headers set by the gateway?
Tips
List the filter chain in order
Do the node count math
Mention fail-open versus fail-closed
Evaluation rubric
Clear request pipeline
Capacity math for nodes and dependencies
Sensible auth and rate limiting
Availability and config trade-offs
65.system-design-0065Mediumfresher
Design an online judge and code execution sandbox like LeetCode or the Schoolabe practice platform that runs untrusted user code safely and handles contest spikes.
Submissions go into a queue; stateless judge workers pull them and run each in an isolated sandbox (a container or microVM with no network, read-only file system, and CPU, memory, process and time limits). The worker compiles the code, runs every test case, compares outputs and stores a verdict. Results stream back to the user. Contest spikes are absorbed by the queue and autoscaling: 50,000 contestants submitting every 5 minutes need about 830 cores at 5 CPU-seconds per submission.
Full answer
Requirements
Functional:
Users submit code in several languages for a problem; they get a verdict (Accepted, Wrong Answer, Time Limit Exceeded, Runtime Error, Compilation Error) and run time.
"Run" against sample tests and "Submit" against hidden tests.
Contests with a live leaderboard.
Non-functional:
User code can never read other users' data, the hidden tests, or reach the network.
Verdicts in a few seconds normally; queues may grow during contests but must not lose submissions.
Fair and repeatable timing.
Capacity estimates
Assumptions: 2M submissions per day normally; a contest with 50,000 users each submitting every 5 minutes; 5 CPU-seconds per submission across all test cases.
Normal: 2M / 86,400 = about 23 submissions per second.
Contest: 50,000 / 300 = about 167 per second.
CPU: 167 x 5 = about 830 cores busy; with 2x headroom about 1,700 cores, autoscaled for the contest window only.
flowchart LR
U[User] --> API[Submission API]
API --> DB[(Submissions DB)]
API --> Q[(Submission queue)]
Q --> W[Judge workers]
W --> SB[Sandbox per run]
W --> TC[(Test cases store)]
W --> DB
W -- "status events" --> PUB[Pub-sub]
PUB --> API
API -- "WebSocket" --> U
Sandboxing
Each run happens in a fresh sandbox:
A container with seccomp filters and no capabilities, or a microVM (Firecracker, gVisor) for stronger isolation.
No network interface; read-only root file system; a small writable temp directory.
Limits through cgroups: CPU time per test, wall-clock time, memory, number of processes (to stop fork bombs), output size.
Runs as an unprivileged user; the sandbox is destroyed afterwards.
The worker copies in only the source and the current test input, never the whole test set, and compares output outside the sandbox (exact match, token match, or a special checker for problems with many correct answers).
Bottlenecks and trade-offs
Contest spikes. Pre-warm workers before the start, use the queue to absorb bursts, and give contest submissions priority over practice runs.
Timing fairness. Noisy neighbours change run times; pin each sandbox to dedicated cores and measure CPU time, not wall time.
Containers versus microVMs. Containers start in milliseconds but share the kernel; microVMs give stronger isolation at a small start-up cost. Pools of pre-started sandboxes hide that cost.
Language images are cached on every worker to avoid pulling them at contest start.
Duplicate processing. If a worker dies, the queue redelivers; the verdict write is idempotent by submission_id.
By level
Fresher: Explain that submissions wait in a queue and workers run them in an isolated box with time and memory limits. A fresher should list at least three things the sandbox must block.
Mid: Do the contest math, describe sandbox limits and isolation choices, and stream status updates. Handle worker crashes with idempotent verdicts.
Senior: Compare containers, gVisor and microVMs, design for timing fairness, prioritisation, pre-warming and special checkers. Expect a threat model that covers escape attempts and data leaks.
Key points
Queue between API and judge workers absorbs spikes
Fresh sandbox per run with no network and strict cgroup limits
Test cases never enter the sandbox in bulk; compare outside
Measure CPU time for fair verdicts
Pre-warm and prioritise for contests
Common mistakes
Running user code directly on the API server
Allowing network access inside the sandbox
No limit on processes or output size
Using wall-clock time on shared machines for verdicts
Follow-ups
How would you support interactive problems that talk to a judge program?
How do you detect plagiarism in a contest?
How would you add a new language safely?
Tips
Start with the threat model: untrusted code
List the concrete sandbox limits
Do the contest CPU math
Evaluation rubric
Clear async pipeline with a queue
Strong sandbox design with specific limits
Capacity math for contests
Fairness and failure handling
66.system-design-0066Hardsenior
Design a live video streaming platform like Twitch or YouTube Live where one stream can reach 1 million concurrent viewers with a few seconds of delay.
The streamer sends RTMP or SRT to an ingest server, which transcodes in real time into a ladder of bitrates and cuts the stream into short segments (1 to 2 seconds, or smaller parts for low-latency HLS). Segments and playlists are pushed to origin storage and fanned out through a CDN; players fetch the newest segments and switch bitrate as their bandwidth changes. One stream at 1 million viewers and 3 Mbps is about 3 Tbps of egress, which only a CDN can serve.
Full answer
Requirements
Functional:
Streamers broadcast from software or a phone; viewers watch live with adaptive quality.
Live chat alongside the stream; the stream is recorded for later viewing.
Non-functional:
Glass-to-glass delay of a few seconds (standard HLS is 15 to 30 seconds; low-latency modes reach 2 to 5).
Smooth playback for viewers on weak connections.
A popular stream must not overload origin servers.
Capacity estimates
Assumptions: one big stream with 1M concurrent viewers at an average of 3 Mbps, a ladder of 6 renditions (1080p down to 160p), 100,000 concurrent streams platform-wide, most with a few viewers.
Egress for the big stream: 1M x 3 Mbps = 3 Tbps, served by CDN edges.
Origin egress stays small: each CDN edge region fetches each segment once and serves it many times.
Transcoding: 100,000 streams x 6 renditions; GPU or hardware encoders handle dozens of renditions per machine, so the fleet is in the low thousands of machines. Small streams may get fewer renditions to save cost.
API
Ingest: rtmp://ingest.example.com/live/{stream_key}
POST /v1/streams -> {"stream_id", "stream_key", "ingest_url"}
GET /v1/streams/{id}/master.m3u8 -> playlist listing renditions
GET /v1/streams/{id}/720p/index.m3u8 ; .../720p/seg_18342.m4s
WS /v1/streams/{id}/chat
Data model
streams: stream_id, owner, status (live, ended), started_at, ingest_node, renditions.
Segments in object storage: live/{stream_id}/{rendition}/seg_{n}.m4s, plus rolling playlists listing the latest segments.
Recordings: the same segments kept and stitched into a video-on-demand asset after the stream.
High-level design
mermaid
flowchart LR
S[Streamer] -- "RTMP or SRT" --> IN[Ingest edge]
IN --> TR[Real-time transcoder]
TR --> PK[Packager: segments and playlists]
PK --> OR[(Origin storage)]
OR --> SH[Origin shield]
SH --> CDN[CDN edges]
CDN --> V[Viewers]
V --> CH[Chat service]
Latency and delivery
Segment length drives delay: players buffer about three segments, so 6-second segments mean roughly 20 seconds. Low-latency HLS or DASH sends partial segments (around 200 to 500 ms) and lets players request the next part before it exists, bringing delay to a few seconds.
An origin shield layer between CDN edges and origin collapses many edge requests for the same new segment into one.
Request coalescing at the edge stops a "thundering herd" when a million players ask for the next segment at the same moment.
Players use adaptive bitrate: they measure download speed and choose the rendition that keeps the buffer healthy.
Bottlenecks and trade-offs
Latency versus stability. Shorter segments and smaller buffers mean less delay but more rebuffering on poor networks; offer a low-latency mode for interactive streams.
Transcoding cost. Transcode all renditions only for streams with enough viewers; pass through the original for tiny streams.
Ingest failure. Streamers reconnect to another ingest node; the player sees a short gap. Redundant ingest from the streamer is possible for big events.
Chat at 1M viewers is its own fan-out problem: sample or rate-limit messages and shard rooms.
WebRTC gives sub-second delay but is expensive to scale to millions; it suits small interactive streams.
By level
Fresher: Describe the path from streamer to ingest, transcoding, small video files and the CDN. A fresher should explain why viewers get different qualities.
Mid: Explain segment-based delivery and latency, origin shield, adaptive bitrate and the egress math. Mention recording for later viewing.
Senior: Compare LL-HLS, DASH and WebRTC, discuss transcoding economics, request coalescing, ingest redundancy and chat at scale. Expect clear latency versus stability reasoning.
Key points
Ingest, real-time transcode into a bitrate ladder, then segment
CDN plus origin shield serve 3 Tbps for one big stream
Request coalescing prevents herds on new segments
Adaptive bitrate on the player
Common mistakes
Serving viewers from origin servers
Claiming standard HLS gives one-second latency
Transcoding every rendition for streams with two viewers
Ignoring chat scale for big streams
Follow-ups
How would you get delay under one second?
How do you insert ads into a live stream?
How do you handle a streamer with an unstable upload connection?
Tips
Explain the segment-latency link with numbers
Show the egress math to justify the CDN
Mention origin shield and coalescing
Evaluation rubric
Correct ingest to CDN pipeline
Latency reasoning
Egress capacity math
Cost and failure trade-offs
67.system-design-0067Mediummid
Design a Netflix-style video-on-demand service that streams a fixed catalogue to 30 million concurrent viewers at peak, using a CDN that is filled before demand arrives.
Encode every title once into many bitrate and device variants, store them in object storage, and copy them in advance to CDN appliances inside internet providers' networks during quiet hours, based on predicted popularity. The control plane (sign-in, catalogue, recommendations, choosing a CDN server) runs in the cloud; the data plane (video bytes) comes almost entirely from nearby caches. Peak egress is about 150 Tbps for 30 million viewers at 5 Mbps.
Full answer
Requirements
Functional:
Browse the catalogue, play a title, resume where you stopped, on TVs, phones and browsers.
Adaptive quality, subtitles and multiple audio tracks; downloads for offline viewing.
Non-functional:
Playback starts in about 2 seconds and rarely rebuffers.
Peak evening traffic is served without overloading transit links.
Content is protected with DRM.
Capacity estimates
Assumptions: 30M concurrent viewers at peak, 5 Mbps average, 5,000 titles averaging 1.5 hours, 10 renditions per title, 2 GB per hour per rendition on average.
Peak egress: 30M x 5 Mbps = 150 Tbps.
Catalogue size: 5,000 x 1.5 x 10 x 2 GB = 150 TB. Small enough that a large CDN site can hold the whole popular part of it.
This is why pre-positioning works: the catalogue is fixed and known, unlike user-generated video.
API
GET /v1/catalog/rows?profile=.. -> personalised rows of titles
POST /v1/playback/{title_id}/start -> {"manifest_url": "https://cdn-node-17.isp.example/...", "license_url": "...", "resume_s": 1830}
POST /v1/playback/{session}/heartbeat {"position_s": 1890, "bitrate": 4300}
The manifest lists renditions and the specific nearby CDN servers that hold the files.
Data model
titles: title_id, metadata, artwork, available regions.
viewing_progress: (profile_id, title_id) to position and updated_at, in a key-value store.
cdn_inventory: which appliance holds which assets, and its health and load.
High-level design
mermaid
flowchart LR
ST[Studio masters] --> ENC[Encoding pipeline]
ENC --> OS[(Object storage)]
OS -- "nightly fill" --> APP[CDN appliances inside ISPs]
D[Device] --> CP[Control plane in cloud]
CP --> STEER[Steering service]
STEER --> APP
D -- "video bytes" --> APP
D --> LIC[DRM license service]
Key techniques
Per-title and per-scene encoding. Simple cartoons need fewer bits than action films; choosing bitrates per title saves bandwidth at the same quality.
Pre-positioning. Each night, a popularity forecast decides which files each appliance should hold. New releases are pushed before launch day.
Steering. At play time, the control plane picks appliances close to the viewer that hold the files and are healthy, and lists a few fallbacks.
Client logic. The player picks bitrates from measured throughput and buffer level, and switches server if one is slow.
Bottlenecks and trade-offs
Forecast misses. A surprise hit may not be on local appliances; fall back to regional caches and fill on demand.
Storage versus egress. More renditions improve quality on every device but multiply storage and fill traffic.
Control plane outage stops new plays even if caches are healthy; run it in several regions and cache catalogue responses on devices.
Own CDN versus commercial CDN. Placing appliances in ISPs cuts transit cost and latency at huge scale, but needs partnerships and operations work; smaller services should rent a commercial CDN.
DRM licence requests are on the start-up path; keep them fast and regional.
By level
Fresher: Explain that videos are copied to servers near viewers before people watch them, and that the app picks a quality based on the internet speed. A fresher should describe resume playback.
Mid: Size egress and storage, design pre-positioning and steering, and explain per-title encoding. Mention DRM on the start path.
Senior: Discuss forecast misses, own versus rented CDN, control plane resilience, quality measurement and encoding economics. Expect reasoning that ties catalogue size to the caching strategy.
Key points
Encode once into many renditions
Pre-position files in ISP caches during quiet hours
Control plane in the cloud, data plane at the edge
About 150 Tbps at peak for 30 million viewers
Steering picks healthy nearby caches with fallbacks
Common mistakes
Serving video bytes from cloud servers
Treating a fixed catalogue like user uploads
One bitrate ladder for every title
Forgetting that the control plane is still needed to start playback
Follow-ups
How would you handle a surprise hit show?
How do downloads for offline viewing work with DRM?
How would you measure playback quality across devices?
Tips
Contrast with live streaming and user-generated video
Do the egress and catalogue math
Explain control plane versus data plane
Evaluation rubric
Clear separation of control and data planes
Correct capacity math
Pre-positioning and steering
Trade-offs on renditions, CDN ownership and failures
68.system-design-0068Mediumfresher
Design the checkout and inventory system for an e-commerce site with 5 million orders per day, so stock is never oversold and a failed payment does not lose the order.
At checkout, reserve stock with an atomic conditional decrement (only if available is at least the quantity), create the order in a pending state, then take payment with an idempotency key. On success, confirm the order and the reservation; on failure or timeout, release the reservation. These steps form a saga with compensations rather than one distributed transaction. 5 million orders per day is about 580 per second at a 10x peak.
Full answer
Requirements
Functional:
Add to cart, check out with an address and payment method, receive an order confirmation.
Stock levels per product and warehouse; reservations during checkout.
Cancel and refund.
Non-functional:
Never sell more units than exist (for normal products).
A user who clicks "Pay" twice is charged once.
The cart and product pages can be slightly stale; stock decisions cannot.
Capacity estimates
Assumptions: 5M orders per day, peak factor 10 during sales, 3 items per order.
Orders: 5M / 86,400 = about 58 per second; about 580 per second at peak.
Stock updates: 3 x 580 = about 1,740 reservations per second at peak, spread over many products.
One busy product may see hundreds of reservations per second during a sale, which is the real hot spot (see flash sale design for extreme cases).
API
POST /v1/carts/{id}/items {"sku": "TSHIRT-M-BLUE", "qty": 2}
POST /v1/checkout Idempotency-Key: 9b2e... {"cart_id", "address_id", "payment_method_id"}
-> 201 {"order_id": "o_5521", "status": "CONFIRMED"} or 409 {"error": "OUT_OF_STOCK", "sku": ...}
POST /v1/orders/{id}/cancel
Data model
sql
CREATE TABLE inventory (
sku VARCHAR(40),
warehouse VARCHAR(10),
on_hand INT NOT NULL,
reserved INT NOT NULL DEFAULT 0,
PRIMARY KEY (sku, warehouse),
CHECK (reserved <= on_hand)
);
flowchart LR
U[User] --> CO[Checkout service]
CO --> INV[Inventory service]
INV --> IDB[(Inventory DB)]
CO --> ODB[(Orders DB)]
CO --> PAY[Payment service]
CO -- "order events" --> BUS[(Event bus)]
BUS --> FUL[Fulfilment]
BUS --> EMAIL[Email]
EXP[Reservation expiry worker] --> INV
Checkout saga
Check the idempotency key; return the earlier result if found.
Reserve stock for each item:
UPDATE inventory SET reserved = reserved + :q WHERE sku = :s AND warehouse = :w AND on_hand - reserved >= :q.
If any update affects 0 rows, release earlier reservations and return out of stock.
Create the order as PENDING_PAYMENT.
Charge the payment with the order ID as the idempotency key.
Success: mark the order CONFIRMED, commit reservations (decrement on_hand and reserved when shipped). Failure: mark the order PAYMENT_FAILED and release reservations.
Reservations have an expiry; the worker releases any left behind by crashes.
Each step is idempotent, so the saga can be retried from any point.
Bottlenecks and trade-offs
Reserve at add-to-cart or at checkout? Reserving at checkout avoids stock being locked in abandoned carts; the cost is that a user may find an item gone at checkout.
Hot products make one row hot; split stock into several rows (buckets) and reserve from any bucket that has enough.
Payment timeouts keep the order pending until the payment status is known, rather than releasing stock and charging later.
Overselling on purpose is sometimes chosen for items that restock fast; that is a business decision, not a bug.
Cart and catalogue are cached and eventually consistent; only the inventory and order writes need strong consistency.
By level
Fresher: Explain that stock is checked and reduced in one safe step, and that the order waits for payment before it is confirmed. A fresher should know why a double click must not create two orders.
Mid: Write the reservation update, design the saga with compensations and expiry, and size the peak. Discuss when to reserve.
Senior: Cover hot rows with bucketed stock, payment timeouts, intentional overselling, multi-warehouse allocation and consistency boundaries. Expect clear failure handling at each step.
Key points
Reserve stock with an atomic conditional update
Order states move from pending to confirmed or failed
Saga with compensations instead of a distributed transaction
Idempotency key on checkout and payment
Reservation expiry cleans up after crashes
Common mistakes
Reading stock then writing it in two steps without a condition
Reserving at add-to-cart with no expiry
Releasing stock when a payment times out but may have succeeded
Using a distributed transaction across inventory, orders and payment
Follow-ups
How would you split an order across two warehouses?
How do you handle a return?
What changes for a flash sale with 100,000 units in 10 seconds?
Tips
Write the conditional update
Walk through the saga steps and compensations
Separate strong and eventual consistency areas
Evaluation rubric
Correct reservation logic
Saga with compensations and idempotency
Capacity math
Hot products and timeout handling
69.system-design-0069Hardsenior
Design a flash sale system where 10 million users try to buy 100,000 discounted phones in the first 10 seconds of a sale.
Do not let 1 million requests per second reach the order database. Serve the sale page from a CDN, put users through a virtual waiting room that admits them at a fixed rate, decrement a pre-loaded stock counter atomically in memory (Redis, split into buckets), and give each winner a short-lived purchase token. Orders are then created asynchronously from a queue at a rate the database can handle. Only 100,000 users can succeed, so the system's job is to say "sold out" quickly and fairly to the other 9.9 million.
Full answer
Requirements
Functional:
At the start time, users press "Buy"; the first 100,000 valid buyers get a phone, one per user.
Winners complete payment within a time limit; unpaid units go back to the pool.
Everyone else sees a clear sold-out or waiting message.
Non-functional:
No overselling, no duplicate purchases per user.
The rest of the site keeps working during the sale.
Fair: bots should not take most units.
Capacity estimates
Assumptions: 10M users arrive within 10 seconds, 100,000 units, the order database sustains 5,000 order writes per second.
Incoming: 10M / 10 = 1M requests per second at the peak.
Successful buyers: 100,000, only 1% of requests.
Order creation: 100,000 / 5,000 = 20 seconds to write every order if they are queued and processed steadily.
The design must turn a 1M requests per second spike into a 5,000 writes per second stream.
API
GET /sale/phone-x (static page from CDN with countdown)
POST /v1/sales/phone-x/enter -> {"queue_token": "...", "position": 120345} (waiting room)
POST /v1/sales/phone-x/claim (with admission token) -> 200 {"purchase_token", "expires_in": 600} or 410 {"status": "SOLD_OUT"}
POST /v1/orders {"purchase_token", "address_id", "payment_method_id"}
Data model
sale:{id}:stock:{bucket} in Redis, 100,000 units split into, for example, 20 buckets of 5,000.
sale:{id}:buyers set of user IDs that already claimed (one per user).
Orders in the normal orders database, written by queue consumers.
High-level design
mermaid
flowchart LR
U[Users] --> CDN[CDN: sale page]
U --> WR[Waiting room]
WR -- "admitted at fixed rate" --> CL[Claim service]
CL --> R[(Redis stock buckets and buyer set)]
CL --> Q[(Order queue)]
Q --> OW[Order workers]
OW --> DB[(Orders DB)]
OW --> PAY[Payment]
EXP[Expiry worker] --> R
The claim step
A Lua script in Redis runs atomically:
If the user is in the buyer set, return "already claimed".
Pick a random stock bucket; if its count is above 0, decrement it, add the user to the buyer set and return success; otherwise try another bucket, and if all are empty return sold out.
Success returns a signed purchase token and puts an order request on the queue. Because each script is atomic, stock never goes below zero. Splitting stock into buckets spreads the load over several Redis shards so one key is not a bottleneck.
When stock reaches zero, a "sold out" flag is published to the CDN and waiting room, so new users get the answer without touching the claim service.
Bottlenecks and trade-offs
Protecting the rest of the site. Run the sale on separate capacity and use rate limits so the flood cannot exhaust shared services.
Fairness and bots. Require sign-in before the sale, one claim per verified account, CAPTCHA or proof of work in the waiting room, and randomised admission among users who arrived before the start.
Unpaid claims. Purchase tokens expire after 10 minutes; the expiry worker returns units to stock and can admit more users.
Redis failure during the sale: use a replicated setup and accept that a failover could briefly reject claims; reconcile Redis stock with orders after the sale.
Strict first-come-first-served is impossible at network scale; a waiting room with random order among early arrivals is fairer than a race of milliseconds.
By level
Fresher: Explain that the sale page is cached, users wait in a queue, and stock is reduced in one safe step. A fresher should say why the database cannot take every click directly.
Mid: Do the spike math, design the waiting room, the atomic claim and the order queue, and handle unpaid claims. Explain stock buckets.
Senior: Cover fairness, bots, isolation from the main site, Redis failover and reconciliation, and the limits of first-come-first-served. Expect a clear plan for failing fast.
Key points
Turn a 1M requests per second spike into a steady stream the database can handle
Static page on CDN plus a waiting room
Atomic stock decrement in Redis split into buckets
One claim per user enforced in the same atomic step
Async order creation from a queue; expiring purchase tokens
Common mistakes
Sending every buy request to the relational database
One Redis key for all stock, creating a hot key
Checking "already bought" and decrementing in separate steps
Letting the sale traffic take down the rest of the site
Follow-ups
How would you stop bots from winning most units?
How do you return unpaid units to other users?
How would you run several flash sales at once?
Tips
Lead with the numbers: 1M per second versus 5,000 writes per second
Explain why most requests should fail fast
Show the atomic script steps
Evaluation rubric
Correct spike math and overload protection
Atomic, oversell-free stock handling
Async order pipeline with expiry
Fairness and isolation trade-offs
70.system-design-0070Mediumfresher
Design a proximity search service like Yelp or Google Maps "restaurants near me" that finds places within a few kilometres from 100 million listings.
Store places in a database and index them by location cell (a geohash prefix or a quadtree node). A search computes the user's cell and its eight neighbours, fetches candidate places from those cells, filters by exact distance and other filters, and ranks the results. Place data changes rarely, so the index is read-heavy, cacheable and replicated. 100 million places at 1 KB each is only about 100 GB.
Full answer
Requirements
Functional:
Search places near a point within a radius (for example 2 km), with filters such as category and "open now".
View place details, photos and reviews.
Owners add or update places; users add reviews.
Non-functional:
Search results in under about 200 ms.
Read-heavy: searches far outnumber updates.
New or edited places may take a few minutes to appear in search.
Capacity estimates
Assumptions: 100M places, 1 KB per place record, 50,000 searches per second at peak, about 10 place updates per second.
Place data: 100M x 1 KB = about 100 GB, which fits on a single large database server and easily in a few index replicas.
Searches are the load: 50,000 per second, served by many read replicas of the geo index and a cache for popular areas.
Reviews and photos are far larger but are fetched only on the details page, from separate services.
API
GET /v1/search?lat=19.07&lng=72.87&radius_m=2000&category=cafe&open_now=true&cursor=..
-> [{"place_id", "name", "distance_m", "rating", "price_level"}...]
GET /v1/places/{id}
POST /v1/places/{id}/reviews {"rating": 4, "text": "..."}
Data model
places: place_id, name, lat, lng, geohash (precision 6 to 8), category, rating, price_level, hours, updated_at.
Index on (geohash) so a prefix query returns all places in a cell.
reviews: review_id, place_id, user_id, rating, text, created_at (separate service and store).
High-level design
mermaid
flowchart LR
U[User app] --> LB[Load balancer]
LB --> S[Search service]
S --> C[(Cache by cell and filters)]
S --> GI[(Geo index replicas)]
LB --> P[Place service]
P --> DB[(Places DB primary)]
DB -- "change stream" --> GI
LB --> RV[Reviews service]
How the geo lookup works
A geohash turns latitude and longitude into a string where a shared prefix means nearby. Precision 6 is a cell of roughly 1.2 km by 0.6 km. For a 2 km search:
Choose a precision whose cell size is close to the radius (precision 5 or 6).
Compute the user's cell and its 8 neighbours (needed because a user near a cell edge has close places in the next cell).
Fetch places in those 9 cells, compute the real distance with the haversine formula, keep those within the radius.
Apply filters, rank by distance, rating and relevance, and return a page.
A quadtree is an alternative: it splits busy areas (city centres) into small nodes and leaves empty areas (deserts) as large nodes, so each leaf holds a similar number of places.
Bottlenecks and trade-offs
Uneven density. A fixed geohash precision gives thousands of places per cell in Manhattan and none in rural areas. Use adaptive radius (grow the search until enough results) or a quadtree.
Caching. Cache results per (cell, category) for a minute; popular areas get high hit rates.
Freshness. Changes flow to index replicas through a change stream; a few minutes of delay is acceptable.
Geohash versus quadtree versus S2 or H3. Geohash works in any database with a string index; quadtrees adapt to density but are usually in-memory; S2 and H3 give better-shaped cells for global coverage.
"Open now" depends on local time zones and holidays; compute it at query time from stored hours.
By level
Fresher: Explain that places are grouped into map squares so the search only looks at nearby squares, then checks exact distance. A fresher should mention caching popular areas.
Mid: Describe geohash precision and neighbours, the read path with replicas and cache, and the update path with a change stream. Do the capacity math.
Senior: Compare geohash, quadtrees, S2 and H3, handle density with adaptive radius, and discuss ranking and freshness. Expect clear reasoning about where the load is.
Key points
Index places by location cell (geohash prefix or quadtree)
Search the user's cell plus 8 neighbours, then filter by exact distance
100 million places is only about 100 GB
Read replicas and caching handle 50,000 searches per second
Adaptive radius or quadtrees handle uneven density
Common mistakes
Scanning all places and computing distance for each
Searching only the user's own cell and missing places across the edge
Using one fixed cell size everywhere without handling density
Writing every search through the primary database
Follow-ups
How would you rank results beyond distance?
How do you handle a user moving while results load?
How would you search along a route instead of around a point?
Tips
Explain geohash prefixes with an example
Mention the neighbour cells
Note how small the data set is
Evaluation rubric
Correct geo indexing method
Neighbour cells and exact distance filtering
Capacity math for data and reads
Density and freshness trade-offs
71.system-design-0071Hardsenior
Design a stock exchange matching engine that matches buy and sell orders with price-time priority at microsecond latency and never loses an accepted order.
Each symbol's order book is owned by a single-threaded matching engine that keeps bids and asks in memory, sorted by price and then arrival time. Incoming orders are sequenced into a durable log first; the engine reads the log in order, matches deterministically and publishes trades and book updates. Because the engine is deterministic, replicas replay the same log to reach identical state, which gives fast failover. Throughput scales by splitting symbols across engines, not by sharing one book.
Full answer
Requirements
Functional:
Accept limit and market orders, cancels and modifications for thousands of symbols.
Match by price-time priority: best price first, and the earliest order at that price first.
Publish trades and market data; send execution reports to brokers.
Non-functional:
Matching latency in microseconds to low milliseconds, with very low variance.
No accepted order is lost; the same input always yields the same trades.
Fair: no participant gets an unfair ordering advantage.
Capacity estimates
Assumptions: 100,000 orders per second at peak across 5,000 symbols, 200 bytes per log event, a 6.5-hour trading day.
Log volume: 100,000 x 200 bytes = 20 MB per second; 20 MB x 6.5 x 3,600 = about 468 GB per day.
Per symbol: busy symbols get a few thousand orders per second; one in-memory single-threaded engine can process more than 1M simple operations per second, so even the busiest symbol fits on one thread.
Order book memory is small: a few hundred thousand resting orders per symbol at most.
API
Brokers connect over a binary protocol (FIX or a native one) through gateways:
Prices are integers in ticks (for example paise or cents), never floats.
Data model
In memory per symbol:
Bids: price levels sorted high to low; each level is a FIFO queue of orders.
Asks: price levels sorted low to high.
Order map: order_id to its node, so cancels are O(1).
Durable:
Sequenced input log: every accepted command with a sequence number.
Output log: trades and execution reports, also sequenced.
High-level design
mermaid
flowchart LR
B[Brokers] --> GW[Order gateways: validation and risk checks]
GW --> SEQ[Sequencer]
SEQ --> LOG[(Replicated input log)]
LOG --> ME1[Matching engine primary]
LOG --> ME2[Matching engine replica]
ME1 --> OUT[(Trade and report log)]
OUT --> MD[Market data publisher]
OUT --> GW
OUT --> CLR[Clearing and settlement]
Matching
A buy limit at 251.50 for 100 shares arrives. While its quantity remains and the best ask is at or below 251.50, it trades with the oldest order at the best ask level, removing filled orders. Any remainder rests in the bid book at 251.50, behind earlier orders at that price.
The engine runs on one thread per symbol group: no locks, no shared state, and processing in sequence order. Determinism lets a replica that consumes the same log produce the same book and trades, so failover is a switch to a warm replica, not a recovery from disk.
Bottlenecks and trade-offs
Sequencer and log are on the critical path; they are replicated synchronously within the data centre (microseconds) before an order is acknowledged.
Risk checks (credit limits, price bands) happen in gateways before sequencing, so the engine stays simple.
Latency variance matters as much as average: avoid garbage collection pauses, pin threads to cores, pre-allocate memory and use kernel-bypass networking.
Fairness. Some exchanges add small randomised or fixed delays to reduce speed races; others offer equal-length cables in co-location.
Scaling is by partitioning symbols across engines; one symbol is never split, because price-time priority needs a single order.
By level
Fresher: Explain buy and sell queues sorted by price and time, and walk through one match. A fresher should know that every order must be recorded before it is processed.
Mid: Design the in-memory book, sequencer and log, and deterministic replicas. Do the log volume math and explain cancels.
Senior: Discuss latency variance, kernel bypass, risk checks, auctions, cross-site disaster recovery and fairness mechanisms. Expect a clear reason why one book stays on one thread.
Key points
Single-threaded engine per symbol group with in-memory price-time books
Sequence orders into a replicated log before matching
Deterministic replay gives identical replicas and fast failover
Integer tick prices; O(1) cancels through an order map
Scale by partitioning symbols, never by splitting one book
Common mistakes
Using a database transaction per order on the hot path
Multi-threaded matching on one book with locks
Floating-point prices
Acknowledging orders before they are durably sequenced
Follow-ups
How would you implement stop orders?
How do you run an opening auction?
How do you recover if the primary data centre is lost?
Tips
Explain price-time priority with a small example
Stress determinism and the input log
Talk about latency variance, not only average latency
Evaluation rubric
Correct order book structure
Durable sequencing before matching
Deterministic replication and failover
Latency and partitioning trade-offs
72.system-design-0072Mediumfresher
Design an email service like Gmail that receives, stores and searches mail for 100 million users who each get about 40 emails per day.
Incoming mail arrives over SMTP at mail transfer agents, passes spam and malware checks, and is stored as message metadata in a database partitioned by user plus message bodies and attachments in object storage, with identical attachments stored once. A search index per user is updated asynchronously. Clients read through an API (or IMAP) and get new-mail notifications by push. The scale is about 46,000 incoming emails per second and 200 TB of new data per day before deduplication.
Full answer
Requirements
Functional:
Receive and send mail with attachments using standard protocols (SMTP, and IMAP for third-party clients).
Folders and labels, threads, search over all mail.
Spam filtering and notifications for new mail.
Non-functional:
Accepted mail is never lost.
The inbox loads quickly; search returns in about a second.
Storage is the biggest cost.
Capacity estimates
Assumptions: 100M users, 40 incoming emails per user per day, 50 KB average size including attachments.
Incoming: 100M x 40 / 86,400 = about 46,000 emails per second.
New storage: 100M x 40 x 50 KB = 200 TB per day, about 73 PB per year before deduplication and compression.
Attachments sent to many people (a newsletter PDF) are stored once and referenced, which cuts storage a lot.
API
GET /v1/messages?label=INBOX&cursor=.. -> list of headers and snippets
GET /v1/messages/{id} -> full message with attachment links
POST /v1/messages/send {"to": [...], "subject", "body", "attachment_ids": [...]}
GET /v1/search?q=from:registrar has:attachment after:2026/11/01
POST /v1/messages/{id}/labels {"add": ["STARRED"], "remove": ["INBOX"]}
Data model
messages: (user_id, message_id) primary key, thread_id, from, to, subject, snippet, labels, received_at, body_ref, size. Partitioned by user_id so a user's mailbox is on one shard.
bodies: content-addressed blobs in object storage (key = hash of the content).
Search index: per-user inverted index over subject, body text, sender and attachment names.
High-level design
mermaid
flowchart LR
EXT[Other mail servers] -- "SMTP" --> MTA[Inbound MTAs]
MTA --> SP[Spam and malware filter]
SP --> ST[Store service]
ST --> MD[(Message metadata DB)]
ST --> OS[(Blob storage)]
ST -- "new mail event" --> IX[Indexer]
IX --> SI[(Search index)]
ST -- "new mail event" --> NT[Push notifications]
C[Web and mobile clients] --> API[Mail API]
API --> MD
API --> SI
API --> OS
API --> OUT[Outbound MTAs] --> EXT
Main flows
Receive. The MTA accepts the message only after it is safely queued on disk (otherwise the sender retries later, which SMTP supports). Checks: SPF, DKIM and DMARC for sender authenticity, spam scoring, virus scanning. The store service writes the body blob and the metadata row, then emits an event for indexing and notifications.
Read. The inbox list is a range read of the user's partition by label and time.
Send. The API stores the message in Sent, then the outbound MTA delivers it, retrying with backoff for hours if the receiving server is unavailable.
Bottlenecks and trade-offs
Storage cost. Deduplicate attachments, compress bodies, and move old mail to cheaper storage classes while keeping metadata hot.
Search freshness. Indexing is asynchronous, so a just-arrived email may take a few seconds to be searchable.
Big mailboxes. A user with millions of messages stays on one partition; that is fine for storage but heavy for search, so per-user index segments are merged in the background.
Spam filtering trades false positives (lost real mail) against false negatives; the spam folder is the safety net.
Sending reputation. Outbound IPs must be protected from abusive senders with rate limits, or the whole service's mail starts landing in spam elsewhere.
By level
Fresher: Explain that mail arrives at mail servers, is checked for spam, and is saved with its details in a database and its contents in file storage. A fresher should describe how the inbox list is loaded.
Mid: Size the system, partition by user, deduplicate attachments and design async indexing and notifications. Explain retries in SMTP.
Senior: Discuss storage tiering, large mailboxes, sender authentication, spam trade-offs, outbound reputation and deletion of shared blobs. Expect cost-driven reasoning.
Key points
SMTP in through MTAs that accept only after durable queueing
Metadata partitioned by user; bodies in blob storage
Store identical attachments once
Asynchronous per-user search indexing
About 46,000 emails per second and 200 TB per day before deduplication
Common mistakes
Storing full message bodies and attachments in the relational database
Accepting mail before it is durably stored
Indexing search synchronously on the receive path
Ignoring outbound sending reputation
Follow-ups
How would you implement conversation threading?
How do you support IMAP clients efficiently?
How would you delete an attachment shared by many messages?
Tips
Separate metadata, blobs and the search index
Do the storage math; it drives most decisions
Mention SPF, DKIM and DMARC
Evaluation rubric
Correct receive, store and read paths
Capacity math and storage strategy
Search and notification design
Spam and reputation trade-offs
73.system-design-0073Hardsenior
Design a distributed key-value store in the style of Amazon Dynamo or Cassandra that stays writable during failures and stores 10 TB with 1 million operations per second.
Partition keys with consistent hashing and virtual nodes, replicate each key to the next N nodes on the ring, and use tunable quorums (for example N = 3, W = 2, R = 2) so reads see the latest write while tolerating one failed replica. Handle temporary failures with hinted handoff, repair divergence with read repair and Merkle-tree anti-entropy, and spread membership with gossip. Each node stores data in an LSM tree for fast writes. 10 TB at 3 replicas is 30 TB, about 15 nodes by storage, and more with headroom.
Full answer
Requirements
Functional:
put(key, value), get(key), delete(key), values up to about 1 MB.
Per-request consistency level (fast and possibly stale, or quorum).
Non-functional:
Always writable, even when some nodes or a data centre link fail.
Scale out by adding nodes; no single point of failure.
Low latency: single-digit milliseconds at p99 inside a region.
Capacity estimates
Assumptions: 10 TB of data, replication factor 3, 2 TB usable disk per node, 100,000 operations per second per node, 1M operations per second total.
Stored data: 10 TB x 3 = 30 TB.
Nodes by storage: 30 / 2 = 15.
Nodes by throughput: each operation touches several replicas, but even counting 1M operations against 100,000 per node gives 10 nodes.
Storage decides: start with about 20 nodes to leave room for compaction space and growth.
API
PUT /kv/{key} body: value headers: Consistency: QUORUM, If-Match: <version> -> 200 {"version": ...}
GET /kv/{key} Consistency: ONE | QUORUM | ALL -> value + version (or several siblings)
DELETE /kv/{key} -> writes a tombstone
Data model
Each record: key, value, version (a vector clock or a timestamp with node ID), tombstone flag, TTL. On disk per node: commit log plus memtable plus SSTables (an LSM tree). Each node also keeps a Merkle tree per key range for repair.
High-level design
mermaid
flowchart LR
C[Client] --> CO[Coordinator: any node]
CO --> A[Replica A]
CO --> B[Replica B]
CO --> D[Replica C]
A <-->|gossip| B
B <-->|gossip| D
A --> L[(Commit log, memtable, SSTables)]
How requests work
Placement. Hash the key onto a ring; walk clockwise to find the first N distinct physical nodes. Virtual nodes (many tokens per server) spread load evenly and make adding a node move small slices from many peers.
Write. The coordinator sends the write to all N replicas and returns success after W acknowledge.
Read. It asks R replicas and returns the newest version. With R + W > N (2 + 2 > 3), every read set overlaps every write set in at least one replica that has the latest write.
Hinted handoff. If a replica is down, another node stores the write with a hint and passes it on when the replica returns, so writes keep succeeding.
Repair. Read repair fixes stale replicas noticed during reads; background anti-entropy compares Merkle trees to find and sync differing ranges cheaply.
Conflicts. With last-write-wins timestamps, concurrent writes silently drop one; with vector clocks, the store returns siblings and the application merges them (Dynamo's shopping cart example).
Bottlenecks and trade-offs
Consistency versus latency.ONE is fastest and may be stale; QUORUM is safer; ALL loses availability when any replica is down.
Sloppy quorums keep writes available but mean R + W > N no longer guarantees overlap during failures.
Hot keys still land on N nodes; cache them or split them at the application level.
Tombstones must be kept longer than the repair interval, or deleted data comes back from a stale replica.
Compaction in LSM trees uses disk bandwidth and space; leave headroom and schedule it carefully.
By level
Fresher: Explain that keys are spread across servers with a hash ring and each key is copied to three servers. A fresher should say why copies keep data safe when a server fails.
Mid: Describe quorums with R + W > N, hinted handoff, read repair and the capacity math including replication. Explain virtual nodes.
Senior: Discuss sloppy quorums, vector clocks versus last-write-wins, tombstone timing, Merkle-tree repair and compaction headroom. Expect exact trade-offs between consistency levels.
Key points
Consistent hashing with virtual nodes for placement
Replicate to N nodes with tunable W and R; R + W > N gives overlap
Hinted handoff keeps writes available
Read repair and Merkle trees fix divergence
Gossip for membership; LSM storage for fast writes
Common mistakes
Claiming R + W > N always gives strong consistency even with sloppy quorums
Using last-write-wins without noting it can drop concurrent writes
Deleting data without tombstones
Sizing by throughput only and ignoring replication and compaction space
Follow-ups
How would you add a node with no downtime?
How do vector clocks detect concurrent writes?
How would you support range scans?
Tips
Walk through one write and one read with N, W, R
Explain hinted handoff with a failed node
Size by storage with the replication factor
Evaluation rubric
Correct partitioning and replication
Quorum reasoning
Failure handling and repair
Conflict resolution and capacity math
74.system-design-0074Hardsenior
Design an object storage service like Amazon S3 that stores 100 PB across 100 billion objects with very high durability.
Separate the metadata service (bucket, key, version, size, and where the data chunks are) from the data nodes that store chunks. Large objects are split into chunks and protected with erasure coding, for example 6 data plus 3 parity fragments spread across failure domains, which survives 3 lost fragments at 1.5x storage instead of 3x for triple replication. Background scrubbing detects bit rot and repairs fragments. At 100 PB, erasure coding saves 150 PB of raw disk compared with three copies.
Full answer
Requirements
Functional:
Create buckets; PUT, GET, DELETE and LIST objects by key; objects from bytes to terabytes.
Multipart upload for large objects; versioning; pre-signed URLs.
Non-functional:
Durability of many nines: data must survive disk, machine and rack failures.
High availability for reads and writes; strong read-after-write consistency for new objects.
Throughput scales with the number of clients.
Capacity estimates
Assumptions: 100 PB of logical data, 100B objects (1 MB average), about 500 bytes of metadata per object, erasure coding with 6 data and 3 parity fragments.
Raw storage with erasure coding: 100 PB x 9 / 6 = 150 PB.
Raw storage with 3 replicas: 300 PB. Erasure coding saves 150 PB.
Metadata: 100B x 500 bytes = 50 TB, which needs its own sharded, replicated store.
API
PUT /{bucket}/{key} body: bytes -> 200 ETag: "9f86d0..."
GET /{bucket}/{key} Range: bytes=0-1048575
DELETE /{bucket}/{key}
GET /{bucket}?list-type=2&prefix=photos/2026/&continuation-token=..
POST /{bucket}/{key}?uploads -> upload_id; then PUT parts; then POST ...?uploadId=.. to complete
Data model
Metadata (sharded by hash of bucket and key, with a secondary ordering for prefix listing): bucket, key, version_id, size, etag, created_at, storage_class, list of chunk IDs.
Chunk placement: chunk_id to the 9 fragment locations (node, disk).
Data nodes: fragments in large append-only files, with checksums per block.
High-level design
mermaid
flowchart LR
C[Client] --> FE[Front-end API servers]
FE --> MS[(Metadata service)]
FE --> PL[Placement service]
FE --> DN1[Data node rack 1]
FE --> DN2[Data node rack 2]
FE --> DN3[Data node rack 3]
SCR[Scrubber and repair] --> DN1
SCR --> MS
GC[Garbage collector] --> DN2
Write and read paths
Write. The front end splits the object into chunks (for example 64 MB), encodes each into 6 data and 3 parity fragments, and writes the 9 fragments to 9 different nodes in different racks or zones. When enough fragments are durable, it writes the metadata record last. Writing metadata last means a failed upload leaves only orphan fragments, which garbage collection removes, and never a visible half-written object.
Read. Look up metadata, then read the 6 data fragments directly. If some are missing or slow, read parity fragments and decode.
Small objects are packed together into larger files so the system does not manage billions of tiny files on disks.
Bottlenecks and trade-offs
Erasure coding versus replication. Coding uses half the space of three copies but costs CPU, and repairing one lost fragment requires reading 6 others. Hot small objects can stay replicated for faster reads.
Metadata scale (50 TB, very high request rates) is often the real bottleneck, especially for LIST with prefixes; shard carefully and avoid hot prefixes.
Durability depends on detecting failures fast: scrubbers re-read checksums and repair before a second and third fragment are lost.
Consistency. Making the metadata write the commit point gives read-after-write consistency for new objects.
Deletes remove metadata first; space is reclaimed later by garbage collection, which also handles orphan fragments.
By level
Fresher: Explain that file details go in a metadata store and file contents are split and spread over many disks. A fresher should know why copies or parity pieces are needed.
Mid: Design chunking, erasure coding with placement across racks, and metadata-last writes. Do the storage math versus replication.
Senior: Discuss repair bandwidth, scrubbing, small object packing, metadata sharding and LIST, consistency guarantees and garbage collection. Expect durability reasoning tied to failure detection speed.
Key points
Separate metadata service from data nodes
Erasure coding 6 + 3 survives 3 lost fragments at 1.5x storage
Spread fragments across racks or zones
Write metadata last as the commit point
Scrubbing and repair keep durability high
Common mistakes
Storing objects only as three replicas at 100 PB scale without discussing cost
Putting fragments of one chunk on the same rack
Writing metadata before data is durable
Ignoring the metadata store as a scaling problem
Follow-ups
How would you implement versioning?
How do you list a prefix with billions of keys quickly?
How would you calculate durability from disk failure rates?
Tips
Do the erasure coding storage math
Explain metadata-last writes
Mention scrubbing and failure domains
Evaluation rubric
Clear metadata and data separation
Correct erasure coding reasoning and math
Write and read paths with consistency
Durability, repair and metadata scaling
75.system-design-0075Easyfresher
Design a unique ID generator service that issues 1 million 64-bit, roughly time-ordered IDs per second across many data centres without a central database.
Use a Snowflake-style layout: 41 bits of milliseconds since a custom epoch, 10 bits of machine ID and 12 bits of sequence within the millisecond. Each generator works alone, so there is no coordination per ID; only machine IDs must be assigned uniquely, for example through a coordination service at start-up. One machine can issue 4,096 IDs per millisecond, about 4 million per second, and 41 bits of milliseconds last about 69 years.
Full answer
Requirements
Functional:
Return a new unique 64-bit integer ID on request, fast.
IDs sort roughly by creation time, so newer rows have larger IDs.
Non-functional:
1M IDs per second in total, with low latency (a local call or a microsecond-level library function).
No single point of failure; keeps working if one data centre is cut off.
IDs are never reused, even after restarts.
Capacity estimates
Assumptions: 1M IDs per second at peak, generators embedded in application servers or run as a small service.
Time bits: 2^41 milliseconds is about 69.7 years from the chosen epoch.
Machine bits: 2^10 = 1,024 generators.
Sequence bits: 2^12 = 4,096 IDs per millisecond per generator, about 4.1M per second per generator.
So one generator could serve the whole 1M per second; many generators exist for availability and locality.
API
GET /v1/ids?count=100 -> {"ids": [7387719012345856001, ...]}
In practice most systems embed the generator as a library, so the "API" is next_id() with no network call.
Data model
No per-ID storage. The only state is:
machine_id per generator, leased from a coordination service (etcd or ZooKeeper) or derived from configuration (data centre bits plus worker bits).
The last timestamp and sequence in memory.
High-level design
mermaid
flowchart LR
A[App server] --> G1[ID generator lib, machine 17]
B[App server] --> G2[ID generator lib, machine 18]
G1 -. "lease machine ID at start" .-> ZK[(Coordination service)]
G2 -. "lease machine ID at start" .-> ZK
The generator
python
import threading
import time
EPOCH_MS = 1_767_225_600_000 # 2026-01-01T00:00:00Z, a custom epoch
class Snowflake:
"""64-bit IDs: 41 bits time (ms) | 10 bits machine | 12 bits sequence."""
def __init__(self, machine_id, clock=lambda: int(time.time() * 1000)):
assert 0 <= machine_id < 1024
self.machine_id, self.clock = machine_id, clock
self.last_ms, self.seq = -1, 0
self.lock = threading.Lock()
def next_id(self):
with self.lock:
now = self.clock()
if now < self.last_ms:
raise RuntimeError("clock moved backwards; refuse to issue IDs")
if now == self.last_ms:
self.seq = (self.seq + 1) & 0xFFF
if self.seq == 0: # 4,096 IDs used this ms: wait
while now <= self.last_ms:
now = self.clock()
else:
self.seq = 0
self.last_ms = now
return ((now - EPOCH_MS) << 22) | (self.machine_id << 12) | self.seq
if __name__ == "__main__":
gen = Snowflake(machine_id=7)
ids = [gen.next_id() for _ in range(10_000)]
assert len(set(ids)) == len(ids) and ids == sorted(ids)
assert (ids[0] >> 12) & 0x3FF == 7 # machine bits round-trip
t = [1_767_225_600_005]
stuck = Snowflake(1, clock=lambda: t[0])
stuck.next_id()
t[0] -= 1
try:
stuck.next_id()
raise AssertionError("expected RuntimeError")
except RuntimeError:
pass
print("ok: 10000 unique, sorted IDs")
Save as snowflake.py and run python3 snowflake.py (Python 3.13.5).
The time part makes IDs sortable across machines (to the millisecond); the machine part prevents collisions between generators; the sequence handles many IDs in one millisecond.
Bottlenecks and trade-offs
Clock going backwards (NTP correction) could create duplicates. The generator refuses to issue IDs (or waits) until the clock passes the last timestamp; monitoring alerts on clock jumps.
Machine ID reuse. If two processes get the same machine ID, they collide. Leases with expiry, and a delay before reusing a released ID, prevent this.
Ordering is approximate. IDs from different machines in the same millisecond are not ordered by real time. That is fine for sorting feeds, not for strict sequencing.
Alternatives. UUIDv4 needs no coordination but is 128 bits and random, which hurts index locality; UUIDv7 is time-ordered and 128 bits; a database sequence is simple but central. Snowflake gives 64-bit sortable IDs with no central service on the hot path.
Information leak. IDs reveal creation time and roughly how many IDs a machine issues; do not use them where that matters, or scramble them for public display.
By level
Fresher: Explain how the ID is built from time, machine number and a counter, and why that makes IDs unique. A fresher should compute how many IDs fit in one millisecond.
Mid: Do the field arithmetic, handle clock moving backwards, and explain machine ID leasing. Compare with UUIDs.
Senior: Discuss clock monitoring, lease safety, information leakage, UUIDv7 and index locality, and multi-region assignment of machine bits. Expect clear limits on ordering guarantees.
Key points
41 bits time, 10 bits machine, 12 bits sequence
No coordination per ID; only machine IDs are assigned
4,096 IDs per millisecond per generator
About 69 years of time bits from a custom epoch
Refuse or wait when the clock goes backwards
Common mistakes
Using a single auto-increment database as the generator at 1M per second
Ignoring clock moving backwards
Hard-coding machine IDs that can be duplicated by autoscaling
Claiming the IDs are strictly ordered across machines
Follow-ups
How would you assign machine IDs in a Kubernetes cluster?
When would you choose UUIDv7 instead?
How do you hide creation time from public IDs?
Tips
Draw the 64-bit layout
Compute the limits of each field
Mention clock skew handling
Evaluation rubric
Correct bit layout and limits
Explains uniqueness across machines
Clock and machine ID failure handling
Compares with alternatives
76.system-design-0076Easyfresher
Design a Pastebin-style service where users store text snippets and share them with a link, with optional expiry, for 1 million new pastes per day.
Generate a short random key for each paste, store the text in object storage (or a key-value store for small pastes) and the metadata in a database, and serve reads through a cache and CDN. Expiry is handled by a TTL or a cleanup job. The load is small (about 12 writes and 116 reads per second), so the design focuses on clean storage choices, expiry and abuse control.
Full answer
Requirements
Functional:
Create a paste (text up to 1 MB) and get a link such as https://paste.example/k7Hq2x.
Read a paste by link; optional expiry (10 minutes to never) and "burn after reading".
Optional syntax highlighting and private pastes.
Non-functional:
Reads are fast and highly available.
Keys are hard to guess so private pastes are not discovered.
Expired pastes stop being served promptly.
Capacity estimates
Assumptions: 1M new pastes per day, 10 reads per paste on average, 10 KB average size, 5 years of retention for pastes that do not expire.
Writes: 1M / 86,400 = about 12 per second.
Reads: 10M / 86,400 = about 116 per second.
Storage: 1M x 10 KB = 10 GB per day, about 18.25 TB over 5 years.
Key space: 8 base62 characters give 62^8, about 218 trillion keys, so random keys rarely collide.
API
POST /v1/pastes {"content": "...", "language": "python", "expires_in": "1d", "visibility": "unlisted"}
-> 201 {"key": "k7Hq2x9P", "url": "https://paste.example/k7Hq2x9P"}
GET /v1/pastes/{key} -> {"content", "language", "created_at", "expires_at"}
GET /{key} -> HTML page
DELETE /v1/pastes/{key} (owner only)
Content: object storage at pastes/{key}, or inline in the row if under a few KB.
High-level design
mermaid
flowchart LR
U[User] --> CDN[CDN for public pastes]
CDN --> API[Paste API]
API --> C[(Cache)]
API --> DB[(Metadata DB)]
API --> OS[(Object storage)]
J[Expiry job] --> DB
J --> OS
Key generation and expiry
Generate 8 random base62 characters from a cryptographically secure random source and insert with "only if the key does not exist"; on the rare collision, try again. Random keys (rather than counters) make links hard to guess.
Expiry: reads check expires_at and return 404 if passed, so expired pastes are never served even before cleanup. A daily job (or the store's native TTL) deletes expired rows and objects. Burn-after-reading pastes are deleted in the same request that returns them, with a conditional delete so two simultaneous readers cannot both see it.
Bottlenecks and trade-offs
Small load. A single region with a replicated database and object storage is enough; avoid over-engineering.
Caching. Public pastes are cached at the CDN with a TTL no longer than their remaining lifetime; private ones are never cached at shared layers.
Abuse. Rate limit paste creation per IP, scan for leaked credentials and malware, and support takedown requests.
Inline versus object storage. Inline storage is simpler and faster for small pastes; object storage is cheaper for large ones. A size threshold uses both.
Analytics such as view counts are written asynchronously so reads stay fast.
By level
Fresher: Sketch the create and read APIs and a table with key, content location and expiry time. A fresher should explain why random keys are safer than counting numbers.
Mid: Do the math, choose inline or object storage by size, handle expiry on read and in the background, and cache safely. Mention burn after reading.
Senior: Discuss abuse and secret scanning, viral pastes, privacy with caches, retention policy and right-sizing the design. Expect restraint about complexity.
Key points
Random 8-character base62 keys with a collision check
Metadata in a database, content in object storage or inline
Check expiry on read and clean up in the background
Cache public pastes at the CDN, never private ones
Load is small: about 12 writes and 116 reads per second
Common mistakes
Using sequential IDs that make private pastes guessable
Relying only on a cleanup job so expired pastes are still served
Caching private pastes at a CDN
Designing a large distributed system for 12 writes per second
Follow-ups
How would you add editing with version history?
How do you handle a paste that goes viral?
How would you detect leaked passwords in pastes?
Tips
Size it honestly; it is small
Explain why keys are random
Show how expiry works on the read path
Evaluation rubric
Correct capacity math
Sensible key generation
Expiry and burn-after-read handled
Caching and abuse considerations
77.system-design-0077Mediummid
Design the backend for a real-time multiplayer game with 1 million concurrent players in 100-player matches, including matchmaking and authoritative game servers.
Matchmaking groups players by skill and region and assigns each match to a dedicated, authoritative game server process. Clients send inputs over UDP; the server simulates the world at a fixed tick rate (for example 30 per second) and sends state snapshots with delta compression and interest management, so each player only receives nearby entities. Clients predict their own movement and the server reconciles. 1 million players in 100-player matches means 10,000 concurrent matches.
Full answer
Requirements
Functional:
Players queue for a match; matchmaking finds 100 players of similar skill and low latency.
During the match, every player sees others move and shoot in near real time; the server decides hits.
After the match, results update ranks and rewards.
Non-functional:
Round-trip latency under about 80 ms for most players; tolerate packet loss.
Cheating is hard: clients cannot decide outcomes.
A crashed game server affects only its own match.
Capacity estimates
Assumptions: 1M concurrent players, 100 per match, 30 ticks per second, 20 bytes per entity update after delta compression, each player receiving updates for about 20 nearby entities.
Matches: 1M / 100 = 10,000 concurrent.
Naive snapshots (every player gets all 100 players at 100 bytes, 30 times a second): 100 x 100 x 30 x 100 bytes = 30 MB per second per match, too much.
With interest management and deltas: 100 players x 20 entities x 30 ticks x 20 bytes = 1.2 MB per second per match, about 10 Mbps.
If one host runs about 20 matches, that is about 500 hosts across regions.
API
POST /v1/matchmaking/tickets {"mode": "battle-royale", "region_pings": {"ap-south": 32, "ap-southeast": 71}}
-> {"ticket_id"}
GET /v1/matchmaking/tickets/{id} -> {"status": "MATCHED", "server": "203.0.113.7:7777", "token": "..."}
UDP client -> server: {seq, input bits, aim, client_time} server -> client: {tick, ack_seq, delta snapshot}
POST /v1/matches/{id}/results (game server -> backend, signed)
Data model
players: player_id, skill rating, region, inventory (in a normal database).
Matchmaking queues in memory (Redis or the matchmaker's own state), keyed by mode and region.
matches: match_id, server address, players, started_at, result.
Game state lives only in the game server's memory during the match.
High-level design
mermaid
flowchart LR
C[Game client] --> API[Backend API]
API --> MM[Matchmaker]
MM --> FL[Fleet manager]
FL --> GS[Dedicated game server]
C -- "UDP inputs and snapshots" --> GS
GS -- "signed results" --> API
API --> DB[(Players, ranks, inventory)]
Game loop
Every tick (33 ms at 30 Hz) the server:
Applies the inputs received from each player.
Simulates movement and physics; resolves hits with lag compensation (rewinding other players' positions to what the shooter saw).
Sends each player a snapshot of what changed among entities relevant to them, as a delta against the last snapshot that player acknowledged.
Clients predict their own movement immediately and interpolate others between snapshots, then correct when the server's state differs. UDP is used because a late position update is useless; resending it (as TCP would) only adds delay.
Bottlenecks and trade-offs
Matchmaking trades wait time against match quality: widen the skill range and region over time while a ticket waits.
Tick rate. Higher rates feel better but cost CPU and bandwidth linearly; 20 to 60 Hz is typical depending on the genre.
Authority. The server decides outcomes; client prediction keeps it responsive. Lag compensation helps shooters but can let a target be hit "behind a wall" from their own view.
Fleet scaling. Pre-warm servers ahead of peak hours; matches cannot move between hosts, so draining a host means waiting for its matches to end.
Cheating. Server authority stops speed and teleport hacks; aim bots need separate detection from behaviour data.
By level
Fresher: Explain matchmaking, a server per match and why the server, not the player's device, decides who wins. A fresher should know the server updates the game many times per second.
Mid: Do the bandwidth math, explain UDP, tick loops, delta snapshots and interest management, and describe client prediction. Mention fleet sizing.
Senior: Discuss lag compensation trade-offs, tick rate economics, fleet draining, matchmaking expansion policies and cheat detection. Expect precise reasoning about what happens each tick.
Key points
Matchmaking by skill and region, then a dedicated authoritative server per match
UDP inputs and fixed tick simulation
Delta snapshots and interest management cut bandwidth from 30 MB to 1.2 MB per second per match
Client prediction and server reconciliation
10,000 concurrent matches for 1 million players
Common mistakes
Letting clients report hits or positions as truth
Using TCP and suffering head-of-line delays
Sending full world state to every player each tick
Ignoring region latency in matchmaking
Follow-ups
How does lag compensation work?
How would you handle a game server crash mid-match?
How do you scale matchmaking for many modes and regions?
Tips
Do the naive versus optimised bandwidth math
Explain the tick loop step by step
Separate matchmaking, game servers and the persistent backend
Evaluation rubric
Clear architecture with authoritative servers
Correct bandwidth reasoning
Latency techniques: prediction, interpolation, lag compensation
Matchmaking and fleet trade-offs
78.system-design-0078Easyfresher
Design a learning platform like Schoolabe or Coursera with video lessons, quizzes and progress tracking for 2 million daily learners.
Serve course pages and videos through a CDN (videos are transcoded into adaptive bitrate segments ahead of time), keep courses, enrolments, progress and quiz attempts in a relational database, and grade quizzes on the server. Progress events from the player are batched. The two load points are video bandwidth (about 300 Gbps for 200,000 concurrent viewers) and quiz submissions at the end of timed tests (about 830 per second when 50,000 students submit within a minute).
Full answer
Requirements
Functional:
Browse courses, enrol, watch video lessons, resume where you stopped.
Take quizzes (multiple choice and short answer), some timed; see scores.
Instructors upload videos and create quizzes; learners see a progress bar and certificates.
Non-functional:
Videos start quickly and adapt to slow mobile networks.
Quiz answers are never lost, even at the deadline rush.
Correct answers are not exposed to the browser before submission.
Capacity estimates
Assumptions: 2M daily learners, 200,000 concurrent video viewers at peak, 1.5 Mbps average bitrate, a timed test where 50,000 students submit in the final minute.
Video egress: 200,000 x 1.5 Mbps = 300 Gbps at peak, served by a CDN.
Quiz rush: 50,000 / 60 = about 830 submissions per second.
Progress events: if each viewer sends one heartbeat every 30 seconds, 200,000 / 30 = about 6,700 per second, which is why they are batched.
API
GET /v1/courses/{id} -> outline with lessons and the learner's progress
GET /v1/lessons/{id}/playback -> {"manifest_url": "https://cdn.../master.m3u8?token=..."}
POST /v1/progress {"lesson_id", "position_s": 312, "completed": false} (batched by the client)
POST /v1/quizzes/{id}/attempts -> {"attempt_id", "questions": [...without answers], "ends_at"}
PUT /v1/attempts/{id}/answers {"q1": "B", "q2": "C"} (autosave)
POST /v1/attempts/{id}/submit -> {"score": 8, "max": 10}
flowchart LR
L[Learner] --> CDN[CDN: pages and video segments]
L --> API[Learning API]
API --> DB[(Courses, progress, attempts)]
API --> Q[(Progress event queue)]
Q --> W[Progress workers] --> DB
I[Instructor] --> UP[Upload service] --> OS[(Object storage)]
OS --> TC[Transcoder] --> OS
OS --> CDN
Key flows
Video. Instructor uploads go to object storage; a transcoder creates 240p to 1080p HLS renditions; the player requests a signed manifest so only enrolled learners can watch.
Progress. The player sends heartbeats, batched every 30 seconds; workers upsert lesson_progress. Losing one heartbeat only loses a few seconds of position.
Quizzes. Answers autosave during the attempt. The server enforces ends_at (with a small grace period) and grades on submit using the stored correct answers. A submission is idempotent per attempt, so a retry after a network error does not create a second attempt.
Bottlenecks and trade-offs
Deadline rush. Autosave spreads writes across the test, so the final submit is a small update; the queue can absorb grading if it is heavier (for example code questions).
Video cost. Most cost is CDN bandwidth; offer lower default quality on mobile data and download for offline viewing.
Cheating in timed tests. Randomise question order and options, draw from question pools, and keep answers server-side.
Monolith first. At this scale a well-structured monolith with a relational database, a CDN and a transcoding service is enough; split services only when teams or load require it.
By level
Fresher: Describe courses, lessons, progress and quiz tables, and explain that videos come from a CDN. A fresher should know why correct answers stay on the server.
Mid: Do the bandwidth and rush math, batch progress events, design autosave and idempotent submission, and sign video URLs. Mention transcoding.
Senior: Discuss cost control for video, cheating defences, coding sandboxes, certificates, and when to split the monolith. Expect a design sized to the real load.
Key points
CDN for pages and pre-transcoded video
Relational database for courses, enrolments, progress and attempts
Batch progress heartbeats
Autosave answers and grade on the server; never send correct answers
Idempotent quiz submission per attempt
Common mistakes
Sending correct answers to the browser
Writing a database row for every second of video watched
Accepting submissions after the deadline without server-side checks
Streaming video from the application servers
Follow-ups
How would you add coding exercises that run in a sandbox?
How would you issue verifiable certificates?
How do you support offline viewing on phones?
Tips
Identify video bandwidth and deadline rush as the two load points
Explain autosave
Keep the architecture simple for the scale
Evaluation rubric
Correct video delivery design
Capacity math for video, progress and quizzes
Secure, idempotent quiz handling
Sensible simplicity and trade-offs
79.system-design-0079Mediummid
Add personalisation to a search autocomplete service: suggestions must reflect each user's own recent searches and interests while still returning in under 50 ms.
Keep the global top-k suggestions per prefix precomputed (as in a standard typeahead), and add a small per-user layer: the user's recent queries and topic interests stored in a fast key-value store. At request time, fetch the global candidates for the prefix and the user's matching history in parallel, merge them with a lightweight ranking function, and return the top 10. Personal history for 50 million users is about 150 GB, small enough for an in-memory cluster.
Full answer
Requirements
Functional:
As a user types, return up to 10 suggestions that include their own recent matching searches and items related to their interests, plus popular global suggestions.
Users can delete their history or turn personalisation off.
Non-functional:
p99 latency under 50 ms per keystroke request.
New searches appear in that user's suggestions within seconds.
Privacy: one user's history never appears in another user's suggestions.
Capacity estimates
Assumptions: 50M daily users, 10 searches per user per day, 5 suggestion requests per search (after debouncing), peak factor 3, 100 recent queries kept per user at about 30 bytes each.
Requests: 50M x 10 x 5 / 86,400 = about 28,900 per second; about 86,800 per second at peak.
Personal history: 50M x 100 x 30 bytes = 150 GB, which fits in a replicated in-memory store.
The global prefix index is already sized by the base typeahead design and is shared by all users.
API
GET /v1/suggest?q=mach&limit=10 (user from session token)
-> [{"text": "machine learning course", "source": "history"}, {"text": "machine design", "source": "global"}]
DELETE /v1/me/search-history
PUT /v1/me/settings {"personalised_suggestions": false}
Data model
Global: prefix to top 50 candidate completions with scores (trie snapshot or prefix table), as in the base design.
user_history:{user_id}: Redis sorted set of recent queries scored by last-used time, capped at 100.
user_interests:{user_id}: small vector or list of topic weights (for example "python": 0.8, "system design": 0.6), updated by a batch job.
Candidate topic labels for global completions (computed offline).
High-level design
mermaid
flowchart LR
U[Client] --> S[Suggest service]
S --> G[(Global prefix index)]
S --> H[(User history store)]
S --> I[(User interests)]
S --> RK[Merge and rank]
U -- "search submitted" --> LOG[(Search log)]
LOG --> HU[History updater] --> H
LOG --> BATCH[Daily interest job] --> I
Ranking at request time
In parallel: get the top 50 global candidates for the prefix; get the user's history entries that start with the prefix (a scan of at most 100 short strings).
Score each candidate: score = a x global_popularity + b x recency_of_user_use + c x interest_match(topic), with weights tuned offline from click data.
Remove duplicates, apply safety filters, return the top 10, usually with at most 3 or 4 history items so popular results still appear.
If the personal stores are slow or unavailable, return global results only; personalisation must never break the base feature.
Bottlenecks and trade-offs
Latency budget. Parallel fetches with tight timeouts (for example 10 ms for the personal store) and a fallback keep the p99 within 50 ms.
Freshness versus cost. History updates are near real time (append to a sorted set); interest vectors update daily in batch because they change slowly.
Caching. Global results per prefix cache well; personalised results do not, which is why the personal layer is kept tiny and fast.
Privacy. Delete requests must remove history from the store and from the training data path; personal entries must be shown only to their owner and only when signed in.
Filter bubbles. Too much personal weight hides useful new suggestions; cap personal items per response.
By level
Fresher: Explain that the service mixes popular suggestions with the user's own recent searches. A fresher should describe storing a short list of recent searches per user.
Mid: Design parallel fetches, a scoring formula and capped history, do the capacity math and set a fallback. Explain why personal results do not cache well.
Senior: Discuss latency budgets, evaluation with click data, privacy and deletion, signed-out personalisation and filter bubbles. Expect a clear failure mode plan.
Key points
Keep the global top-k per prefix and add a small per-user layer
Fetch global candidates and user history in parallel
Lightweight linear ranking with tuned weights
Fall back to global results if personal stores are slow
Leaking one user's history to others through shared caches
Follow-ups
How would you personalise for signed-out users?
How do you evaluate whether personalisation helps?
How would you handle history deletion requests?
Tips
Reuse the base typeahead design and add a layer
Show the latency budget split
Mention privacy controls early
Evaluation rubric
Clear layering of global and personal data
Capacity math
Ranking and fallback within the latency budget
Privacy and freshness trade-offs
80.system-design-0080Easyfresher
Design a feature flag service that lets teams turn features on for a percentage of users or specific groups, with SDKs that evaluate flags locally in microseconds.
Store flag definitions (targeting rules, percentages, allow and deny lists) in a database edited through an admin UI. SDKs inside each service download the full rule set at start-up, keep it in memory, receive changes over a streaming connection, and evaluate flags locally with a stable hash of flag key and user ID, so a user always lands in the same bucket. No network call happens per evaluation; the rule set for 2,000 flags is only about 2 MB.
Full answer
Requirements
Functional:
Create flags with rules: on or off, percentage rollout, rules by attribute (country, plan), allow and deny lists.
Change a flag and have it take effect in all services within seconds.
Audit log of who changed what, and a quick kill switch.
Non-functional:
Evaluation adds microseconds, not network round trips.
If the flag service is down, applications keep running with the last known rules.
A user sees the same variant consistently.
Capacity estimates
Assumptions: 2,000 flags at about 1 KB each, 50,000 application instances running the SDK, 1M flag evaluations per second across all services.
Rule set: 2,000 x 1 KB = 2 MB, held in memory by every SDK.
Streaming connections: 50,000, one per instance, spread across a few relay servers.
Evaluations: 1M per second, but all local, so the service sees zero evaluation traffic.
API
Admin:
PUT /v1/flags/new-quiz-ui {"default_percent": 10, "rules": [{"attr": "country", "in": ["IN"], "percent": 50}],
"allow": ["u_qa"], "deny": []}
SDK:
GET /v1/sdk/rules -> full rule set with version
GET /v1/sdk/stream (Server-Sent Events: {"version": 812, "changed": {...}})
In code: flags.is_enabled("new-quiz-ui", user)
flag_audit: flag key, old rules, new rules, who, when.
SDK cache: version plus the full rule set, also written to local disk so a restart without the service still works.
High-level design
mermaid
flowchart LR
ADM[Admin UI] --> FS[Flag service]
FS --> DB[(Flags and audit DB)]
FS --> PUB[(Change stream)]
PUB --> RL[Stream relays]
RL -- "SSE" --> SDK1[SDK in service A]
RL -- "SSE" --> SDK2[SDK in service B]
SDK1 -. "start-up fetch" .-> CDN[CDN copy of rule set]
Evaluation
python
import hashlib
def bucket(flag_key, user_id):
"""Stable bucket 0..9999 for a user and flag: same answer on every server."""
digest = hashlib.sha256(f"{flag_key}:{user_id}".encode()).digest()
return int.from_bytes(digest[:8], "big") % 10_000
def is_enabled(flag, user):
if user["id"] in flag.get("deny", ()):
return False
if user["id"] in flag.get("allow", ()):
return True
for rule in flag.get("rules", ()): # first matching rule wins
if user.get(rule["attr"]) in rule["in"]:
return bucket(flag["key"], user["id"]) < rule["percent"] * 100
return bucket(flag["key"], user["id"]) < flag["default_percent"] * 100
if __name__ == "__main__":
flag = {"key": "new-quiz-ui", "default_percent": 10, "allow": {"u_qa"},
"rules": [{"attr": "country", "in": {"IN"}, "percent": 50}]}
users = [{"id": f"u{i}", "country": "IN" if i % 2 else "US"} for i in range(20_000)]
on_in = sum(is_enabled(flag, u) for u in users if u["country"] == "IN") / 10_000
on_us = sum(is_enabled(flag, u) for u in users if u["country"] == "US") / 10_000
assert 0.48 < on_in < 0.52 and 0.08 < on_us < 0.12
assert is_enabled(flag, {"id": "u_qa", "country": "US"})
assert all(is_enabled(flag, u) == is_enabled(flag, u) for u in users[:100]) # stable
print(f"ok: IN {on_in:.3f}, US {on_us:.3f}")
Save as rollout.py and run python3 rollout.py (Python 3.13.5).
Hashing flag_key:user_id keeps each user in the same bucket across servers and restarts; including the flag key means a user who is in the first 10% of one flag is not automatically in the first 10% of every flag. Raising a rollout from 10% to 20% keeps the original 10% enabled, because their buckets are still below the new threshold.
Bottlenecks and trade-offs
Local evaluation versus server-side evaluation. Local is fast and resilient but ships all rules to every service; for browser and mobile clients, evaluate on the server and send only the results, so rules and user lists are not exposed.
Propagation. Streaming gives updates in seconds; polling every 30 seconds is simpler and also acceptable for many teams.
Stale rules during an outage are safe if defaults are safe; every flag needs a sensible fallback value in code.
Flag debt. Old flags make code hard to follow; track owners and expiry dates and alert on flags unchanged for months.
Experiments reuse the same bucketing but need exposure logging, which is sent asynchronously and sampled if needed.
By level
Fresher: Explain that services download flag rules and check them in memory, and that a hash keeps each user in the same group. A fresher should describe a percentage rollout.
Mid: Design storage, streaming updates, the SDK cache and stable bucketing, and show how rollouts grow without flipping users. Handle outages with defaults.
Senior: Discuss server-side evaluation for clients, experiments and exposure logging, propagation guarantees, flag debt and audit. Expect clear reasoning about failure modes.
Key points
SDKs hold the full rule set in memory and evaluate locally
Stable hash of flag key and user ID for percentage rollouts
Streaming updates with a disk cache for restarts
Safe defaults in code for outages
Server-side evaluation for browser and mobile clients
Common mistakes
Calling the flag service over the network on every evaluation
Using random numbers per request, so users flip between variants
Hashing only the user ID, so the same users get every early rollout
Shipping full rules with user lists to browsers
Follow-ups
How would you run an A/B test with this service?
How do you make a kill switch take effect within one second?