Practice · interactive
Design Lab
Pick a scenario, drag components onto the canvas and connect them. Then check your design: you'll get a rank, what you got right, what's missing and why, and the design an interviewer would hope to see.
See it in action: sizing
A photo-sharing app is about to hit its daily peak. Watch what the right sizing, and the wrong one, does to it.
Traffic–
p99 latency–
Errors–
Cost / month–
Press a button above: one run where it goes well, one where it goes wrong.
The brief
- A photo-sharing site growing from 1k to 1M daily users.
- Reads outnumber writes 50 : 1; photos are a few MB each.
- It must keep working when any single server dies.
The brief
- Turn long URLs into short codes and redirect anyone who opens one.
- 100M new URLs a month, read 100× more often than written.
- Redirects must be fast (under ~50 ms) and links must never break.
Full walkthrough: URL shortener (try the lab first!)
The brief
- Limit each API client to, say, 100 requests per minute, across dozens of gateway servers.
- Adds at most a millisecond or two to each request.
- Over-limit requests get 429 Too Many Requests.
Full walkthrough: Distributed rate limiter (try the lab first!)
The brief
- One-to-one and group chat with real-time delivery, like WhatsApp.
- 50M daily users, ~2B messages a day; history kept forever.
- Offline users get a push notification.
Full walkthrough: Chat system (try the lab first!)
The brief
- Users post; followers see a home timeline of recent posts.
- 200M daily users; timelines are read far more than posts are written.
- Timeline loads must be fast; a post can take a few seconds to appear.
Full walkthrough: News feed (like X / Twitter) (try the lab first!)
The brief
- Creators upload videos; viewers stream them smoothly on any connection.
- 500k uploads a day; at peak, millions of concurrent viewers.
- Videos can take a few minutes to become watchable.
Full walkthrough: Video streaming (like YouTube) (try the lab first!)
The brief
- Riders request rides; the system matches them with nearby available drivers.
- 1M active drivers send their location every 4 seconds.
- A driver must never be assigned to two rides at once.
Full walkthrough: Ride sharing (like Uber) (try the lab first!)
The brief
- Crawl 1 billion pages a month for a search index.
- Be polite: obey robots.txt, and never hammer one site.
- Don’t fetch the same URL twice.
Full walkthrough: Web crawler (try the lab first!)
The brief
- Any service can send push, SMS or email to users.
- 10M notifications a day, with bursts of millions during campaigns.
- Respect user preferences; one-time codes must never be delayed by marketing.
Full walkthrough: Notification system (try the lab first!)
The brief
- Suggest the top completions as someone types, like a search box.
- 5B suggestion requests a day; each answer in under 100 ms.
- Suggestions can be a day old (plus trending terms).
Full walkthrough: Search autocomplete (try the lab first!)
The brief
- Keep files in sync across a user’s devices; share folders.
- 50M users, ~10 GB each; small edits to big files shouldn’t re-upload everything.
- Never lose a file; never show a half-synced one.
Full walkthrough: File sync (like Dropbox) (try the lab first!)
Components
Drag onto the canvas, or tap to add.
Drag components here.
Then pull from a box's ● handle to another box to connect them.
Capacity calculator
How big does this design need to be? Set the traffic and the work each request does; the calculator sizes the servers, load balancers, database, cache and workers. It reads your canvas too: the database and load balancer you picked, and whether there's a cache.
Your estimate first
How many of each will this design need at peak? Guess, then reveal. Way too many and it blasts (wasted money); way too few and it melts down (overloaded).
The best design: Scale a web app to 1M users
- Users get static files and photos from the CDN and API calls through the load balancer.
- Stateless app servers behind the balancer scale out and survive single failures.
- Cache-aside in front of the database absorbs the 50 : 1 read load; read replicas add more.
- Photos live in object storage; the database only stores their keys.
Trade-offs: nothing here is free
Cache-aside in front of the database
You gainThe app decides what to cache; a cache outage degrades speed, not correctness.
You payReaders can see stale data until the key is deleted or expires, so every write must invalidate the key.
Asynchronous read replicas
You gainCheap read capacity and a warm standby.
You payReplication lag: a user can post a comment and not see it on refresh. Read a user's own recent writes from the primary for a few seconds.
One SQL primary
You gainTransactions, joins and simple operations.
You payA write ceiling around 5k/s. Fine at 1M users; plan the shard key before you need it.
Failure modes and edge cases
| What goes wrong | What happens | How the design copes |
|---|---|---|
| The primary dies | Writes fail until a replica is promoted (about 30 s). | Automatic failover. With async replication, the last fraction of a second of writes can be lost. |
| A cache node restarts empty | Every key misses at once and the database gets a stampede. | Request coalescing (one refill per key), jittered TTLs, and warming the cache before taking traffic. |
| A photo goes viral | Millions of requests for one object. | The CDN serves it; an origin shield turns thousands of edge misses into one origin request. |
| A bad deploy | Errors spike across the stateless tier. | Canary releases, health checks that pull bad servers, and instant rollback. |
Go deeper
Load balancing →Scaling basics →SQL vs NoSQL →Caching →Blob storage →CDNs →
The best design: URL shortener
- A load balancer fronts separate shorten and redirect paths.
- Redirects are a cache-aside lookup; most hit Redis and never touch the store.
- A key-value store (replicated) holds billions of code → URL rows.
- An ID generator hands out unique codes; clicks go to a queue for analytics.
Trade-offs: nothing here is free
301 vs 302 redirects
You gain301 is cached by browsers: less load.
You payYou lose click analytics. Use 302 if analytics matter.
Counter + base62 codes
You gainNo collisions and no lookups to check uniqueness.
You payCodes are guessable in order; shuffle the number (a bijective mix) before encoding.
Key-value store over SQL
You gainScales to billions of rows by partitioning on the code.
You payNo joins or ad-hoc queries; analytics go to a separate store.
Failure modes and edge cases
| What goes wrong | What happens | How the design copes |
|---|---|---|
| A link goes viral (hot key) | One cache shard and one store partition take all the traffic. | Replicate hot keys across cache nodes and add a small in-process cache on each server. |
| The ID generator is down | New links can't be created. | Each server leases a block of IDs in advance and keeps working through short outages. |
| A link is deleted for abuse | Caches and browsers keep redirecting. | Delete the cache key, purge the CDN, and prefer 302 for links you may need to kill. |
Go deeper
The best design: Distributed rate limiter
- The limiter lives in the API gateway, so bad traffic is stopped before it reaches services.
- Counters sit in Redis, updated atomically with a Lua script so gateways never race.
- Rules come from a config service and are cached in each gateway.
Trade-offs: nothing here is free
Token bucket vs sliding window
You gainToken bucket allows short bursts and is cheap.
You paySliding windows are smoother and more exact but cost more memory or maths.
Central Redis counters
You gainOne exact count across all gateways.
You payAn extra network hop (~1 ms) and a dependency that can fail.
Fail open vs fail closed
You gainOpen keeps the API up if Redis dies.
You payIt also turns off protection. Close it for login and payment endpoints.
Failure modes and edge cases
| What goes wrong | What happens | How the design copes |
|---|---|---|
| Redis is unreachable | Limits can't be checked. | Fail open for normal endpoints, closed for sensitive ones, with a local in-memory fallback limit. |
| One huge client (hot key) | All its checks land on one Redis shard. | A local pre-limiter per gateway, so only near-limit traffic consults Redis. |
| Multi-region traffic | Per-region counters allow N× the limit globally. | Accept it, split the limit across regions, or sync counters asynchronously. |
Go deeper
The best design: Chat system
- Realtime gateways hold a connection per device; a session registry knows who is where.
- The chat service persists each message (wide-column store, partitioned by conversation) before acking.
- Offline users get push notifications.
Trade-offs: nothing here is free
Wide-column store for messages
You gainBillions of appends a day, partitioned by conversation, read in order.
You payNo joins or full-text search; search needs a separate index.
At-least-once delivery
You gainNo message is lost when a connection drops.
You payDuplicates on retry, so clients send a message ID and the server dedupes.
Push to each member on send (small groups)
You gainInstant delivery and simple reads.
You payHuge groups multiply writes; very large channels switch to members pulling the latest messages.
Failure modes and edge cases
| What goes wrong | What happens | How the design copes |
|---|---|---|
| Messages arrive out of order | Two senders, client clocks that disagree, or a retry make messages race. | The server assigns a per-conversation sequence number; clients sort by it and fetch any gap they detect. |
| Replication lag | A message is written to one replica; the recipient's history read hits a replica that hasn't caught up, so the message seems missing. | Write and read history at quorum (W + R > N), or read from the partition leader; tolerate lag only for counters like unread badges. |
| A hot partition during a viral event | A live event's chat or a 100k-member group pins one partition, so one node melts while others idle. | Partition by (conversation, time bucket), cap group size, and move very large rooms to a broadcast/fan-out tier. |
| A gateway crashes | Its 50k connected users all reconnect at once (a reconnect storm). | Jittered backoff, and resuming from each device's last sequence number instead of a full resync. |
Go deeper
APIs & real-time →Scaling basics →SQL vs NoSQL →Caching →Notification system walkthrough →
The best design: News feed (like X / Twitter)
- Posting puts an event on a queue; fan-out workers push the post ID into followers’ timeline caches.
- Reading a timeline is one cache read, then a batch lookup to hydrate posts.
- Celebrities are the exception: their posts are merged in at read time (hybrid fan-out).
Trade-offs: nothing here is free
Fan-out on write
You gainA timeline load is one cache read.
You payWrite amplification: one post becomes a write per follower.
Hybrid for celebrities
You gainAvoids 100M writes per celebrity post.
You payReads get a merge step and more code paths to test.
Capped timelines in Redis (~800 IDs)
You gainBounded memory per user.
You payDeep scrolling falls back to slower queries.
Failure modes and edge cases
| What goes wrong | What happens | How the design copes |
|---|---|---|
| A celebrity posts | Fan-out workers fall behind for everyone. | Skip fan-out above a follower threshold and merge their posts at read time. |
| The timeline cache cluster is lost | Every load rebuilds from the database at once. | Replicas for the cache, rebuild timelines lazily, and shed load for inactive users. |
| A post is deleted or a user is blocked | Precomputed timelines still contain the ID. | Filter at read time when hydrating posts. |
Go deeper
Load balancing →Scaling basics →Queues & streams →Caching →SQL vs NoSQL →
The best design: Video streaming (like YouTube)
- Uploads go straight to object storage; a queue triggers parallel transcoding workers.
- Viewers stream segments from the CDN, which pulls from storage on a miss.
- Metadata (status, renditions) lives in a database; the bytes never touch app servers.
Trade-offs: nothing here is free
Transcode every rendition up front
You gainFast starts and smooth quality switching.
You payStorage for renditions nobody watches; transcode the long tail on demand.
2–6 s segments
You gainQuick adaptation to bandwidth changes.
You payMore requests and manifest overhead than longer segments.
Pull CDN with an origin shield
You gainSimple, and popular videos cache themselves.
You payThe first viewer in each region pays a miss; pre-warm for premieres.
Failure modes and edge cases
| What goes wrong | What happens | How the design copes |
|---|---|---|
| A transcode worker crashes | One chunk isn't encoded. | Chunks are idempotent tasks on a queue and get retried. |
| A CDN region goes down | Viewers in that region buffer. | Multi-CDN with DNS steering to healthy edges. |
| A premiere starts (thundering herd) | Millions of first requests miss together. | Pre-warm edges, an origin shield, and collapsing identical requests. |
Go deeper
Scaling basics →Blob storage →Queues & streams →CDNs →SQL vs NoSQL →
The best design: Ride sharing (like Uber)
- Driver locations go to an in-memory geo index sharded by city: fast writes, nearest-driver queries.
- Matching reads the geo index and offers the ride to one driver at a time.
- Ride state lives in SQL with conditional updates, so a driver can’t be double-booked.
Trade-offs: nothing here is free
Locations in memory, not a database
You gain250k updates a second at microsecond cost.
You payLost on a crash, but rebuilt from the next round of pings within seconds.
Geohash cells
You gainSimple, prefix-based and easy to shard.
You payEdge effects: always search neighbouring cells too.
Strong consistency for assignment
You gainA driver can never get two rides.
You payA conditional write on every assignment, and some unavailability during partitions.
Failure modes and edge cases
| What goes wrong | What happens | How the design copes |
|---|---|---|
| Two riders match the same driver | A race at the moment of assignment. | Claim the driver with a conditional update (status = available) or a short lease. |
| A concert ends (hot cell) | One city shard gets thousands of requests at once. | Split dense cells, add replicas for that shard, and surge pricing to shape demand. |
| A driver's app goes offline | A stale location keeps getting offered rides. | Locations expire after a few missed pings. |
Go deeper
APIs & real-time →Load balancing →Scaling basics →Ride sharing walkthrough →SQL vs NoSQL →
The best design: Web crawler
- The URL frontier (queue) balances priority and per-host politeness.
- Fetchers obey robots.txt, store pages in object storage, and hand pages to parsers.
- A Bloom filter drops URLs already seen; only new ones return to the frontier.
Trade-offs: nothing here is free
Bloom filter for seen URLs
You gainAbout 1 byte per URL.
You payFalse positives: a few new URLs are wrongly skipped.
Priority over breadth-first
You gainImportant pages are fresh.
You payLow-priority pages may wait a long time.
Politeness per host
You gainSites don't block you.
You payBig sites take days to crawl at one request a second.
Failure modes and edge cases
| What goes wrong | What happens | How the design copes |
|---|---|---|
| A crawler trap (infinite calendar) | Endless URLs from one site. | Depth, URL-length and per-host page budgets. |
| A crawler node dies | Its hosts stop being crawled. | Durable frontier partitions reassigned to other nodes. |
| Mirrors and duplicate pages | Storage and work wasted. | Content checksums and SimHash for near-duplicates. |
Go deeper
The best design: Notification system
- One notification API checks preferences, then enqueues.
- Separate queues per channel (and per priority) isolate slow providers and protect one-time codes.
- Workers retry with backoff and record results; idempotency keys prevent duplicates.
Trade-offs: nothing here is free
At-least-once sending
You gainNothing is silently dropped.
You payPossible duplicates; idempotency keys and send records make them rare.
A queue per channel
You gainOne slow provider can't stall the others.
You payMore queues and workers to operate.
Priority queues
You gainOne-time codes never wait behind marketing.
You payLow priority can starve; give it a guaranteed share.
Failure modes and edge cases
| What goes wrong | What happens | How the design copes |
|---|---|---|
| A provider outage | One channel stops delivering. | A circuit breaker and a second provider per channel. |
| A worker crashes after sending | The message is redelivered and sent twice. | Check a send record keyed by (notification, channel) before sending. |
| A 50M-user campaign | Queues flood and provider rate limits hit. | Throttle to provider limits and spread sends over time. |
Go deeper
Scaling basics →Queues & streams →Notification system walkthrough →Caching →SQL vs NoSQL →
The best design: Search autocomplete
- The CDN answers popular prefixes; misses go to the suggest service.
- Suggestions come from an in-memory trie with top-k precomputed at every node.
- An offline aggregation job builds new trie snapshots from search logs.
Trade-offs: nothing here is free
Precomputed top-k in a trie
You gainLookups in microseconds.
You payMemory-heavy and stale until the next rebuild.
Daily rebuild + a trending layer
You gainCheap batch builds with fresh news.
You payTwo systems to merge and keep consistent.
Global suggestions, cached at the edge
You gainHuge cache hit rates.
You payPersonalisation breaks caching; merge per-user terms on the client.
Failure modes and edge cases
| What goes wrong | What happens | How the design copes |
|---|---|---|
| An offensive suggestion appears | Shown to millions immediately. | A runtime blocklist applied before responding, no rebuild needed. |
| A bad snapshot is loaded | Wrong suggestions everywhere. | Validate snapshots and keep the previous one for instant rollback. |
| A hot prefix | One trie shard overloaded. | Edge caching and extra replicas for that shard. |
Go deeper
The best design: File sync (like Dropbox)
- Clients split files into content-hashed chunks and upload only missing ones, directly to storage.
- The metadata service commits each version in a SQL transaction and appends to a change journal.
- A notification service tells other devices to fetch changes since their cursor.
Trade-offs: nothing here is free
Content-defined chunks
You gainSmall edits upload little; identical chunks are stored once.
You payMore CPU on the client to find chunk boundaries.
Strongly consistent metadata (SQL)
You gainNo corrupt or half-synced file trees.
You payHarder to scale; shard by namespace.
Conflicted copies instead of merging
You gainNever loses anyone's work.
You payUsers sometimes have to reconcile two files by hand.
Failure modes and edge cases
| What goes wrong | What happens | How the design copes |
|---|---|---|
| Two devices edit offline | Both commit against the same version. | The second commit gets a conflict and is saved as a conflicted copy. |
| An upload is interrupted | A partial file. | Nothing is committed until every chunk exists; uploads resume per chunk. |
| The notification service is down | Devices don't hear about changes. | Clients fall back to polling with backoff. |
Go deeper
Blob storage →SQL vs NoSQL →Scaling basics →APIs & real-time →