Summary#
Most system design problems are built from a small set of recurring sub-problems. Each has a well-known family of solutions, a pattern. There are eight that come up constantly:
- Real-time updates. Push changes to users as they happen.
- Dealing with contention. Many actors compete for the same scarce thing.
- Long-running tasks. Work too slow for a request/response cycle.
- Large blobs. Files too big to route through your servers.
- Scaling reads. Read traffic outgrows one database.
- Scaling writes. Write traffic outgrows one database.
- Multi-step processes. Flows that span services, failures and time.
- Proximity search. Find things near a location.
This guide teaches you how to:
- spot each pattern from signals in the problem: verbs, nouns, adjectives and, above all, numbers;
- climb each pattern's ladder from the simplest option to the most complex, only as far as the requirements force you;
- combine patterns without them undermining one another;
- recognise each pattern in the case studies.
The patterns are not mutually exclusive. A real system typically uses three to five of them at once.
Why It Exists#
An interview gives you 45 minutes for a problem that took a real company years. A real project gives you more time but more ambiguity. Either way, you can't derive every design decision from first principles under pressure. Experienced engineers don't try. They recognise the shape of the problem, recall the known solutions, and spend their thinking on the part that is genuinely new.
That recognition is much of what separates senior designers from junior ones. A junior candidate given "design Ticketmaster" draws boxes for users, events and tickets, then discovers the race on the last seat 30 minutes in, by accident. A senior candidate hears "many people want the same seat at the same moment" within the first minute. They name it as a contention problem and immediately know the menu:
- conditional writes;
- locks;
- optimistic concurrency;
- reservations with a TTL;
- a virtual waiting room.
They also know the classic failure modes: deadlocks, the hold that never expires, payment that completes after the hold has expired. The pattern doesn't make the decisions for them. It tells them which decisions matter, and which pitfalls to steer around, so they can spend their minutes on trade-offs instead of rediscovery.
Patterns also give you a shared vocabulary with interviewers and colleagues. "We'll handle uploads with presigned URLs and process them asynchronously, with a status the client polls" is one sentence, but it carries a lot of design, because everyone who knows the patterns can unpack it.
Three warnings belong right at the start:
- Patterns are tools, not trophies. Using a pattern the problem doesn't need is a red flag. Examples: a queue in front of a 50 ms operation, a WebSocket for data that changes daily, a workflow engine for a two-step flow.
- Patterns have ladders. Every pattern has a cheap first rung (polling, a database transaction, a status column, a read replica) and an expensive top rung (WebSocket gateways with pub/sub, distributed locks, durable execution engines, multi-tier caching with sharding). Start low and climb only when a stated requirement pushes you.
- Databases already solve many of these problems. Atomicity, isolation, indexes and replication are decades of engineering. Every time you split data across systems, you take some of those problems back. Splitting is sometimes right, but be deliberate about it.
How It Works#
Selection is a loop with four steps:
- Read signals from the requirements.
- Map each signal to a pattern.
- Choose a rung on each pattern's ladder, using the numbers.
- Check the combination for interference.
The table is the map, and the flowchart below is the same map as a quick triage.
| Pattern | Core problem | Typical signals | Bottom rung → top rung | Page |
|---|---|---|---|---|
| Real-time updates | Users must see changes without asking | "live", "instantly", "chat", "notifications", "presence", "collaborative" | Polling → long polling → SSE → WebSocket + pub/sub or consistent-hashed servers | Real-time Updates |
| Dealing with contention | Concurrent actors compete for one resource | "last seat", "bid", "inventory", "double booking", "exactly one winner" | DB constraint / conditional write → row locks or OCC → reservations with TTL → queue serialisation, waiting room | Dealing with Contention |
| Long-running tasks | Work takes longer than a request should | "encode", "generate report", "export", "crawl", "batch", "takes minutes" | Sync with timeout → queue + workers + job status → priority queues, DLQs, autoscaling | Long-Running Tasks |
| Large blobs | Bytes too big for app servers | "upload video/photos/files", "attachments", "download", "sync" | Proxy small files → presigned URLs → multipart/resumable + chunk dedupe + signed CDN | Handling Large Blobs |
| Scaling reads | Read QPS outgrows the database | "feed", "timeline", "profile views", "100:1 read/write", "viral", "hot key" | Indexes, denormalise → read replicas → cache (Redis, CDN) → hot-key replication, request coalescing | Scaling Reads |
| Scaling writes | Write QPS or volume outgrows one node | "events per second", "location updates", "clicks", "metrics", "logs", "likes" | Batch and tune → vertical partitioning → sharding → queue buffering, load shedding, aggregation | Scaling Writes |
| Multi-step processes | Flow spans services, failures, time | "order", "payment then shipping", "approval", "onboarding", "if it fails, refund" | Single-server orchestration → DB state machine → saga → workflow engine / durable execution | Multi-Step Processes |
| Proximity search | Find entities near a point | "nearby", "within 5 km", "closest driver", "map", "geofence" | Scan (small N) → DB geo extension (PostGIS, Redis GEO) → geohash/quadtree/S2/H3 sharded index | Geospatial Indexing |
Ask all eight questions, not just the first that fires. Most real systems trip several. The art lies in step 3, choosing a rung, and step 4, combining. The rest of this page covers both in depth.
Reading the problem: where signals hide#
Signals appear in four forms. Training yourself to scan for each is the core skill.
1. Verbs in the functional requirements. Each verb is a candidate operation, and its nature hints at a pattern:
| Verb | Typical pattern |
|---|---|
| upload, attach, stream, download | Large blobs |
| book, reserve, bid, buy, claim, match | Contention |
| transcode, generate, export, crawl, train, render | Long-running tasks |
| notify, chat, follow live, watch the score | Real-time updates |
| order, pay, refund, onboard, approve | Multi-step processes |
| find nearby, track on map, dispatch | Proximity (plus real-time) |
| view, browse, search, scroll the feed | Scaling reads |
| post, like, click, report location, emit metrics | Scaling writes |
2. Nouns that carry physics.
- "Video", "photo", "document", "backup" mean large bytes.
- "Ticket", "seat", "item in stock", "driver" are scarce, contended resources.
- "Location", "map", "restaurant near me" mean geospatial data.
- "Feed", "timeline", "leaderboard" mean read-heavy, precomputed views.
3. Adjectives and adverbs that define quality.
- "Instantly", "live", "real-time" push you toward real-time updates. Be careful: "real-time" in a product spec often means "within a few seconds", which polling can satisfy.
- "Exactly once", "never double-charge", "never oversell" point to contention plus idempotency.
- "Reliable even if a service is down" points to multi-step processes.
- "Globally", "low latency everywhere" point to CDN and replication, which are scaling reads.
- "Durable", "auditable" point to event logs and state machines.
4. Numbers, the most decisive signals. Translate every number into a load, using Back-of-the-Envelope Estimation.
- 100M daily active users × 20 feed views a day is about 23,000 reads/s on average, and perhaps 70,000/s at peak. That is far beyond one database's comfortable read capacity, so scaling reads is in play.
- 5M drivers sending a location every 4 s is 1.25M writes/s. That is far beyond any single database, so scaling writes is in play, and the hot data probably belongs in memory.
- 10,000 tickets and 2M people at 10:00:00 is a contention ratio of 200:1 at a single instant. You need contention handling and load shaping: a waiting room.
- An average upload of 300 MB means large blobs, with multipart.
- "Encoding takes about 1× real time" on a 1-hour video means long-running tasks.
If the interviewer gives no numbers, ask for them, or propose reasonable ones and confirm. The same functional spec at 1,000 users and at 100 million users calls for different rungs. See Requirements Gathering and Non-Functional Requirements.
The signal-to-pattern map#
For each pattern, here are the first question to ask, the escalation trigger that moves you up a rung, and the classic mistake. Learn these three per pattern, and you can navigate most problems.
| Pattern | First question | Escalate when | Classic mistake |
|---|---|---|---|
| Real-time | How fresh must it be, and who must see it? | Freshness under about 5 s at scale, or bidirectional low-latency traffic | WebSockets for data that changes hourly |
| Contention | What is the scarce unit, and how many actors compete at peak? | Hot rows, holds needed across user think-time, or a cross-shard resource | Distributed locks where a conditional UPDATE would do |
| Long tasks | How long does it take at p99, and does the user wait for it? | Work beyond a few seconds, or beyond HTTP and proxy timeouts | Queueing 50 ms work and losing back-pressure |
| Large blobs | How big are the files, and where are they read from? | Files beyond a few MB, flaky networks, global readers | Bytes through API servers, or blobs in the database |
| Scaling reads | What's the read QPS, ratio and hottest key? | Indexes exhausted and the DB near its read limit; global latency needs | Caching before fixing a missing index |
| Scaling writes | What's the write QPS, burstiness and partition key? | Sustained writes beyond one primary; bursts beyond buffer capacity | Sharding on a key that makes the hottest entity a hot shard |
| Multi-step | How many side effects, across how many services, over how long? | Steps crossing services, waits measured in minutes or longer, human steps | A workflow engine for a two-step flow, or in-memory orchestration of a 3-day flow |
| Proximity | How many entities, and how often do they move? | More than about 100,000 entities, or frequent location updates | A custom geo index for 1,000 shops |
The signal-to-pattern map, in depth#
Real-time updates. The signal is that users must learn about a change without asking. Examples: chat messages, live scores, a driver's car moving on the map, collaborative cursors, notification badges.
-
First question: how fresh, for whom, and at what fan-out? "Within a second, for the 2 people in a chat" is a different problem from "within 10 s, for 5 million viewers of a live stream".
-
The ladder:
- Short polling works fine at 5–30 s freshness and modest scale, and it needs nothing special.
- Long polling cuts empty responses.
- Server-Sent Events give one-way server push over plain HTTP, with automatic reconnect.
- WebSockets give bidirectional, low-latency traffic.
On the server side, the hard part is routing: how does the server holding user A's connection learn about an event produced elsewhere? There are two common answers:
- Pub/sub (for example sharded Redis Pub/Sub, or Kafka for durable streams). Every connection server subscribes to the channels of its connected users. This is used for chat and notification fan-out.
- Stateful servers assigned by consistent hashing, so that everyone editing document D lands on the same server, which holds D's state in memory. This is used for collaborative editing and game rooms, where processing is heavy and stateful.
-
Escalate to persistent connections when freshness targets are around a second or less, or when the client also sends frequently (games, collaborative editing). Escalate to dedicated connection infrastructure when connection counts reach hundreds of thousands per region.
-
Mistake: reaching for WebSockets first. Start with polling and move up only when the numbers demand it. Persistent connections complicate load balancing, deploys (reconnect storms) and autoscaling.
-
See Real-time Updates and Real-time Communication.
Dealing with contention. The signal is many actors competing for the same scarce thing at the same time: the last seat, the item in stock, the top bid, the idle driver, the username.
-
First question: what exactly is the contended unit (a seat, a count of 10,000 identical units, a single auction's top bid)? How many actors are there at peak, and how long must the resource be held? A hold lasts milliseconds for a conditional update, and minutes for checkout.
-
The ladder:
- Database-native atomicity: a unique constraint, or a conditional write such as
UPDATE ... WHERE available > 0, orWHERE version = v. - Explicit row locks (
SELECT ... FOR UPDATE) or optimistic concurrency with retries. - Reservations with a TTL, for holds that span user think-time.
- Serialising through a queue or a single writer per resource, at extreme hotness.
- Sharded counters and escrow, for divisible inventory.
- A virtual waiting room, to shape demand before it ever reaches the database.
Distributed locks (Redis, ZooKeeper or etcd leases) belong where the protected resource isn't a database row: an external API, a file, a cron job.
- Database-native atomicity: a unique constraint, or a conditional write such as
-
Escalate when a single row becomes a hotspot: contention ratio ρ = λ·t approaching 1, meaning lock queues and OCC retry storms. Also escalate when the resource spans shards or services.
-
Mistake: splitting the data across services or shards, then rebuilding transactions badly with distributed locks and two-phase commit. Keep the contended state in one database, behind one constraint, as long as you can.
Long-running tasks. The signal is work that takes seconds to hours: video encoding, PDF generation, bulk imports, ML inference on large inputs, crawling, report exports.
- First question: how long at p99, and does the user need the result before continuing?
- The ladder:
- Synchronous if the p99 fits comfortably within request timeouts and user patience. Under about 2 s is usually fine.
- Queue plus a worker pool plus a job-status record the client polls, or gets pushed. This gives immediate acknowledgement, workers that scale independently, retries, and dead-letter queues for poison messages.
- Priority and fair-share queues, autoscaling on queue depth, chunking huge jobs into many small ones, and heartbeats with leases for jobs that run for hours.
- Escalate when work exceeds a few seconds, varies wildly in duration, is bursty, or has heavy resource needs (GPUs, encoders) that should scale separately from the API.
- Mistake: the reverse is just as common. Putting a 200 ms operation behind a queue adds latency, complexity and an invisible backlog, and it loses natural back-pressure: a synchronous call slows the caller, while a queue silently grows. If the work is short, return the result synchronously.
- See Managing Long-Running Tasks.
Large blobs. The signal is bytes: photos, video, audio, documents, datasets, backups.
-
First question: how big are the files, how many per second, and where are they read from?
-
The ladder:
- Proxy small files (under a few MB) through the API for simplicity.
- Presigned URLs for direct-to-store uploads and downloads.
- Multipart and resumable uploads for large files and mobile clients.
- Signed CDN delivery for frequent or global reads.
- Content-hash chunking with dedupe for sync and backup products.
The metadata database and the blob store must be kept consistent: pending rows, storage events, reconciliation.
-
Escalate when files exceed a few MB, uploads exceed hundreds per second, clients are on flaky networks, or reads are global.
-
Mistake: storing blobs in the relational database, or routing gigabytes through stateless API servers.
-
See Handling Large Blobs.
Scaling reads. The signal is read traffic far exceeding writes, plus a database that can't keep up. Read-to-write ratios of 10:1 are normal, and 100:1 to 1,000:1 is common for social and content products. One person posts once a day, while their feed is opened dozens of times and each open triggers dozens of queries.
- First question: what's the peak read QPS, what's the hottest key, and how stale may a read be?
- The ladder:
- Optimise inside the database: the right indexes, covering indexes, denormalisation, materialised views.
- Read replicas, which bring replication lag and read-your-writes concerns.
- A cache: cache-aside in Redis or Memcached for application data, and a CDN for static and media content, with invalidation strategy and TTLs.
- Hot-key handling: replicate hot keys across cache nodes, use local in-process caches, coalesce requests so that one miss triggers one fetch.
- Precomputed views: fan-out-on-write feeds, leaderboards in sorted sets.
- Escalate when indexes are already right and the database is near its read capacity, or for global latency targets.
- Mistake: adding Redis before checking whether a missing index is the real cause.
- See Scaling Reads.
Scaling writes. The signal is sustained high write rates or volume: clicks, location pings, metrics, logs, likes, IoT readings.
- First question: what's the sustained and peak write QPS, how bursty is it, and what's a partition key that spreads load and keeps related data together?
- The ladder:
- Batch and tune: bulk inserts, group commit, write-optimised storage such as LSM-tree engines.
- Vertical partitioning: separate the hot write table from everything else.
- Horizontal sharding on a well-chosen key.
- Absorb bursts with a durable queue (Kafka) and write at a sustainable rate.
- Shed or degrade low-priority writes under overload.
- Pre-aggregate: count clicks per ad per minute in a stream processor instead of storing every click row in the OLTP database.
- Escalate when one primary's sustainable write throughput is exceeded. That is roughly thousands to tens of thousands of simple writes per second for a well-tuned relational primary, depending on the hardware and row size.
- Mistake: a partition key that concentrates the hottest entities, such as a celebrity's posts, a viral video's likes, or "today" in time-ordered keys. Another mistake is sharding on a key that every query must scatter across.
- See Scaling Writes and Partitioning and Sharding.
Multi-step processes. The signal is a business flow with several side effects across services, which must all complete or be compensated, often over long periods. Examples: an order that charges, reserves, ships and notifies; a ride that matches, picks up, completes and pays; onboarding with a human approval.
- First question: how many steps, across how many services or third parties, over what duration? What happens if step 3 fails after steps 1 and 2 succeeded?
- The ladder:
- Single-server orchestration in one handler, with idempotent steps, for short flows.
- A state machine in the database, with a status column and a runner.
- A saga, choreographed via events or orchestrated by a coordinator, with explicit compensations.
- A workflow engine or durable execution (Temporal, AWS Step Functions and peers). These offer durable timers, signals, retries and versioning, for many long-lived, complex flows.
- Escalate when flows span services and must survive crashes, include waits measured in minutes or days, or involve humans.
- Mistake: either extreme. In-memory orchestration of a 3-day flow loses everything on a deploy, while a workflow engine for a two-step flow is pure overhead.
- See Multi-Step Processes.
Proximity search. The signal is queries by location: "restaurants within 2 km", "nearest available driver", "stores that deliver here", "friends nearby".
- First question: how many entities, how often do they move, and is the search radius local?
- The ladder:
- Scan. With 1,000 entities, computing distance to each is microseconds of work, and no index is needed.
- A geospatial extension of a database you already have: PostGIS on PostgreSQL, Redis's geo commands (
GEOADD,GEOSEARCH), or Elasticsearch's geo queries. - A dedicated sharded geo index, built on geohash prefixes, quadtrees or hierarchical cells (Google's S2, Uber's H3), for very large or very dynamic sets.
- Escalate when entity counts reach hundreds of thousands or millions, or entities move constantly. Moving drivers are also a scaling-writes problem.
- Mistake: building a quadtree service for a few thousand static shops, or forgetting that queries are local. The index can then be partitioned by region, so no node ever needs a global view.
- See Geospatial Indexing, and the third deep dive below.
Patterns underneath the patterns#
The eight patterns sit on top of more basic choices that shape every design. A pattern can't rescue a wrong foundation.
Access patterns drive the data model. Before choosing a database, list the queries the product must serve, with their frequency and latency targets. For example:
- "fetch a user's 50 latest posts" (80% of traffic, p99 50 ms);
- "count likes per post" (constant);
- "search posts by keyword" (occasional).
Model and index for those queries, not for an abstract notion of the entities. That means composite indexes whose column order matches the filters and sort, covering indexes that answer a query from the index alone, denormalised read models for hot paths, and partition keys aligned with the dominant access path.
Physical storage reinforces this:
- B-tree indexes favour point lookups and range scans on the indexed prefix.
- LSM-tree engines favour high write rates.
- Clustered storage keeps rows with nearby keys on the same pages, so range scans are cheap.
Many "scaling reads" problems vanish once the indexes match the queries. See Data Modeling and Database Indexing.
API patterns encode the contract. A few API-level patterns recur in nearly every design, and several of them are part of the eight patterns' solutions:
- cursor-based pagination for feeds;
- idempotency keys for unsafe operations;
202 Acceptedwith a job resource for long tasks;- presigned-URL issuance for blobs;
- ETags and conditional requests for optimistic concurrency;
- webhooks and SSE for push;
- versioning for evolution.
See API Design and Idempotency.
Architectural styles set the frame.
- Client–server is the default.
- Microservices split ownership along business boundaries. That multiplies multi-step and consistency problems, so do it for team-scaling reasons, not fashion.
- Serverless (functions plus managed services) suits spiky, event-driven work, with cold starts and execution limits as constraints.
- Event-driven architecture decouples producers from consumers via events. It is the glue for choreographed sagas, post-upload processing and fan-out.
- Peer-to-peer removes central servers for distribution (BitTorrent-style) or resilience. It appears in interviews mostly for content distribution, or as a contrast case.
The style you pick changes which patterns become hard. In a monolith with one database, contention and multi-step flows are mostly database transactions. Across 30 microservices, they become sagas. See Architecture Styles, Monolith vs Microservices, Serverless and Event-Driven Architecture.
Combining patterns#
Real systems rarely use one pattern. A video platform shows a typical combination:
- Large blobs for uploading the source file.
- Long-running tasks for transcoding.
- Multi-step processes to coordinate upload, validation, transcoding, packaging and publishing, plus the cleanup when any of them fails.
- Real-time updates to show the creator "processing 63%".
- Scaling reads (CDN, caches) to serve millions of viewers.
- Scaling writes for view counts and watch-history events.
Patterns combine along a few recurring seams. Knowing them lets you assemble designs quickly.
Two further seams are left out of the picture to keep it readable. Long-running tasks often grow into multi-step processes once their steps need coordination and compensation. Scaled read views fan their changes out to real-time push, as in a live feed.
Seam 1: an event hands off between patterns. A storage event, a domain event such as OrderPlaced, or a CDC record is how one pattern's output becomes another's input. Use a queue or log (SQS, Kafka) at every seam, and make every consumer idempotent. This is the most common combination glue, from blob → task and task → real-time, to write stream → aggregated read view.
Seam 2: contention feeds a multi-step flow. Wherever a scarce resource must be held while something slow happens, such as payment, a driver accepting, or a user filling in a form, you need both patterns. Contention handling (a reservation with a TTL) protects the resource, and the multi-step flow (hold → pay → confirm, or release on failure or expiry) completes the business transaction. Ticketing, flash sales, auctions with payment, and ride dispatch all have this shape.
Seam 3: write scale produces read scale. High-rate writes (likes, clicks, views, locations) are rarely read raw. They are aggregated by a stream processor or a counter service into views (counts, top-K lists, heat maps, indexes), which are then cached and served. The write path and the read path are designed separately, joined by the aggregation step. Ad click aggregation, top-K trending, metrics dashboards and live like counts all follow this shape.
Seam 4: real-time rides on top of something else. Real-time delivery is usually the last mile of another pattern: chat messages after they're persisted, job progress from a long-running task, a driver's location from a high-rate write stream, a feed update from fan-out. Design the underlying pattern first, then decide how its changes reach the client.
Combining patterns, in depth: where patterns interfere#
Patterns are designed in isolation, and they can break each other when combined. The interactions are where strong designs separate from box-drawing.
-
Caching versus contention. Caching a contended value, such as "seats left" or "stock", makes reads cheap, but the cache is stale by design. Rule: the cache may drive display, never decisions. The authoritative check happens at write time, against the source of truth, with a conditional write or lock. Showing "3 left" from a 2-second-old cache is fine. Selling the fourth ticket because the cache said 3 is not.
-
Sharding versus contention. Sharding spreads writes, but a contended invariant that spans shards (a bank transfer between accounts on different shards, a seat map split across nodes) now needs distributed coordination. Choose shard keys so that each invariant lives inside one shard: shard by event for ticketing, and by account for most ledger operations. Accept cross-shard coordination only for the rare operations that truly need it.
-
Asynchrony versus read-your-writes. Queues and async workers mean the user's own action may not be visible yet when their next request reads it. Mitigations:
- return the new state in the write's response;
- read from the primary for that user for a few seconds;
- show a
pendingstatus explicitly.
See Consistency Models.
-
Fan-out versus write scale. Real-time and feed fan-out multiply writes. One post by an account with 50M followers is 50M feed inserts, or 50M push messages. Handle it with fan-out-on-read for celebrity accounts, a hybrid push/pull model, or rate-limited, batched pushes. Otherwise a "scaling reads" decision silently creates a "scaling writes" emergency.
-
Retries versus contention. Optimistic concurrency under heavy contention produces retry storms, and retries from many clients can turn a short spike into collapse. Retries need jittered backoff and budgets. At very high contention, switch strategy: queue serialisation or a waiting room.
-
Queues versus back-pressure. A queue between an API and workers absorbs bursts, but it also hides overload. The API keeps accepting while the backlog grows for hours. Use bounded queues, admission control, and visible queue-age metrics. Shed load at the edge when the backlog's age exceeds what the product can tolerate.
-
CDN caching versus private or changing blobs. Long cache lifetimes need immutable keys. Private content needs signed URLs or cookies that don't fragment the cache key. Combining "fast downloads" with "access control" is a design task, not a default.
-
Workflows versus hot entities. A durable workflow per order scales well, because the workflows are independent. A single workflow coordinating "all orders" is a hot key with a hard per-workflow throughput ceiling. Model workflows per business entity.
Three composition rules prevent most interference:
- One source of truth per fact. Every other copy (caches, search indexes, read models, CDN objects) is derived, possibly stale, and never used for decisions about that fact.
- Idempotency at every seam. Events, retries and redeliveries happen in every combination. A stable key per operation makes them harmless.
- Keep each invariant inside one consistency boundary, whether that's one row, one shard, one database or one workflow. Cross boundaries only through explicit, compensatable steps.
Examples from the case studies#
The table maps the case studies in this handbook to the patterns they combine. Bold marks the pattern that dominates that problem's deep dives.
| Case study | RT | Contention | Long tasks | Blobs | Reads | Writes | Multi-step | Proximity |
|---|---|---|---|---|---|---|---|---|
| URL shortener | ✓ unique codes | ✓ | ||||||
| News feed | ✓ | ✓ fan-out | ✓ media | ✓ | ✓ | |||
| Chat system | ✓ | ✓ attachments | ✓ | ✓ | ||||
| Live comments | ✓ | ✓ | ✓ | |||||
| ✓ variants | ✓ | ✓ | ||||||
| Web crawler | ✓ | ✓ pages | ✓ | ✓ | ||||
| Video streaming | ✓ progress | ✓ transcode | ✓ | ✓ CDN | ✓ views | ✓ | ||
| File sync | ✓ change notices | ✓ conflicts | ✓ | ✓ | ||||
| Collaborative editor | ✓ | ✓ concurrent edits | ✓ | |||||
| Code judge | ✓ results | ✓ | ✓ | |||||
| Job scheduler | ✓ claim jobs | ✓ | ✓ | ✓ | ||||
| Ride-hailing | ✓ | ✓ driver claim | ✓ locations | ✓ trip | ✓ | |||
| Proximity service | ✓ | ✓ | ||||||
| Local delivery | ✓ | ✓ inventory | ✓ | ✓ order | ✓ | |||
| Dating app | ✓ matches | ✓ mutual swipes | ✓ photos | ✓ | ✓ swipes | ✓ | ||
| Ticket booking | ✓ seat map | ✓ | ✓ | ✓ hold-pay | ||||
| Online auction | ✓ bids | ✓ | ✓ photos | ✓ | ✓ | ✓ close | ||
| Flash sale | ✓ | ✓ | ✓ | ✓ checkout | ||||
| Payment system | ✓ ledger | ✓ | ||||||
| Stock trading | ✓ prices | ✓ order book | ✓ | ✓ | ✓ | |||
| Ad click aggregator | ✓ | ✓ | ||||||
| Top-K / trending | ✓ | ✓ | ||||||
| Metrics monitoring | ✓ alerts | ✓ | ✓ | |||||
| Notification system | ✓ | ✓ | ✓ | ✓ retries | ||||
| LLM chat (ChatGPT) | ✓ streaming | ✓ GPU capacity | ✓ | ✓ files | ✓ tools |
Some patterns the table makes visible:
- Read-heavy content products (feed, Instagram, URL shortener) centre on reads, plus blobs when there's media.
- Marketplaces and inventory (tickets, auctions, flash sales, ride-hailing, trading) centre on contention, combined with multi-step flows.
- Telemetry products (ad clicks, top-K, metrics) centre on scaling writes, with aggregation feeding reads.
- Interactive products (chat, live comments, collaborative editing, LLM chat) centre on real-time delivery.
Learning one design from each family covers much of the problem space.
Walk-through 1: video platform, a pipeline of patterns. "Design YouTube" combines the patterns like this:
- Upload (large blobs). The creator's app requests an upload. The API inserts a
pendingvideo row and returns presigned multipart URLs. The app uploads parts directly to object storage, resuming after drops. - Kick-off (event seam). The storage
ObjectCreatedevent lands on a queue. A worker verifies the object and starts a workflow for this video. - Processing (long-running tasks inside a multi-step process). The workflow splits the source into segments and fans out transcode tasks across a GPU or CPU worker pool, at several renditions. It waits for all of them, then packages HLS or DASH manifests, generates thumbnails and runs moderation. If moderation fails, the workflow's compensation removes the renditions and marks the video
rejected. - Progress (real-time). Each completed step updates the video row. The creator's page receives updates over SSE, or simply polls every few seconds. Polling is entirely adequate here.
- Viewing (scaling reads). Renditions are served from a CDN with long cache lifetimes, using immutable keys. Metadata comes from a cache in front of the database.
- Counting (scaling writes). View events stream into Kafka and are aggregated per video per minute. Counters are updated in batches, and the displayed count is eventually consistent.
Walk-through 2: ride-hailing, contention at the centre of three other patterns.
- Locations (scaling writes). Millions of drivers report their location every few seconds. The pings go to an in-memory geo index, partitioned by region, rather than to a relational table. Durable storage gets sampled or batched history.
- Matching (proximity). For a ride request, the index returns the nearest available drivers within a radius, using geohash or H3 cells.
- Claiming (contention). Two concurrent requests must not get the same driver. A conditional update claims the driver: set
status = 'offered' WHERE status = 'available', or use a per-driver lock with a short TTL. The offer then waits for the driver to accept within about 10–15 s. On timeout or decline, the system releases the driver and offers the next one. - The trip (multi-step process). Matched → en route → picked up → completed → paid → rated, with timeouts and compensations such as cancellation fees or payment retries.
- Real-time. The rider's map is updated from the driver's location stream, pushed over a WebSocket or SSE connection.
Walk-through 3: ticket booking, contention plus a multi-step flow plus load shaping. At a big on-sale, millions of users arrive at once for tens of thousands of seats.
- Load shaping. A virtual waiting room admits users at a rate the system can serve. That keeps the contended database below its collapse point.
- Holding a seat (contention). A seat is reserved with a TTL via a conditional update, so exactly one hold wins.
- Paying (multi-step process). The hold → payment → confirm flow is idempotent per order. If payment hasn't succeeded when the hold expires, the hold is released, and any late payment is refunded.
- The seat map (scaling reads, plus optional real-time). It is served from a cache that is a few seconds stale, and may be pushed over SSE. It is never used to decide who gets a seat.
Walk-through 4: chat, real-time over scaled writes.
- Persist first. Messages are written durably to a store partitioned by conversation (Cassandra-style wide rows) before delivery.
- Then deliver (real-time). Each user's connection server subscribes to their channel on a sharded pub/sub layer. Senders publish to the recipient's channel. Offline users get push notifications, and fetch from the store on reconnect.
- Attachments (large blobs). They go through presigned uploads, and recipients download them via signed URLs.
The real-time pattern only ever carries notifications of durable facts, so a lost push costs latency, not data.
Start simple, escalate on evidence#
Every pattern has a ladder, and the right rung is the lowest one that meets the stated requirements, with headroom. Climbing higher costs operational complexity, new failure modes and engineering time. Climbing too low fails the requirements.
Use the requirement numbers to justify each step, aloud:
- "At 2,000 reads per second, a single PostgreSQL instance with the right index is fine. At the stated 200,000 per second, with a hot key, we need a cache tier with hot-key replication."
- "Polling every 10 seconds meets the 'within 30 seconds' freshness requirement for 1M users. That's 100,000 requests per second of mostly empty responses, which is wasteful, so SSE is worth it here."
- "One order flow with three steps runs fine as a database state machine. If we add the 14-day return flow and partner webhooks, a workflow engine starts paying for itself."
Escalation is also reversible in design, but not in production. An architecture can grow from replicas to caches to sharding as traffic grows. Each step is a migration (see Data Migration), so leave seams: an abstraction over storage access, and keys that will shard well. Don't build the top rung on day one.
Anti-patterns in pattern selection#
- Pattern stuffing. Naming Kafka, Redis, Temporal, WebSockets and Elasticsearch in the first five minutes, with no requirement that calls for them. Every component must answer a requirement.
- Queue everything. Asynchrony by default turns simple synchronous calls into eventual consistency, hidden backlogs and harder debugging.
- Premature sharding. Sharding before exhausting indexes, vertical scaling, replicas and caching. A single modern database server handles far more than most candidates assume (see Numbers to Know).
- Cache before index. Masking a slow query with a cache, and inheriting invalidation problems, when an index would have fixed the root cause.
- Distributed lock as a hammer. Reaching for Redis locks for state that lives in one database, where a constraint or conditional write is simpler and stronger.
- Microservices for a small team. Splitting a three-engineer product into ten services, which turns every transaction into a saga.
- WebSockets for everything. Persistent connections where polling meets the freshness target.
- Ignoring the interaction. Adding a cache to a contention problem, or fan-out to a write-bound system, without addressing the interference described above.
When to Use It#
Use this guide:
- At the start of any design, after gathering requirements. Scan for the eight signals, list the patterns in play, and say which one is the crux. Typically one pattern dominates the deep dives, and naming it early focuses the session.
- When the problem is unfamiliar. Decompose it into patterns. "Design a parking-garage booking system" is a contention plus multi-step problem with a proximity search, even if you've never seen it before.
- When reviewing a real design. For each pattern present, check the rung against the numbers, and check the combination against the interference list.
- When the interviewer pushes on scale. Re-run the ladder with the new numbers and climb exactly as far as needed, explaining why.
When NOT to Use It#
- As a replacement for requirements. Patterns answer "how", once requirements answer "what" and "how much". Pattern-matching on the product name ("it's Uber, so geohash and Kafka") without the numbers leads to over- or under-building.
- For genuinely novel cores. Some problems contain a part no standard pattern covers: a custom ranking algorithm, a consensus-heavy coordination problem, a domain-specific scheduler. Use the patterns for the familiar parts, and spend your thinking on the novel part.
- As a checklist to fill. A design that uses all eight patterns is almost certainly wrong. Most real systems need three to five, each at the lowest adequate rung.
How to Implement It#
Applying patterns is a procedure. Run it the same way every time, in an interview or a design review.
- Gather functional requirements as verbs ("upload a video", "book a seat") and non-functional requirements as numbers: DAU, QPS, sizes, freshness, latency, consistency, durability.
- Estimate the loads for each operation: reads/s, writes/s, bytes/s, peak-to-average ratio, and the hottest key.
- Scan for the eight signals, using the questions in the flowchart. List every pattern that fires.
- Name the crux: the one or two patterns that make this problem hard. That is where your deep dives go.
- For each pattern, pick a rung and justify it with a number. Say what would make you climb.
- Draw the high-level design with each pattern's components in place: presign service, queue and workers, cache, shard map, workflow engine, geo index, connection gateway.
- Check the seams: events between patterns, idempotency keys, and one source of truth per fact.
- Check interference against the list above: caching versus contention, sharding versus invariants, async versus read-your-writes, fan-out versus write scale.
- Walk the failure paths for the crux patterns. What if a worker dies, a hold expires, a pub/sub node fails, a shard is hot?
- Revisit with new numbers when the interviewer scales the problem up, and climb exactly the rungs the new load requires.
A compact worksheet keeps this honest. Here it is filled in for a ticket-booking design:
problem: ticket booking for stadium on-sales
loads:
peak_users: 2_000_000 # arrive within 5 minutes of 10:00
seats: 60_000
seat_map_reads_per_s: 150_000 # mostly cacheable
hold_attempts_per_s: 20_000 # after waiting-room admission
patterns:
contention: # crux
rung: conditional UPDATE + hold with 10 min TTL
climb_if: single event row hot -> per-section rows, waiting room rate
multi_step:
rung: DB state machine (held -> paid -> confirmed | released)
climb_if: partner payouts, refunds, 14-day flows -> workflow engine
scaling_reads:
rung: seat map in Redis, 2 s staleness, never used for decisions
realtime:
rung: SSE seat-map deltas for admitted users; polling fallback
load_shaping:
rung: virtual waiting room admitting about 5,000 users/min
seams:
- payment webhook -> idempotent confirm keyed by order_id
- hold expiry sweeper -> release + refund late payments
interference_checks:
- cache shows availability only; claim checks the source of truth
- all seats of one event on one shard (invariant in one boundary)Each pattern has a default technology at each of its rungs. Here are the usual defaults; the technology pages cover them in depth.
| Technology | Fits when |
|---|---|
PostgreSQL / MySQL (constraints, FOR UPDATE, SKIP LOCKED) | Contention, DB state machines and simple job queues at moderate scale; the default source of truth |
| Redis (cache, sorted sets, Lua, pub/sub, geo, streams) | Scaling reads, leaderboards, atomic counters, lightweight pub/sub for real-time, in-memory geo search |
| Kafka (or Kinesis, Pulsar) | Write buffering, event seams between patterns, stream aggregation, durable fan-out |
| SQS / RabbitMQ / cloud task queues | Long-running task queues with retries, visibility timeouts and DLQs |
| Temporal / AWS Step Functions | Multi-step processes with durable timers, signals and compensations |
| S3 / GCS / Azure Blob + CDN | Large blobs: presigned uploads, multipart, signed delivery |
| Cassandra / DynamoDB / ScyllaDB | Write-heavy, partition-key-driven data at scale: messages, events, time-ordered data |
| Elasticsearch / OpenSearch | Full-text search and geo queries over denormalised documents |
| PostGIS / H3 / S2 libraries | Proximity search, from a database extension to custom sharded cell indexes |
| WebSocket / SSE gateways (managed or self-run) | Real-time delivery at large connection counts |
Trade-offs#
Every escalation buys capacity, and every one has a price.
| Option | Pros | Cons | Pick when |
|---|---|---|---|
| Stay in one database (indexes, transactions, constraints) | Strong consistency, simplest operations, transactions solve contention and multi-step locally | Single-node limits on writes and connections | Loads fit one primary with headroom, which is more often than you think |
| Add read replicas | Easy read scaling, failover targets | Replication lag; read-your-writes issues | Reads outgrow the primary; staleness of seconds is acceptable |
| Add a cache / CDN | Large read offload, low latency | Invalidation, stampedes, staleness; never authoritative | Read-heavy hot data; static and media content |
| Add a queue + workers | Absorbs bursts, decouples slow work, retries | Eventual consistency, hidden backlog, more moving parts | Work exceeds request budgets, or bursts exceed capacity |
| Add pub/sub or persistent connections | Low-latency push, fan-out | Connection management, reconnect storms, stateful routing | Freshness targets around a second; high fan-out |
| Shard the database | Write and storage scale out | Cross-shard queries and transactions, rebalancing, hot shards | Sustained writes or data size beyond one node after tuning |
| Add a workflow engine | Durable, observable multi-step flows with timers and compensation | New infrastructure, determinism and versioning discipline | Many long-lived, cross-service flows |
| Add a specialised index (geo, search) | Fast specialised queries | Another copy of the data to sync (via CDC), eventual consistency | Query types the primary store can't serve at the needed scale |
Common Pitfalls#
- Skipping the numbers. Picking rungs by product name instead of by load.
- Missing the crux. Spending 20 minutes on a URL shortener's blob storage, which it doesn't have, instead of its read path and code generation.
- Treating each pattern in isolation and missing the interference: a stale cache deciding a sale, fan-out exploding writes, cross-shard invariants.
- Over-escalating. Top-rung designs for bottom-rung loads, with no explanation of why.
- Under-escalating when the interviewer raises the scale: a single database at a million writes per second.
- No seams. Patterns connected by synchronous calls with no idempotency, so one slow component stalls the chain.
- Forgetting failure paths. The happy path through five patterns is easy. What matters is who notices, and who recovers, when a worker, a hold, a push or a shard fails.
- Inventing a pattern for a problem the database already solves.
Real-World Examples#
The engineering blogs that accompany well-known systems repeatedly show patterns being combined and escalated in response to real load:
- Discord described, in 2023, moving its message storage from Cassandra to ScyllaDB as message volume reached the trillions. In front of the database, it added data services that coalesce concurrent requests for the same hot channel. That is scaling writes and reads together, with hot-key mitigation, exactly the interaction described above.
- Slack wrote in 2017 about re-architecting its job queue, which had run on Redis, by placing Kafka in front of Redis as a durable buffer. Bursts and Redis memory limits had caused incidents. It's a textbook escalation of the long-running-tasks pattern with a write-buffering seam.
- Figma explained (2019) how its multiplayer editing runs a server process per document that holds the authoritative state and relays changes over WebSockets, inspired by CRDT ideas but simplified because the server is central. That is real-time combined with stateful routing.
- Shopify has written about reserving inventory under flash-sale load with database-native techniques (row-level reservations,
SKIP LOCKED). It shows the contention pattern climbing its ladder without leaving the relational database. - Uber built H3, a hexagonal hierarchical spatial index (open-sourced in 2018), for proximity and geographic analysis at its scale. It also created the Cadence workflow engine for its multi-step processes. Two patterns, two pieces of infrastructure built because the top rungs of their ladders were needed.
Case studies that use this pattern#
Every case study applies this guide. Each one opens by naming the patterns it combines, then spends its deep dives on the crux. These cover the four families:
- Design a Ticket Booking System (Ticketmaster): contention plus multi-step plus load shaping.
- Design a Video Streaming Platform (YouTube / Netflix): blobs, long tasks, multi-step, scaled reads.
- Design a Ride-Hailing App (Uber): proximity, write scale, contention, trip workflow, real-time.
- Design a Chat System (WhatsApp): real-time over durable, partitioned writes.
- Design a News Feed (Facebook / Twitter): read scaling with hybrid fan-out.
- Design an Ad Click Aggregator: write scale with stream aggregation.
In the Interview#
Deep Dive: Quantitative triggers for each patternShow
Vague rules ("use a cache when reads are high") don't help under pressure. Here are rough, defensible numbers for when each pattern's next rung becomes necessary. They are orders of magnitude, not guarantees. Hardware, row sizes and query shapes shift them, so state your assumptions when you use them.
Real-time. Polling cost is clients ÷ interval requests per second, and most of those requests return nothing.
- 1M connected clients polling every 5 s is 200,000 requests/s, and most are wasted.
- The same clients on SSE or WebSocket hold 1M mostly idle connections. A well-tuned connection server holds roughly tens to hundreds of thousands of them, depending on memory per connection and message rate. That means about 10–50 servers, sending messages only on change.
The crossover comes when clients × (1 / interval) is large and updates are sparse, or when the freshness target is below about 2–5 s. Below a few thousand clients, or above about 30 s freshness, polling is usually the better engineering choice.
Contention. Model a hot row as a single server with service time t, for example 5 ms holding a row lock. With arrival rate λ, utilisation is ρ = λt.
- Queueing delay grows like ρ / (1 − ρ) times the service time.
- At λ = 100/s, ρ = 0.5 and waits average about one service time.
- At λ = 180/s, ρ = 0.9 and waits are about 9× the service time.
- At λ ≥ 200/s, the queue grows without bound.
So a single hot row sustains at most about 1/t operations per second, here 200/s. To go beyond that you must:
- shorten t: no network calls while holding a lock, and use a single conditional
UPDATEinstead of read-then-write; - split the resource: per-section rows, sharded counters, escrow;
- or shape arrivals: a waiting room, queue serialisation.
Under optimistic concurrency, the success probability per attempt falls roughly as e^(−λw), where w is the conflict window. Retries amplify load, so switch to pessimistic or serialised approaches once conflicts are common.
Long-running tasks. Move work off the request path when:
- its p99 exceeds about 1–2 s, which is user patience for an interactive action;
- it can approach the shortest timeout on the path, which is often 30–60 s at load balancers and gateways;
- its resource profile differs from the API's (GPU, large memory);
- or its arrival is bursty relative to processing capacity.
Size the worker pool by Little's Law: workers needed ≈ arrival rate × mean processing time. For example, 50 jobs/s × 40 s each = 2,000 concurrent workers, plus headroom for peaks and retries.
Large blobs. Proxying costs about 2 × file size of fleet bandwidth per transfer, plus held connections for size ÷ client bandwidth seconds. Above a few MB per file, or around 100 Mbit/s of aggregate transfer, direct-to-store wins on cost and reliability. Use multipart above about 100 MB, or sooner for mobile clients. A part size of at least file size ÷ 10,000 respects S3's part cap.
Scaling reads. A well-indexed point read on a relational database costs well under a millisecond of database time when the data is in memory. A single node can therefore serve on the order of tens of thousands of simple reads per second, and more for trivial key lookups, depending on hardware.
- Replicas multiply read capacity roughly linearly until replication lag or write amplification bites.
- A Redis node serves on the order of 100,000+ simple operations per second.
- A cache's value depends on its hit rate h. The origin load becomes (1 − h) × reads. Going from a 90% to a 99% hit rate cuts origin load by 10×.
Use these to compute how many replicas or cache nodes the stated QPS needs, rather than asserting "we'll add a cache".
Scaling writes. A relational primary sustains roughly thousands to tens of thousands of simple transactional writes per second. The figure depends on fsync latency (group commit helps), index count and row size. LSM-based stores (Cassandra, ScyllaDB, RocksDB-backed systems) sustain more per node and scale out by partition.
- When to shard: when sustained writes, or data size (multiple TB with heavy indexes), exceed one node after batching and tuning.
- When to buffer: when the peak-to-average ratio is high, so a durable queue lets you provision for the average plus drain time instead of the peak.
- When to aggregate: when the reads only need aggregates. A million clicks per second becomes about 10,000 counter updates per second when they are aggregated per ad per second.
Multi-step. Count the side effects and the services. If there is one database and the side effects can share a transaction, use a transaction. If there are several services, durations under a few seconds and rare failures, use single-server orchestration with idempotent steps plus a sweeper. Consider a state machine or saga when any of these hold:
- waits can last minutes or longer;
- humans or partner webhooks are involved;
- failures need compensation;
- you run many such flows, and want visibility into stuck instances.
A workflow engine becomes cost-effective when you have several such flows, or one very complex one.
Proximity. Scanning N entities with a distance computation costs about N × 50 ns.
- At N = 10,000 that is 0.5 ms: no index needed.
- At N = 10M it is 0.5 s per query, far too slow at any real query rate.
The crossover is around 10⁵ entities, or a few hundred queries per second. Moving entities add the write load as well. 1M drivers updating every 4 s means 250,000 index updates per second, which pushes you toward in-memory, region-partitioned indexes.
Deep Dive: Consistency boundaries when patterns combineShow
The deepest source of bugs in combined designs is mixing data with different consistency guarantees without noticing. Each pattern introduces copies, delays or concurrency:
- caches and replicas are stale copies;
- queues and events are delayed effects;
- shards split invariants;
- workflows spread one transaction over time;
- real-time pushes are best-effort notifications.
A disciplined way to reason is to draw consistency boundaries. A boundary is a region inside which an invariant is enforced atomically: a row, a partition, a database, a single-writer actor, a workflow instance. Then check where each decision is made.
Rule 1: decisions read from inside the boundary that owns the invariant.
- "Is this seat free?" is answered by the seat row in the primary, not by the cache, a replica or the search index.
- "Does this user have enough balance?" is answered by the ledger partition for that account.
Everything outside the boundary is for display and routing.
Rule 2: cross-boundary effects are messages, not transactions.
- When an action in one boundary must cause an effect in another (payment succeeded, so confirm the seat), send a message: an outbox event, a workflow step, a webhook.
- Make the receiver idempotent.
- Plan the compensating message for failure.
This is the saga discipline. It applies just as much to "cache invalidation after write" (the invalidation is a message that may be lost or delayed, so TTLs are your compensation) as it does to payments.
Rule 3: each copy states its staleness bound. Every derived copy should have a known, stated bound:
- "Cache: TTL 30 s, plus invalidation on write."
- "Search index: CDC lag p99 2 s."
- "Replica: lag p99 under 1 s, primary reads for the writer for 5 s."
- "Feed: fan-out completes within 10 s for non-celebrity authors."
Then compare each bound against the product requirement for that read. If the requirement is tighter than the bound, the read must move inside the boundary, or the bound must be tightened.
Rule 4: real-time pushes carry notifications, not truth. A push can be lost (a disconnect), duplicated (a reconnect replay) or reordered (multiple paths). Treat each push as a hint to refresh, or as a delta carrying a version number. Clients apply only newer versions, and resync from the source of truth on gaps. Then the real-time layer can be best-effort, which is what makes it cheap to scale.
A worked check: the flash sale.
| Copy | Staleness bound | Used for |
|---|---|---|
| Stock counter (sharded, in the DB) | none: authoritative, conditional decrement | Decisions |
| Product page stock badge (CDN or cache) | about 5 s | Display only |
| Order record and payment | Hold → pay → confirm, each step idempotent by order ID | Decisions, in a workflow |
| Analytics stream | Lag of minutes is fine | Dashboards only |
The check passes when no decision reads a row in the "display only" category. The classic bug is a "Buy" button that decides from the cached badge: it oversells for 5 seconds after stock hits zero. The fix is a conditional decrement at click time. The badge is unchanged.
Why this generalises. Pat Helland's essay "Life beyond Distributed Transactions: an Apostate's Opinion" (CIDR 2007) argued that scalable systems are built from entities, each with a key and its own serialisable boundary, communicating via messages with at-least-once delivery and idempotent processing. The combined-patterns discipline above is that idea applied:
- workflows per order;
- contention rows per seat or section;
- shards keyed by the invariant's owner;
- events as seams between boundaries.
Deep Dive: Proximity search, the pattern without its own pageShow
Proximity has no dedicated pattern page in this handbook. Its mechanics live in Geospatial Indexing, and its applications in the ride-hailing, proximity-service and local-delivery case studies. This section collects the pattern-level view: the ladder and its triggers, as with the other seven patterns.
Why ordinary indexes fail. A query for "points within 2 km of (lat, lng)" is a two-dimensional range query. A B-tree on (lat, lng) can narrow by latitude, but within that band it must scan every longitude. That means a long, thin strip around the planet, mostly irrelevant. Geospatial indexes map 2-D space onto structures that keep nearby points together.
Rung 1: scan. For up to a few tens of thousands of entities, keep them in memory, compute the haversine distance to each, and sort. 10,000 entities × about 50 ns ≈ 0.5 ms per query. A list of 2,000 stores or 500 warehouses needs nothing more. Optionally pre-filter with a bounding box: a cheap check on latitude and longitude ranges before computing the exact distance.
Rung 2: a geo extension in a database you already run.
- PostGIS adds geometry and geography types, R-tree-style indexes (GiST) and functions such as
ST_DWithin, all with SQL and transactions. It is great for stores, venues and listings, with moderate update rates. - Redis geo commands (
GEOADD,GEOSEARCH) store points in a sorted set keyed by a 52-bit geohash-style interleaving. Radius queries take sub-milliseconds, and high update rates are fine, which makes it a common choice for moving drivers in one region. - Elasticsearch / OpenSearch
geo_pointandgeo_shapefields combine proximity with text filters and ranking, such as "Thai restaurants open now within 3 km, sorted by rating".
Rung 3: cell-based sharded indexes. At very large scale, or with very high update rates, systems index by cell:
- Geohash interleaves latitude and longitude bits into a base-32 string. A longer shared prefix means a smaller enclosing cell: about 5 km at precision 5, about 150 m at precision 7. Search the target cell and its 8 neighbours to handle boundary effects.
- Quadtrees recursively split dense areas into four children until each leaf holds at most k entities. The index thereby adapts to density: Manhattan gets deep trees, the ocean stays shallow.
- Google's S2 projects the sphere onto a cube and uses a Hilbert curve to number hierarchical cells, giving good locality and uniform-ish cell areas.
- Uber's H3 uses hexagonal hierarchical cells. Every neighbour of a hexagon is equidistant from it, which suits movement modelling, surge-pricing regions and aggregation.
With cells as keys, the index shards naturally by region. Each shard holds cells for an area, and a query touches one shard or a few neighbouring ones. Because "nearby" queries are local, no node needs a global view.
Moving entities make it a write-scaling problem too. 1M active drivers updating every 4 s is 250,000 updates/s. A durable SQL index per update would be wasteful. Instead:
- keep the live index in memory (Redis or a custom service), partitioned by region;
- accept loss of the last few seconds on failure, because drivers re-report within seconds;
- persist sampled location history asynchronously for analytics and disputes.
Only state transitions (available, offered, on trip) go to durable storage, and they are protected by contention controls.
Common deep-dive questions.
- "What about boundary effects?" Always query neighbouring cells, or use a covering set of cells for the radius.
- "What about density variation?" Use adaptive structures (quadtrees), or choose the cell resolution dynamically, for example expanding rings of H3 cells until enough candidates are found.
- "How do you rank candidates?" By straight-line distance first, then refine the top candidates with ETA from a routing service. Straight-line distance can mislead across rivers and highways.
Key Takeaways#
- Most design problems are combinations of eight recurring patterns: real-time updates, contention, long-running tasks, large blobs, scaling reads, scaling writes, multi-step processes, and proximity search.
- Find them from signals: the verbs, the nouns with physics, the quality adjectives, and above all the numbers. Ask for numbers if none are given.
- Each pattern has a ladder. Pick the lowest rung that meets the requirements with headroom, justify it with arithmetic, and name what would make you climb.
- Name the crux early: usually one pattern dominates the deep dives.
- Patterns combine through seams (events, idempotency keys, holds that feed workflows, write streams that feed read views), and they interfere at boundaries (stale caches, cross-shard invariants, fan-out explosions, hidden backlogs).
- Keep one source of truth per fact, keep each invariant inside one consistency boundary, and treat every other copy as display-only, with a stated staleness bound.
- Restraint backed by numbers is as strong a signal as knowing the top rungs.