Summary#
The big engineering blogs (Netflix, Uber, Meta) describe systems that took hundreds of engineers years to build. Most teams will never work at that scale. This page collects smaller, sharper stories that show one idea each, clearly. Most come from short public write-ups: Neo Kim's System Design Newsletter (systemdesign.one), a ByteByteGo guide and Canva's own engineering blog. Newsletter posts summarise company talks and blogs, and some say outright that they are the author's research and may differ from the real systems. So this page attributes claims to the newsletter where it should, and explains the engineering idea behind each one in full.
The stories fall into six families:
- Delivering reads at scale: Giphy's CDN with edge and shield servers, Hashnode's precomputed feeds, and Meta's measured cache consistency at ten nines.
- Simple stacks that scale: Khan Academy reaching 30 million users on managed services, Levels.fyi on Google Sheets and its move off them, and Zapier's task automation built from proven parts.
- Peaks and structure: Shopify's ten flash-sale tactics and its modular monolith, and Razorpay's flash-sale preparation.
- Moving data while live: Tumblr moving a database leader across data centers with 60 billion rows, and Canva moving media metadata from MySQL to DynamoDB with zero downtime.
- Real time at huge scale: WeChat's chat architecture.
- Synthesis: what these smaller stories teach, and how they answer classic interview deep dives on caching, consistency, feeds and chat.
Why It Exists#
Big-company case studies can mislead in two ways. First, they make heavy infrastructure look normal, when it was built for problems most teams do not have. Second, they hide the early decisions, which are usually the most instructive. The stories here fix both:
- They show the starting point. Levels.fyi had no backend at all. Khan Academy put its videos on YouTube. Shopify kept a monolith. These choices were deliberate, and the posts explain why.
- They show one idea in isolation. Giphy is about a CDN shield tier. Tumblr is about moving a database leader. Canva is about migrating with a queue of "touch" messages. Each is small enough to learn whole.
- They show what each team gave up. Canva lost ad hoc SQL. Hashnode skipped machine learning. WeChat split users by region instead of solving global consistency. The trade-offs are visible.
The learning approach is the same as for the larger blog pages: for each story, write down assumptions about traffic, latency, consistency and maintenance, study the architecture, look for overlooked constraints, and ask what the engineers sacrificed.
How It Works#
The diagram groups the eleven stories by the main problem each solves.
The lessons follow the families in order. Each covers one story and ends with what the team gave up.
Family 1: Delivering reads at scale
Lesson 1: Giphy's CDN delivering billions of GIFs#
Assumptions.
- Traffic: the newsletter reports about 10 billion GIFs a day to more than 1 billion people, with the CDN handling about 100,000 requests a second.
- Latency: a GIF in a chat or a search result must appear almost instantly, wherever the viewer is.
- Consistency: a GIF never changes after upload, so cached copies never go stale.
- Maintenance: a small team; the CDN is a managed service (Fastly).
The problem. A GIF service is almost pure reads of immutable files. Without help, every view anywhere in the world would travel to Giphy's origin servers. Two things go wrong. Viewers far from the origin wait for long network round trips. And when a GIF goes viral, millions of requests for the same file land on the origin at once.
Step 1: edge servers. A content delivery network (CDN) places edge servers in many cities. Each keeps copies of popular files, often in memory, and serves nearby users. A viewer in Mumbai gets the GIF from a Mumbai edge server instead of a US origin, so latency falls from hundreds of milliseconds to tens. Most requests never reach the origin, which cuts server cost. See CDN.
Step 2: the viral problem. Edge servers only help after they have a copy. When a brand-new GIF goes viral, every edge server in the world misses at the same moment and asks the origin. With hundreds of edge locations, a single new file can trigger hundreds of simultaneous origin requests, and many new files can overwhelm it.
Step 3: shield servers. Giphy's fix, as the newsletter describes it, is a shield tier: a small set of chosen CDN servers that sit between the edges and the origin. Edges ask the shield on a miss; only the shield asks the origin. Now a viral GIF causes one origin fetch per shield rather than one per edge. Fastly calls this origin shielding; other CDNs call it a mid-tier or regional cache.
Storage behind the CDN. The newsletter says GIF files live in Amazon S3 and GIF metadata (titles, tags, IDs) in DynamoDB. The origin is therefore thin: object storage for bytes, a key-value store for metadata, and the CDN for almost all delivery.
Overlooked constraints.
- Request collapsing matters as much as the shield. If 1,000 requests for the same missing file reach one edge in the same second, the edge should send one request upstream and make the rest wait for it. CDNs call this request collapsing or coalescing.
- The shield is a hot spot. All misses converge on a few servers. They must be sized for the miss rate, and a shield in the wrong region adds latency for distant edges.
- Immutability is the enabler. Because a GIF never changes, cache lifetimes can be very long and invalidation is almost never needed. Mutable content would be much harder.
What Giphy sacrificed. Control and some cost: delivery depends on a vendor's network and pricing, and a CDN outage is a Giphy outage. It also adds a little latency on shield misses (edge to shield to origin) in exchange for protecting the origin.
Deep Dive: the arithmetic of a shield tierShow
Without a shield (handbook's illustration). A CDN has 300 edge locations, each with several servers. A new GIF goes viral and is requested everywhere within a minute. Each location misses at least once: 300 origin requests for one file. If 2,000 new GIFs a minute trend at that rate, the origin sees 600,000 requests a minute, about 10,000 a second, all for uncached content.
With a shield. With 2 shield locations, each new GIF causes at most 2 origin fetches: 4,000 a minute for 2,000 trending GIFs, about 67 a second. That is a 150-fold cut in origin load.
Hit-ratio math. If the CDN as a whole has a 99 percent hit ratio at 100,000 requests a second, the origin serves 1,000 a second. Raising the hit ratio to 99.9 percent cuts origin load to 100 a second. At high hit ratios, each additional "nine" divides origin load by 10, which is why CDN tuning (TTLs, shielding, collapsing) pays off so strongly.
Latency. A cross-ocean round trip is about 150 to 250 ms. An edge hit is often 10 to 30 ms. For a GIF of 2 MB on a mobile connection, transfer time dominates anyway, which is why CDNs also serve smaller formats (MP4 or WebP versions of GIFs) to cut bytes.
Lesson 2: Hashnode's feed generation#
Assumptions.
- Traffic: the newsletter reports about 2.3 million developers and hundreds of new articles a day; reads far outnumber writes.
- Latency: the feed is the home page, so it must load in well under a second.
- Consistency: a new article may take a short while to appear in followers' feeds.
- Maintenance: a small team; serverless services preferred so nobody manages servers.
What a feed is. A feed is a personalised list of articles shown when a user logs in, built from the authors and tags they follow and their activity. Hashnode started it in 2020 to improve engagement and discovery.
Ranking without machine learning. The newsletter reports that Hashnode does not use ML to rank. Each article gets a score from factors such as likes, views and comments, which are normalised so a few very popular articles do not take over everyone's feed. Articles already shown to a user are ranked lower so the feed stays fresh. Simple scoring is cheap, explainable and easy to tune.
Precompute for active users. Building a feed on request is expensive: a user may follow many authors, and each author's articles must be fetched and merged. Doing that on every page load repeats the same work. So Hashnode precomputes feeds before users ask and stores them in a Redis cache, but only for active users, those who logged in within the last few days. Computing feeds for inactive users would waste memory on feeds nobody reads.
Event-driven and serverless. Every user action, such as publishing or liking an article, emits an event to AWS EventBridge (a managed event bus). Lambda functions react. One reads a metadata cache (author data and the list of their active followers), falling back to MongoDB where articles live if the cache is stale. Another computes feeds and writes them to Redis (Upstash, a serverless Redis provider). AWS Step Functions with its distributed map feature runs many Lambda computations in parallel and tracks them, so the Lambdas stay small.
The cache layout. The newsletter says the exact layout is not public, and suggests a reasonable design: a Redis list per user holding a few hundred article IDs (and author IDs), not full articles. Article data sits in a separate cache, and the page fetches many articles in one round trip with MGET.
The celebrity problem. Writing an article ID into every follower's list is fan-out on write: O(n) work per publish for an author with n followers, while reading a feed is a single O(1) fetch. For famous authors with huge followings, the write becomes slow. The usual fix, which the newsletter suggests, is a hybrid: do not fan out a famous author's posts; merge them into the follower's feed when the follower reads it. See the news feed case study.
Overlooked constraints.
- Returning users have no feed. A user inactive for weeks has no precomputed feed. The first load must build it on demand or show a generic one while it is computed.
- Serverless concurrency limits. A popular author's publish can trigger thousands of Lambda invocations. Account concurrency limits and Redis connection limits must allow for that burst.
- Ranking changes need recomputation. If scores change (an article gets many likes), precomputed feeds hold old rankings until recomputed.
What Hashnode sacrificed. Personalisation quality (simple scores instead of ML), freshness for inactive users, and memory for precomputed lists, in exchange for fast home pages and almost no servers to run.
Deep Dive: fan-out on write versus read, in numbersShow
Fan-out on write (handbook's illustration). 500 articles a day, each author with 2,000 active followers on average: 1 million list inserts a day, about 12 a second. Trivial for Redis. Memory: 2 million active users × 500 IDs × about 16 bytes = 16 GB. Affordable, but the main cost of the design.
The celebrity case. One author with 500,000 active followers publishes: 500,000 inserts. At 50,000 inserts a second across parallel Lambdas, the fan-out takes 10 seconds. Acceptable here, but at Twitter scale (authors with tens of millions of followers, thousands of posts a second) it is not, which is why Twitter's timeline design uses the hybrid.
Fan-out on read. At read time, merge the newest posts from each followed author. If a user follows 200 authors, that is up to 200 lookups per page load. At 1,000 feed loads a second, 200,000 lookups a second. Precomputation trades that read cost for write cost and memory.
Hybrid rule. Fan out on write for authors with fewer than, say, 10,000 followers; for larger authors, store posts once and merge at read time. Each reader then merges only a handful of celebrity sources, which keeps reads cheap and writes bounded.
Lesson 3: Meta's cache consistency at ten nines#
Assumptions.
- Traffic: the newsletter cites about a quadrillion (10^15) cache requests a day. Even a 1 percent miss rate would be 10 trillion cache fills a day.
- Latency: cache reads in well under a millisecond; database reads are far more expensive.
- Consistency: caches should eventually match the database, and the time to converge should be measured.
- Maintenance: a huge fleet of cache servers fed by an invalidation pipeline.
Why caches go stale. Caches avoid coordination with the database, which is how they make systems fast. But that independence lets them drift. The classic race: a client misses in the cache, and the cache reads x = 0 from the database. Before that fill arrives, the database changes x to 1, and the invalidation for x = 1 reaches the cache first. Then the slow fill arrives and writes x = 0. The database says 1, the cache says 0, and nothing will fix it until the entry expires. From a user's point of view, a stale cache looks like lost data.
Step 1: measure it with Polaris. Meta built Polaris, a separate service that measures cache inconsistency. It behaves like a cache server and receives invalidation events. For each one, it asks the cache replicas whether they hold the new value. If one does not, Polaris queues that check and tries again later. It does not fix anything; it measures. Because a network partition between the cache and Polaris could make Polaris miss events, Polaris gets its own invalidation stream from the client side.
Not overloading the database. The obvious way to decide who is right, cache or database, is to read the database. At Meta's scale that would overload it. So Polaris checks the database only at timescales of 1, 5 and 10 minutes: if a mismatch persists past a timescale, then it confirms against the database. Most mismatches are just in-flight invalidations and resolve on retry. The output is a metric of the form "this fraction of writes is consistent within M minutes".
Step 2: trace only the risky window. Logging every cache mutation is impossible because caches are read-heavy and writes are numerous. Meta's tracing library, embedded in cache servers, logs mutations only during the short window after a write, when fills and invalidations race. That is where bugs live. The Meta engineering page walks through this in detail, including a real bug the tracing found: an error handler that dropped an item only if its version was older, while the stale item already carried the new version number. On-call engineers found it in under 30 minutes.
Result. For TAO, Meta's graph cache, consistency within five minutes improved from six nines (99.9999 percent) to ten nines (99.99999999 percent): fewer than 1 in 10 billion writes still inconsistent after five minutes.
Overlooked constraints.
- You cannot fix what you do not measure. Before Polaris, inconsistency was a rumour; afterwards it was a number on a dashboard, with alerts.
- Versions must be compared correctly. Many cache bugs are version bugs: a fill without a version can overwrite a newer value. Leases or version-checked fills are the standard defence (the memcache paper by Nishtala and others, NSDI 2013, describes leases).
- The measuring system needs its own path. If Polaris got events only through the cache's pipeline, it would miss exactly the events the cache missed.
What Meta sacrificed. Infrastructure and engineering effort for a system that serves no user traffic, plus some database reads for confirmation. Meta did not try to make caches strongly consistent, which would destroy their performance; it made inconsistency rare and measurable.
Deep Dive: what ten nines means and how leases prevent the raceShow
Scale (handbook's illustration). If a cache tier processes 10 billion writes a day, six nines of consistency at five minutes leaves 10,000 stale entries a day. Ten nines leaves 1. At Meta's request volume, the difference between six and ten nines is the difference between a steady trickle of "my post disappeared" reports and essentially none.
Leases. On a miss, the cache gives the client a lease token. The client may fill the key only with that token. If an invalidation arrives in between, the cache cancels the lease, so the late fill with x = 0 is rejected. This closes the race in the diagram above. Leases also stop thundering herds: only the lease holder fills; others wait briefly or get a slightly stale value.
Version-checked fills. Alternatively, store a version with every value and accept a fill only if its version is newer than what the cache holds or has seen invalidated. The bug Meta's tracing found shows why this must be applied everywhere, including error handlers.
Interview link: cache invalidation that must be immediately visible. When a user must see an update at once, options are: write-through (update the cache synchronously with the database), delete-then-read from the primary for the writer only (read-your-own-writes), version tokens that let the reader detect stale entries, or skipping the cache for that read. Each costs latency or complexity; most systems use read-your-own-writes for the writer and eventual consistency for everyone else. See cache eviction and invalidation.
Family 2: Simple stacks that scale
Lesson 4: Khan Academy scaling to 30 million users#
Assumptions.
- Traffic: the newsletter reports 30 million students in April 2020, when schools closed and Khan Academy became one of the most used learning resources for distance learning. Traffic jumped in weeks, not years.
- Latency: lessons and exercises must feel responsive on cheap devices and slow school networks.
- Consistency: progress and mastery data must not be lost; content can be cached heavily.
- Maintenance: a nonprofit with a modest engineering team and budget, so every hour of operations work is expensive.
Origins. Sal Khan began in 2004 by tutoring a cousin remotely, then recorded lessons on YouTube so others could use them. That beginning shaped the architecture: use what exists before building anything.
KISS: keep it simple. The newsletter lists the choices that kept the system simple:
- Videos on YouTube. Video hosting, encoding and global delivery are hard and expensive. YouTube does them for free. Where YouTube is blocked (some countries and schools), videos fall back to files in S3 served through Fastly's CDN.
- Serverless hosting. The app runs on Google App Engine, a managed platform that scales instances automatically. Nobody provisions servers for a traffic spike; the platform adds instances.
- CDN for every request. Fastly sits in front of all traffic, caching static content and absorbing load.
- A content management system with a versioned content store, so authors publish lessons without engineers, and content changes can be tracked and rolled back.
- Managed data. Google Cloud Datastore, a managed NoSQL database, stores data; Memcache caches common queries, user preferences and session data.
From monolith to services. Khan Academy's original Python monolith became slow to change: deploys and tests took long, and a bug anywhere could affect everything. The team split it into about 20 services, which gave faster deploys and tests, a smaller blast radius when something breaks, and the freedom to choose instance types and tune cost and performance per service. Each service owns its data, and other services reach that data only through a GraphQL API. The team also moved from Python to Go: faster compiles, lower memory use, and simple concurrency, which cut instance count and cost.
People and process. The newsletter stresses that the migration worked because of how the team worked as much as the technology:
- Succeed or fail together: one shared goal rather than team-by-team scorecards.
- "Good enough", not perfect: finish the migration rather than polish each part.
- No scope creep: the migration did not double as a rewrite of features.
- Ownership by product area, so each service had a clear owner.
- Celebrate milestones to keep a long project moving.
- Conway's law (systems mirror the communication structure of the organisation that builds them) was used on purpose: team boundaries match service boundaries. Open communication and Architecture Decision Records (ADRs), short documents recording why each decision was made, kept the reasoning visible.
Overlooked constraints.
- Platform lock-in. App Engine and Datastore are Google-specific. Moving clouds would mean rewriting data access and deployment.
- YouTube is a dependency outside your control. Blocking, ads policy and embed rules belong to someone else, which is why the S3 fallback exists.
- GraphQL-only data access needs discipline. A service that reads another's database directly would recreate the monolith's coupling. The rule has to be enforced in review.
What Khan Academy sacrificed. Control over video delivery and infrastructure tuning, and a long, expensive migration from Python to Go, in exchange for an architecture a small nonprofit team could run through a sudden pandemic spike.
Deep Dive: why managed services absorbed the 2020 spikeShow
Spike math (handbook's illustration). Suppose daily active users jump from 2 million to 10 million in three weeks, with a school-day peak of 3 times the average. If each active student makes 200 requests a day, the average rate is 2 billion requests a day, about 23,000 a second, and the peak is about 70,000 a second.
What the CDN takes. If Fastly serves 80 percent of requests (static assets, cached content), origin load at peak is 14,000 a second. Videos on YouTube carry the heaviest bandwidth at zero cost to the nonprofit.
What auto-scaling takes. If one Go instance handles 500 requests a second, 28 instances are needed at peak; Python instances handling 150 a second would need about 93. App Engine adds instances automatically, so the team's work is watching quotas and costs, not racking servers.
Where it still breaks. Managed databases have throughput limits per entity group or key range; hot keys (one popular course's metadata read by millions) need the Memcache layer. Write-heavy features (progress tracking) are the real scaling work.
Lesson 5: Levels.fyi on Google Sheets, and the move off it#
Assumptions.
- Traffic: the newsletter reports about 2.5 million unique visitors a month at the time of writing. Early on, submissions were a few a day and reads were modest.
- Latency: a salary comparison page should load in a second or two.
- Consistency: a new salary submission can take minutes to appear.
- Maintenance: two founders with day jobs at first; later a team of about 14.
Version 0: no backend at all. Levels.fyi began in 2017 as a site where people compare compensation across companies and levels. It launched with Google Forms to collect submissions and Google Sheets to store them, read through the Sheets API, with backups. Both newsletter and ByteByteGo explain the reasons:
- No UI to build for data entry; the form exists.
- No processing, ETL or schema to maintain; a column is a field.
- Familiar: non-engineers can view and edit data.
- Cheap, with built-in access control for who can see and edit.
Version 1: a real web page. The site moved to a plain HTML, CSS and JavaScript (jQuery) front end. An AWS Lambda function periodically read the sheets and wrote JSON files to S3, and the browser downloaded the JSON. That is a static site with a scheduled build of data, cheap and nearly impossible to take down. The drawbacks grew with traffic: no SQL analytics, Sheets API rate limits, and Lambda timeouts as the sheets grew.
Version 2: an API. A Node.js backend (NestJS) arrived, behind API Gateway with EC2 instances for lower latency than cold Lambdas, while Lambda kept doing aggregation. A static site generator rendered pages. Graphs and statistics were computed in the browser from downloaded data, which kept servers simple. The backend added spam detection, rate limiting and duplicate prevention for submissions.
Version 3: a real database. Salary data moved to Postgres on AWS RDS, replicated across regions. Lambda computes percentiles from RDS; Metabase serves internal charts; five TypeScript microservices run on a service mesh, deployed with a continuous delivery tool (TinyStacks). The newsletter notes Sheets are still used for other internal cases, and that the 10 million cell limit per spreadsheet is handled by spreading data across sheets, folders and workspaces, a kind of manual sharding.
Costs and lessons. The team ran on the AWS free tier and credits for the first two years. The lessons: keep it simple, avoid premature optimisation, and treat nothing as sacred (replace a component the moment it hurts). ByteByteGo's summary is "start simple and iterate".
Overlooked constraints.
- Rate limits and cell limits are hard walls. Sheets limits API calls and cells per spreadsheet; the design must be replaced before hitting them, not after.
- Client-side computation shifts cost to users. Downloading a large JSON file and computing statistics in the browser is free for the server but slow on phones as data grows.
- Data quality needs a backend. Spam and duplicate submissions cannot be stopped with a public form alone.
What Levels.fyi sacrificed. Query power, data validation and eventually latency in the early years, in exchange for launching in days and spending almost nothing until the product proved itself.
Deep Dive: when a spreadsheet stops being enoughShow
Sizes (handbook's illustration). 200,000 salary rows × 25 columns = 5 million cells, half of a 10 million cell limit. At 1,000 new rows a day the sheet is full in under a year, which forces sharding by year or category.
Read path cost. A 200,000-row JSON file at about 300 bytes a row is 60 MB uncompressed, perhaps 8 MB gzipped. Too heavy for every visitor, which is why the move to an API and server-side percentiles was required.
Signals to migrate. Migrate off a "toy" store when one of these appears: hitting vendor limits, needing joins or ad hoc analytics, needing validation at write time, or needing per-user access control finer than the tool provides. Until then, the toy store is the cheapest database you will ever run.
Interview angle. When asked to "design for millions" from day one, show you can name the simplest version that works for the first 10,000 users and the signals that would trigger each upgrade. See scaling from zero to millions.
Lesson 6: Zapier's task automation#
Assumptions.
- Traffic: the newsletter reports billions of tasks; a task is one step of a user's automation, such as "new email arrives, then add a row to a spreadsheet".
- Latency: most automations tolerate seconds to minutes of delay; exact run times are not promised.
- Consistency: each task should run, and at most once from the user's view.
- Maintenance: thousands of third-party APIs, each with its own limits and failures.
What a Zap is. A Zap is a user-defined workflow: a trigger (an event in one app) followed by actions (steps in other apps). Zapier stores each Zap in MySQL as a directed rooted tree: the trigger is the root, and each node is a step, with branches for conditional paths.
Front door and core. The newsletter describes Nginx in front of a Python Django web app. Session data lives in a dedicated MySQL database used as a key-value store with relaxed consistency. Long background jobs read from read replicas, where some replication lag is fine.
Running tasks. Tasks are independent: a task does not know where it sits in the tree. A workflow engine decides the order and enqueues the next task when one finishes. Work flows through RabbitMQ with Celery workers. Only the task ID goes on the queue; the worker loads the details from the database. That keeps messages tiny and means the database, not the queue, is the source of truth.
Throttling and user code. Redis counts each user's in-flight tasks, so one heavy user cannot take all workers (a per-user concurrency limit). User-written code steps run in AWS Lambda, isolated from Zapier's own servers.
Spreading the load. Many users schedule Zaps "every hour on the hour". Running them all at :00 would create a thundering herd. Zapier adds jitter (a random delay) to spread tasks, which is why it does not promise exact run times. Workers run on Kubernetes and scale on CPU and the number of ready messages in RabbitMQ; failed machines are replaced automatically.
Zap history. Users can see what each run did. Results are written to S3 and an event to Kafka; an indexer consumes the event, fetches the result from S3 and indexes it into Elasticsearch. The history UI uses GraphQL and Next.js API routes. The lesson the newsletter draws: proven, boring technology (MySQL, RabbitMQ, Redis) is enough for billions of tasks when the design is sound.
Overlooked constraints.
- Third-party APIs are the real bottleneck. Every connected app has rate limits and outages. Per-app throttling and retry with backoff matter more than raw worker count.
- At-least-once queues need idempotent steps. RabbitMQ redelivers on worker crash, so "add a row" could run twice. Task status in MySQL must be checked before side effects. See idempotency.
- Polling triggers cost money. A trigger that polls an app every few minutes for millions of Zaps is a huge request load in its own right.
What Zapier sacrificed. Exact timing (jitter), some read freshness (replicas), and the elegance of a bespoke engine, in exchange for components every engineer knows how to run and debug.
Deep Dive: why only the task ID goes on the queueShow
Message size (handbook's illustration). A task with payload might be 20 KB (the triggering email, field mappings). At 50,000 tasks a second, that is 1 GB a second through RabbitMQ, which strains memory and disk. A task ID is about 16 bytes: 800 KB a second.
Correctness. If the queue carries data, a retried message may carry an old snapshot. If it carries only an ID, the worker always reads the current state from MySQL, and can see that the task was already completed or cancelled. The database becomes the single source of truth; the queue only says "look at this".
Cost. Every task now needs a database read. At 50,000 tasks a second that is 50,000 reads a second, served by caching and read replicas. The same "notify, then read current state" idea drives Canva's migration in Lesson 11.
Jitter math. If 1 million Zaps are scheduled hourly at :00, they would all fire in the first second. Spread uniformly over 5 minutes, that is about 3,300 a second, a steady load the worker pool can be sized for.
Family 3: Peaks and structure
Lesson 7: Shopify's flash sale tactics#
Assumptions.
- Traffic: the newsletter reports peaks of about 32 million requests a minute (over 500,000 a second) during big sales events, with load balancing on Nginx and heavy Redis caching.
- Latency: checkout must stay fast under load; a slow checkout loses the sale.
- Consistency: payments must be exactly once from the buyer's view; inventory must not oversell.
- Maintenance: millions of merchants share the platform, so one merchant's flash sale must not hurt others.
What a flash sale is. A merchant releases a limited product (sneakers, a console) at a set time. Traffic rises from normal to many times normal in seconds, nearly all aimed at a few products. See the flash sale case study. The newsletter groups Shopify's approach into ten ideas.
1. Low timeouts. A slow dependency holds threads and connections while callers wait. Short timeouts make calls fail fast, freeing resources so the rest of the system keeps working.
2. Circuit breakers. If a dependency keeps failing, stop calling it for a while and fail immediately (or use a fallback). That spares the struggling service and the caller. See resilience patterns.
3. Rate limits, load shedding, back pressure and fair queueing. Rate limits cap requests per client. Load shedding drops low-value work when overloaded. Back pressure tells upstream callers to slow down. A fair queue (Shopify's checkout queue) admits buyers in first-come, first-served order instead of letting everyone hammer checkout at once. See rate limiting.
4. Monitoring the four golden signals. Latency, traffic, errors and saturation, the signals from Google's SRE book, show whether a system is healthy at a glance.
5. Structured central logging with correlation IDs. Logs in a fixed format (key-value or JSON), sent to one place, each tagged with a request ID that follows the request across services, so one failed checkout can be traced end to end.
6. Idempotency keys. Each payment attempt carries a unique key. If a retry arrives with the same key, the server returns the first result instead of charging again. This is how retries stay safe. See idempotency.
7. Reconciliation. Compare Shopify's records with financial partners' records regularly, and fix mismatches automatically where possible. Retries and timeouts make some mismatches inevitable; reconciliation catches them.
8. Load testing. Simulate flash-sale traffic before the real one to find the first bottleneck while it is cheap. See capacity planning and load testing.
9. Incident management. Clear roles during an incident: an Incident Manager On Call (IMOC) who coordinates, a Support Response Manager (SRM) who handles public communication, and the service owner who fixes the system. Afterwards, a blameless retrospective. See incident management.
10. Data isolation with shards. Merchants are spread across database shards (Shopify calls them pods). Stateless workers serve any shard, but each shard's data is separate, so one merchant's spike or failure stays inside its shard. Each shard's database is replicated across data centers for failover. See partitioning and sharding.
Overlooked constraints.
- Timeouts and retries amplify each other. A short timeout plus aggressive retries can triple load on a struggling service. Retries need backoff, jitter and budgets.
- Fairness has a cost. A queue that admits buyers in order makes the last buyers wait minutes; the product sells out before they reach checkout. That is fair but disappointing, so clear messaging matters.
- Shards fix noisy neighbours but not hot shards. A single huge merchant can make its own shard hot; very large merchants may need dedicated shards.
What Shopify sacrificed. Some buyers get queued or refused, rather than everyone getting a slow site. Engineering effort went into reconciliation and incident process, not only features.
Deep Dive: sizing a flash sale checkoutShow
Load (handbook's illustration). 2 million buyers arrive in the first minute for 50,000 units. If every buyer refreshes once every 2 seconds, the product page sees 1 million requests a second; caching the page in Redis or a CDN takes nearly all of that.
Checkout throughput. If checkout can complete 2,000 orders a second safely, selling 50,000 units takes 25 seconds. A queue admitting 2,000 buyers a second keeps checkout at its safe rate; everyone else waits on a cheap queue page.
Inventory. Reserve stock with an atomic decrement (a Redis DECR or a conditional database update "set stock = stock minus 1 where stock is greater than 0"). Oversell is impossible if the decrement is the gate.
Timeouts. If a payment call normally takes 300 ms at p99, a 2 second timeout gives headroom; a 30 second default would let a stuck partner hold thousands of threads.
Lesson 8: Shopify's modular monolith#
Assumptions.
- Traffic: the same platform; the newsletter's post title cites about 30 TB of data processed a minute at peak.
- Latency: in-process calls between domains, with no network hops.
- Consistency: each module owns its tables; cross-module changes go through public interfaces.
- Maintenance: thousands of developers working in one Ruby on Rails codebase.
The newsletter notes that this post is its own research and may differ from Shopify's actual implementation.
The decision. Shopify's core is one of the largest Rails monoliths. As it grew, changes in one area broke others, and onboarding took longer. The obvious answer was microservices. Shopify rejected that for two reasons the newsletter lists:
- Infrastructure cost: each service needs a deploy pipeline, service discovery, an API gateway and monitoring.
- Reliability: every call becomes a network call that can fail, and each service must be patched and upgraded separately.
Modules instead. Shopify split the monolith into modules, one per business domain (orders, billing, inventory, shipping), following domain-driven design. See domain-driven design.
- High cohesion: related code lives together in one module.
- Low coupling: each module exposes a public interface; everything else is private. Calling a module's internals from outside raises an error, enforced by tooling. Modules with too many cross-dependencies are merged.
- One process: all modules run together, so calls are function calls with no serialisation or network.
- Separate data: each module has its own directory and its own database schema. There are no transactions across modules; modules cooperate through interfaces and events.
Benefits. Changes stay inside one module; developers work faster; no network overhead; one deploy; low infrastructure cost; and if a module later needs to be a separate service, its boundary is already clean, so extraction is easier. See monolith vs microservices.
Overlooked constraints.
- One process means shared fate. A memory leak or a crash in one module still takes down the process. Modules isolate code, not runtime faults.
- One deploy means one release train. Every team's change ships together, so a broken test anywhere blocks everyone; this needs strong CI and fast rollbacks.
- No cross-module transactions is a real constraint. Placing an order and reserving stock become two steps that can partially fail, needing compensation, as in microservices.
What Shopify sacrificed. Independent scaling and deployment per domain, and fault isolation, in exchange for lower cost, simpler operations and in-process speed.
Deep Dive: enforcing module boundariesShow
The mechanism. Boundaries hold only if they are checked automatically. Shopify built and open-sourced a static checker for Ruby called Packwerk, which flags references from one package to another's private constants. Most module systems use the same idea: declare dependencies and public files, then fail the build on violations.
Measuring coupling (handbook's illustration). Count cross-module references per module. A module with 400 incoming references to private code is not yet a module. Track that count down to zero over months, merging modules whose mutual references stay high.
Data boundaries. Separate schemas allow a later move to separate databases. A query joining orders and inventory tables is a violation; it must become two calls or a read model fed by events.
When to extract. Extract a module into a service only when it needs a different scaling profile (say, a CPU-heavy image service), a different release cadence, or isolation for security or compliance. Otherwise the modular monolith is cheaper.
Lesson 9: Razorpay's flash sales#
Assumptions.
- Traffic: IPL ticket sales and similar events push payment traffic far above normal in minutes; the newsletter describes peaks around 1,500 requests a second for one event, with over 23 million fans in the audience.
- Latency: payment pages must stay quick while banks slow down.
- Consistency: no double charges; payment states must be exact.
- Maintenance: a shared payment platform where one merchant's sale must not starve others.
The full story is on the Razorpay engineering page (its peaks lesson). In brief:
- A rate limiter sidecar. Nginx running next to each service applies fixed-window rate limits per merchant, so one merchant's sale cannot exhaust shared capacity.
- A database proxy sidecar. ProxySQL pools and multiplexes database connections, so thousands of app pods do not open thousands of database connections each.
- Pre-scaling. Capacity is added before the event starts, because reactive auto-scaling lags a spike that arrives in seconds.
- Smart routing. When a bank or gateway degrades under load, payments route to healthier ones, using health and success-rate signals (the Razorpay page covers its ML-based routing).
The newsletter's version of this story says it may differ from the real system, so treat the Razorpay page, built from Razorpay's own posts, as the primary reference.
Overlooked constraints.
- The bottleneck is often outside your system. Banks and card networks have their own limits, so routing around them matters more than adding pods.
- Fixed windows allow bursts at boundaries. Up to twice the limit can pass around a window edge; that is acceptable when the limit has headroom.
- Pre-scaling needs a calendar. Someone must know about the sale in advance; surprise sales still depend on auto-scaling.
What Razorpay sacrificed. Idle capacity cost before and during events, and some rejected requests at the rate limiter, in exchange for steady success rates during the spike.
Deep Dive: Shopify versus Razorpay on the same problemShow
Shared ideas. Both shed or queue excess load at the edge, protect databases with connection management, isolate tenants (shards at Shopify, per-merchant limits at Razorpay), make payments idempotent and reconcile with partners.
Different emphasis. Shopify sells inventory, so the hard part is fairness and not overselling: a checkout queue and atomic stock decrements. Razorpay moves money through banks it does not control, so the hard part is downstream health: routing between gateways and banks by success rate.
Connection math (handbook's illustration). 400 pods with a pool of 20 connections each would be 8,000 MySQL connections, far beyond a comfortable limit of a few thousand. A proxy that multiplexes them onto 500 backend connections keeps the database healthy.
Family 4: Moving data while live
Lesson 10: Tumblr moving 60 billion rows across data centers#
Assumptions.
- Traffic: the newsletter reports a MySQL fleet with about 21 TB of data, over 60 billion rows and more than 200 database servers, with the leaders of different clusters spread across data centers.
- Latency: reads must stay local and fast throughout.
- Consistency: writes go to a single leader per cluster; the move must not lose or duplicate writes.
- Maintenance: data center moves and leader changes are routine operations, so they must be automated.
The problem. Tumblr needed to move database leaders from one data center to another. The brute-force way is: stop traffic, move the leader, repoint everything, and turn traffic back on. With 200 servers and many clusters, that means long periods of downtime, which is poor availability.
Split reads from writes. Tumblr's setup is leader-follower replication: the leader takes writes; followers copy them and serve reads. The newsletter describes this as a CQRS-style split (separate paths for reads and writes). Followers live in each data center, so reads are always local. Only writes must reach the leader, possibly in another data center. See replication.
The cross-data-center connection problem. Applications in data center B that write to a leader in data center A keep connections open across the wide-area network. The newsletter reports that these connections dropped often, and reconnecting is expensive (TCP and TLS handshakes over a long round trip, plus MySQL authentication). So Tumblr put ProxySQL in the local data center. Applications connect to the local proxy cheaply; the proxy keeps a pool of persistent connections to the remote leader and reuses them.
The migration. Each data center keeps metadata about its followers, the current leader and the proxy configuration. To move a leader from data center A to B:
- Promote a follower in B to be the new leader (after it has caught up).
- Automation updates the metadata and repoints the followers and the proxies at the new leader.
- Reads continue throughout from local followers. Writes see a few seconds of read-only time, during which they are rejected or buffered and retried.
Why not multi-leader? Leader-leader replication (both data centers accept writes) would avoid read-only time. The newsletter suggests Tumblr avoided it because concurrent writes to two leaders can conflict, and resolving conflicts is complex and error-prone. See multi-region data.
Overlooked constraints.
- Catch-up must be verified. Promoting a follower that is behind loses writes. The old leader must stop accepting writes and the new one must apply everything up to that point before promotion.
- Split brain. If the old leader comes back and still thinks it is the leader, two leaders accept writes. Fencing (making the old leader read-only and blocking its traffic) prevents it.
- Write latency rises for remote writers. After the move, applications in data center A now write across the WAN, so their write latency grows by a round trip.
What Tumblr sacrificed. A few seconds of write availability per move and cross-data-center write latency, in exchange for avoiding multi-leader conflicts and keeping reads always available.
Deep Dive: the cost of reconnecting across a WANShow
Handshake math (handbook's illustration). A round trip between data centers is 60 ms. A new MySQL connection over TLS needs about 3 to 4 round trips (TCP, TLS, MySQL authentication): about 200 ms before the first query. If 1,000 app processes reconnect after a network blip, the leader also faces a burst of 1,000 authentications.
With a local proxy. Apps connect to ProxySQL over the local network in under 1 ms. The proxy holds, say, 200 warm connections to the leader and multiplexes thousands of app connections over them. A WAN blip affects only those 200, which the proxy re-establishes in the background.
Read-only window. If the new leader needs 2 seconds to catch up and repointing takes 3 seconds, writes are blocked for about 5 seconds. At 5,000 writes a second, 25,000 writes must be buffered and retried by clients, or failed with a clear "try again" error.
Lesson 11: Canva's media service, MySQL to DynamoDB at 50 million uploads a day#
This lesson comes from Canva's own engineering blog (Jacky Chen and Robert Sharp, 2022).
Assumptions.
- Traffic: Canva reports more than 100 million monthly active users, about 50 million new uploads a day and more than 25 billion stored media items, plus over 100 million stock photos and graphics.
- Latency: editing designs reads media constantly; reads must be fast.
- Consistency: reads tolerate a little lag (eventual consistency); writes must be durable.
- Maintenance: a growing team that needs schema changes and upgrades without downtime.
What the media service stores. For each media item: its ID, owner, whether it is in the stock library, external source, status (active, trashed, pending deletion), metadata (title, artist, keywords, colour) and references to the stored files. The workload is read-heavy, media is rarely changed after creation, and recent media is read most.
How far MySQL went. The service began on MySQL on Amazon RDS. It scaled vertically to bigger instances, then added read replicas for eventually consistent reads. Then the problems piled up:
- Schema changes took days, and online DDL slowed live traffic. The gh-ost tool (online schema migration) helped, but migrations still took up to six weeks.
- Replication throughput of MySQL 5.6 hit a ceiling.
- RDS storage was capped at 16 TB at the time, and every storage increase added latency.
- Restarts and upgrades needed downtime, because the database depended on a warm buffer pool.
- The ext3 file system limited table files to 2 TB.
Stopgaps in mid-2017. Approaching a billion media items, the team bought time:
- Moved metadata into a JSON column with the schema managed by the service.
- Denormalised tables to avoid joins.
- Removed or shortened repeated content (such as S3 bucket names in every row).
- Dropped foreign keys.
- Reduced metadata updates during imports.
- Added application-level sharding tuned for lookups by ID, with scatter-gather queries across shards for "list by user".
Choosing DynamoDB. The runway was short, so they needed a managed store the team already had experience with, and they prototyped first. DynamoDB fit: horizontal scaling, no schema migrations, single-digit millisecond reads by key. See DynamoDB.
The live migration. They considered dual writes from the app, an ordered change log, and AWS Database Migration Service. They chose something simpler:
- On every create, update or read of a media item, the service sends an SQS message that says only "media X changed or was read". It carries no content.
- A worker receives it, reads the current state from the MySQL primary, and writes to DynamoDB if needed. Because the worker always reads the latest state, messages can arrive out of order, be retried, be paused or be slowed down without corrupting data.
- Two queues: high priority for creates and updates (correctness), low priority for reads (warming).
- A scan from newest to oldest media fed the low-priority queue to backfill everything, with back pressure: it advanced only while the queue was nearly empty. Newest first matched "recent media is read most".
Cutting over.
- Dual reads with comparison to find differences.
- Eventually consistent reads moved to DynamoDB, with a fallback to MySQL for media not yet replicated.
- Non-ID queries (list by owner) moved only after the full scan finished.
- Writes moved last, using DynamoDB transactions and conditional writes, with integration tests running against both stores, an end-to-end suite, a written runbook, a flag to send reads back to MySQL within seconds, and rehearsals in development and staging.
The cutover was seamless, and latency improved. Canva's lessons: be lazy (migrate hot data first), do it live, and test in production with safe fallbacks. Since then, monthly active users more than tripled; DynamoDB was reliable and cheaper than RDS.
Overlooked constraints.
- Notify-then-read doubles primary reads. Every message causes a read on the MySQL primary, the very database already under strain. Priorities and back pressure kept that load safe.
- Query patterns must be known in advance. DynamoDB serves only the access patterns you design for. Listing media by owner needed a secondary index designed up front.
- Fallback reads hide gaps. If the MySQL fallback fires often, migration is incomplete; it must be measured, not just relied on.
What Canva sacrificed. Canva's post is candid: schema changes and backfills now need custom parallel-scan code; ad hoc SQL is gone (replaced by change data capture into the data warehouse); and composite secondary indexes must be built by hand by concatenating attributes. Looking back, they said they would also consider Spanner or CockroachDB, which scale horizontally while keeping SQL.
Deep Dive: why ID-only messages make migration safeShow
The ordering problem. With dual writes, the app writes MySQL then DynamoDB. If two updates race, DynamoDB may apply them in the opposite order and keep the older value forever. A change log fixes ordering but must be consumed strictly in order, so one stuck message blocks everything.
ID-only messages are idempotent. "Media X changed" carries no state. Processing it twice, or out of order, has the same effect: copy MySQL's current state of X. The last processing wins and is always current. This is the same idea as Zapier's task-ID queue in Lesson 6 and the outbox and CDC patterns: the source of truth stays in one place.
Backfill time (handbook's illustration). 10 billion items, worker capacity 20,000 copies a second: about 6 days of scanning. With newest-first order, the media read most often is migrated in the first hours, so the read cutover can start long before the scan ends.
Back pressure. If the low-priority queue holds more than, say, 10,000 messages, the scanner pauses. That keeps capacity for live updates and caps the extra load on MySQL.
Family 5: Real time at huge scale
Lesson 12: WeChat's chat architecture#
Assumptions.
- Traffic: the newsletter reports about 1.67 billion monthly active users; concurrent users grew from 491 at launch in 2011 to more than 400 million.
- Latency: messages should arrive in well under a second when both users are online.
- Consistency: no lost messages; within a chat, messages in order; group chats may be eventually consistent.
- Maintenance: very fast feature growth; the team's principle was release first, optimise later.
The message flow. The receiver may be offline, so the server stores every message before delivering it. It then notifies the receiver that something new is waiting, and the receiver's client fetches new messages. Delivery runs through an asynchronous message queue, because fanning a group message out to hundreds of members takes time. Groups are capped at 500 members, and the server tracks each member's last-read index so a client asks only for messages after it.
Three layers, in C++. WeChat's back end is written in C++ on Svrkit, an in-house RPC framework.
- Access layer: holds client connections, receives requests and pushes notifications. The protocol is not public; the newsletter suggests something like WebSockets (persistent two-way connections). See real-time communication.
- Logic layer: many independently deployable modules, split by function and importance, so a failure in a minor feature does not affect messaging.
- Storage layer: MySQL and SDB (a simple key-value store from strings to values), with Memcached in front.
Storage details.
- SDB holds last-read indexes and contact lists, replicated asynchronously from leader to followers. If the leader crashes, followers keep serving reads.
- MySQL holds accounts and messages. Writes use multiple leaders; reads go to followers, and strongly consistent reads go to the leader. That left two problems: replication lag on followers and single points of failure.
- KVSvr was built on top to fix them: a quorum-based, strongly consistent key-value store with asynchronous replication, high write performance and a cache. See quorums.
Syncing data. The server sends the client key-value snapshots: the client says what version it has, and the server sends what changed. This keeps sync efficient on slow mobile networks.
Multiple data centers. WeChat started in Shanghai, then added Hong Kong and Canada. Each data center is self-contained (a full stack). Users are segmented by region: Chinese users are served from Shanghai, international users elsewhere, with asynchronous replication between data centers. A quorum-based queue syncs data between data centers, and only special cases, such as allocating globally unique account IDs, need cross-data-center coordination. Group chats across regions are eventually consistent.
Overlooked constraints.
- Notify-then-fetch costs an extra round trip, but it makes the push tiny and lets offline clients catch up through the same fetch path. One code path for online and offline is simpler than two.
- Group cap is a design constraint, not a product whim. Fan-out cost grows with group size; capping at 500 bounds the work per message.
- Regional segmentation simplifies consistency but complicates cross-region chats. A chat between a user in China and one abroad crosses data centers with eventual consistency.
What WeChat sacrificed. Global strong consistency (regions are mostly independent), polish in early versions (release first), and simplicity in storage (three stores plus caches), in exchange for growth from hundreds to hundreds of millions of concurrent users.
Deep Dive: handling billions of users in a chat designShow
Connections (handbook's illustration). With 1 billion users and about 20 percent online at once, 200 million persistent connections are open. At 1 to 2 million connections per tuned server, that is 100 to 200 connection servers, before redundancy.
Routing the message to the right server. A plain load balancer spreads users randomly, so the sender's server does not know where the receiver is connected. Three options:
- A topic per user in Kafka. Kafka is not designed for a billion topics: each topic costs metadata (roughly 50 KB each), so about 50 TB of overhead. Not workable.
- Consistent hashing of users to chat servers, tracked in ZooKeeper or etcd. Servers then know where to forward each message, but they need connections to each other, rebalancing must be careful, and a failed server makes many clients reconnect at once (a thundering herd). See consistent hashing.
- Redis pub/sub per user, sharded. The connection server subscribes to channels for its connected users; senders publish to the receiver's channel. Pub/sub is at-most-once, so the message and the receiver's inbox are written durably first, and publish is only a best-effort fast path. If the publish is lost, the client's next fetch finds the message. The Hello Interview material cites a Canva benchmark of about 100,000 mouse-pointer updates a second on a single Redis instance at about 27 percent utilisation, which shows how cheap this path is. See pub/sub.
Per user or per chat channels. For one-to-one chats, a channel per user is efficient: each user subscribes once. For large groups, publishing to every member's channel multiplies work, so a channel per chat is better. An adaptive approach switches chats above a threshold (say 25 members) to chat channels, publishing to both during the transition so no client misses a message.
WeChat's answer. WeChat's store-then-notify-then-fetch model is the same principle: durability first, push as a hint. See the chat system case study.
Family 6: Synthesis
Lesson 13: What these smaller stories teach#
Put side by side, the eleven stories repeat a small set of patterns.
| Pattern | Stories | The idea |
|---|---|---|
| Push reads toward the user | Giphy, Khan Academy, Levels.fyi V1 | CDN edges and static JSON serve most traffic; the origin stays small |
| Protect the origin from bursts | Giphy shield, Shopify queue, Zapier jitter | Collapse, queue or spread requests so the backend sees a steady rate |
| Precompute for the common case | Hashnode feeds, Levels.fyi percentiles | Do work once at write time or on a schedule, not on every read |
| Queue IDs, not payloads | Zapier tasks, Canva migration | The queue says "look at X"; the database holds the truth, so retries and reordering are safe |
| Store first, notify second | WeChat, chat at billions | Durable write is the guarantee; push is a best-effort hint |
| Isolate tenants | Shopify shards, Razorpay per-merchant limits, Zapier per-user throttle | One customer's spike stays contained |
| Measure what you cannot prevent | Meta Polaris, Canva dual reads | Turn "maybe inconsistent" into a number you can alert on |
| Start with the simplest thing | Levels.fyi Sheets, Khan Academy YouTube, Shopify monolith | Use existing tools until a concrete limit forces a change |
| Move data live, hot first | Tumblr, Canva | Keep reads available, migrate recent data first, keep a fast rollback |
| Avoid write conflicts | Tumblr single leader, WeChat regional segmentation | Prefer one writer per item over resolving conflicts |
Three meta-lessons.
- The constraint usually sits outside the code. Sheets API limits, RDS storage caps, ext3 file limits, bank success rates, Kafka topic overhead. The architecture changed when an external limit was hit, not when the code was ugly.
- Teams choose the boring option on purpose. Zapier with MySQL and RabbitMQ, Shopify with Rails, Khan Academy with App Engine. The saved effort went into the one problem that was unique to them.
- Every story has an exit plan. Levels.fyi kept moving; Canva had a flag to send reads back to MySQL; Shopify's modules can become services. Good early choices are the ones you can leave.
What these teams sacrificed overall. Most of them gave up something that looks important on paper: exact timing (Zapier), perfect personalisation (Hashnode), global strong consistency (WeChat), ad hoc SQL (Canva), independent deploys (Shopify), control over delivery (Khan Academy, Giphy). In each case, the thing given up mattered less to users than what was gained.
Deep Dive: mapping famous company architectures to handbook topicsShow
The System Design Primer keeps a list of public architecture write-ups from many companies. Rather than repeat them, use this map to study each through the matching handbook pages:
| Company write-ups | What to study | Handbook page |
|---|---|---|
| Facebook memcached and TAO | Cache leases, invalidation, graph cache | Meta engineering, distributed caching |
| Netflix | Microservices, chaos engineering, CDN | Netflix engineering |
| Uber | Geospatial dispatch, schemaless storage | Uber engineering, ride hailing |
| Twitter, Instagram, Pinterest, Tumblr | Feeds, fan-out, sharded MySQL | news feed, Instagram |
| WhatsApp, WeChat | Long-lived connections, chat delivery | chat system |
| YouTube, Justin.tv | Video storage and delivery | video streaming |
| Dropbox | File sync, block storage | file sync |
| Google, Amazon | Bigtable, Dynamo, GFS papers | landmark papers |
| Stack Overflow, PlentyOfFish | Scaling up a few large servers | Stack Overflow, scaling from zero |
| Flickr, TripAdvisor, ESPN, Salesforce, DataSift, Mailbox, Playfish, Cinchcast | Classic web-scale stacks | real-world architecture lessons |
When reading any such write-up, apply the same four questions used on this page: what were the traffic, latency, consistency and maintenance assumptions; what is the production architecture; which constraint did they hit; and what did they give up.
Cross-cutting interview topics#
These stories answer several classic interview deep dives directly.
Cache architectures. Four ways to place a cache, and when each fits:
| Pattern | How it works | Good for | Watch out for |
|---|---|---|---|
| Cache-aside | App checks cache; on miss reads DB, fills cache, returns | The default for most read-heavy apps | Miss latency; stale data until invalidated |
| Write-through | Writes go to the cache, which writes the DB synchronously | Data read right after writing | Slower writes; cache fills with data never read; still a dual write; Redis does not do it natively |
| Write-behind | Writes go to the cache; DB updated later in batches | Counters, metrics, analytics | Data lost if the cache dies before flushing |
| Read-through | The cache itself fetches from the DB on a miss | CDNs (Giphy, Khan Academy) | The cache must know how to load data |
See caching strategies.
Cache consistency. The simplest reliable approach is to delete the cache entry on write (not update it) and let the next read refill it, plus a short TTL as a safety net. Accept eventual consistency where users do not notice (feeds, view counts). Close the fill race with leases or versions (Lesson 3). For hot keys, replicate the key across several cache nodes, keep a small in-process cache in each app server, and rate-limit abusive clients. See cache failure modes.
Levels of consistency. Pick the weakest level the feature can tolerate:
- Strong: every read sees the latest write. Bank balances, inventory at checkout.
- Causal: effects appear after their causes. A comment never appears before the post it replies to.
- Read-your-own-writes: a user always sees their own changes. Your profile edit shows immediately for you, even if others see it a second later.
- Eventual: replicas converge given time. DNS, like counts, Hashnode's feed, WeChat's cross-region group chats.
See distributed systems fundamentals and time and ordering.
Millions of concurrent reads for the same cached data. One hot key (a viral GIF, a celebrity's profile) can overload the single cache node that owns it. Defences, from cheapest:
- Request coalescing (single flight): only one request per key goes to the backend on a miss; others wait for its result.
- Local in-process caches with a TTL of a few seconds, so most reads never leave the app server.
- Hot-key replication: store copies under several keys (key-1 to key-N) on different nodes and read a random one.
- CDN for anything public, as Giphy does.
See scaling reads.
Invalidation when updates must be visible immediately. Use write-invalidate with versions so stale fills are rejected, leases to stop the fill race, and read-your-own-writes routing (the writer reads from the primary for a few seconds). If truly every reader must see the change at once, the data should not be cached, or should be cached with versions checked on every read.
An aggregated feed from thousands of sources. A news aggregator (such as Google News) collects articles from thousands of publishers, shows an infinitely scrolling feed, and sends readers to the publisher's site on click. It favours availability over consistency: showing a slightly old feed is better than showing an error. Hashnode's design transfers directly: ingest events, score articles, precompute feeds (or regional feeds for anonymous users) in Redis, page with cursors, and cache the rendered pages at a CDN so a breaking-news spike hits cached pages, not the database. See the Google News case study.
Billions of simultaneous chat users. See the WeChat deep dive above: store first, then notify through sharded pub/sub or consistent-hash routing, and choose per-user or per-chat channels by group size.
When to Use It#
Use these stories as templates when your problem looks like theirs:
- Mostly reads of immutable content: Giphy's CDN, edge and shield design.
- Personalised feeds on a small team: Hashnode's event-driven precompute with serverless functions.
- A tiny team facing sudden growth: Khan Academy's managed services and CDN.
- A brand-new product with unknown demand: Levels.fyi's no-backend start.
- User-defined workflows across many APIs: Zapier's tree of tasks, ID-only queue and per-user throttling.
- Known traffic spikes: Shopify's ten tactics and Razorpay's pre-scaling and routing.
- A large codebase that feels tangled: Shopify's modular monolith before microservices.
- Moving a database leader or changing databases: Tumblr's proxy-based leader move and Canva's ID-only live migration.
- Real-time messaging: WeChat's store-notify-fetch model.
When NOT to Use It#
- Do not copy the tools, copy the reasoning. Google Sheets worked for Levels.fyi because of its tiny write rate; it is the wrong choice for anything transactional.
- Do not precompute for everyone. Hashnode precomputes only for active users; precomputing for all users wastes memory.
- Do not use ID-only migration when the source is gone. It needs a live source of truth to read from; for archived data, use bulk export.
- Do not cap groups at 500 because WeChat did. The cap follows from fan-out cost; pick yours from your own numbers.
- Do not assume a modular monolith fixes runtime isolation. If one domain's crashes keep taking down the others, it may need to be a separate process.
How to Implement It#
Turn a story into your design in five steps:
- Write the assumptions first. Traffic (peak QPS and its shape), latency target, consistency per feature, and who will run it.
- Find the dominant cost. Reads, bursts, data size or connections. One of them usually decides the design.
- Pick the matching pattern from the synthesis table.
- Name the exit. What limit would force a change, and how you would migrate live.
- List what you are giving up, and confirm users will not miss it.
An illustration of a migration plan in the style of Canva's, written as a configuration file (the handbook's example, not Canva's real config):
migration: media-metadata-mysql-to-dynamodb
replication:
message: id-only # "media X changed"; worker reads current state
queues:
high: [create, update]
low: [read, backfill]
backfill:
order: newest-first
pause_when_low_queue_depth_above: 10000
cutover:
- stage: dual-read-compare
- stage: id-reads-to-dynamodb
fallback: mysql
- stage: list-queries-to-dynamodb
requires: backfill-complete
- stage: writes-to-dynamodb
requires: [rehearsal-staging, runbook, integration-tests-both-stores]
rollback:
flag: media_reads_source # flip to mysql within secondsTechnology choices.
| Need | Choice in these stories | Alternatives |
|---|---|---|
| Global delivery of files | Fastly CDN with shielding (Giphy, Khan Academy) | Cloudflare, Akamai, CloudFront with Origin Shield |
| Precomputed feeds | Redis lists via Upstash (Hashnode) | Redis Cluster, Cassandra wide rows |
| Event bus | AWS EventBridge (Hashnode) | Kafka, SNS with SQS |
| Workflow queue | RabbitMQ with Celery (Zapier) | SQS, Kafka, Temporal for long workflows |
| Search over history | Kafka to Elasticsearch (Zapier) | OpenSearch, ClickHouse for analytics |
| Connection pooling to a remote DB | ProxySQL (Tumblr, Razorpay) | PgBouncer for Postgres, RDS Proxy |
| Key-value store at scale | DynamoDB (Canva, Giphy) | Cassandra, ScyllaDB, Spanner or CockroachDB when SQL is needed |
| Managed app hosting | App Engine (Khan Academy) | Cloud Run, AWS Lambda, Fargate |
| Chat storage with quorum | KVSvr (WeChat) | Cassandra, ScyllaDB, FoundationDB |
Trade-offs#
| Decision | Gain | Cost |
|---|---|---|
| CDN with shield tier | Tiny origin, low latency | Vendor dependence; extra hop on shield misses |
| Precomputed feeds | O(1) reads | Memory, fan-out cost, stale rankings |
| Measured cache consistency | Rare, visible staleness | A whole system that serves no users |
| Managed services | Small team, auto-scaling | Lock-in, less tuning control |
| Spreadsheet as database | Launch in days, free | Hard limits, no SQL, no validation |
| ID-only queue messages | Safe retries and reordering | Extra database read per message |
| Fair checkout queue | No meltdown, fair order | Late buyers wait and may miss out |
| Modular monolith | Low cost, in-process speed | Shared fate, one release train |
| Single leader with proxy | No write conflicts | Seconds of write pause; remote write latency |
| Live migration to DynamoDB | Scale and no schema migrations | No ad hoc SQL, hand-built indexes |
| Regional segmentation | Simple consistency per region | Cross-region chats eventually consistent |
Common Pitfalls#
- Caching mutable data with long TTLs. Giphy can cache forever because GIFs never change; a profile picture cannot.
- Updating the cache on write instead of deleting. Two concurrent writers can leave the older value in the cache.
- Retries without idempotency. A timed-out payment retried without a key may charge twice.
- Scheduling everything on the hour. Without jitter, a scheduler creates its own thundering herd.
- Promoting a lagging follower. Writes acknowledged by the old leader are lost.
- Dual writes from the app during a migration. Races leave the new store with older values.
- Migrating oldest data first. Hot, recent data waits longest; cutover is delayed.
- Splitting into microservices to fix a tangled codebase. Without module boundaries, you get a distributed tangle.
- Treating pub/sub as durable. Redis pub/sub drops messages for disconnected subscribers; store first.
Real-World Examples#
- Giphy: about 10 billion GIFs a day through Fastly with origin shielding, per the newsletter.
- Hashnode: feeds precomputed for active users with EventBridge, Lambda, Step Functions and Upstash Redis.
- Meta: TAO cache consistency within five minutes raised from six to ten nines with Polaris and targeted tracing.
- Khan Academy: 30 million students in April 2020 on App Engine, Datastore, Fastly and YouTube, after a Python to Go migration.
- Levels.fyi: Google Forms and Sheets to S3 JSON to a Node API to Postgres on RDS.
- Zapier: billions of tasks on Django, MySQL, RabbitMQ, Celery, Redis and Kubernetes.
- Shopify: about 32 million requests a minute at peak; ten flash-sale tactics; a Rails modular monolith.
- Razorpay: rate-limit and ProxySQL sidecars, pre-scaling and smart routing for IPL ticket sales.
- Tumblr: a 21 TB, 60-billion-row MySQL fleet with leaders moved between data centers via ProxySQL.
- Canva: 25 billion media items moved from MySQL to DynamoDB live, with ID-only SQS messages.
- WeChat: 1.67 billion monthly users on a three-layer C++ stack with quorum storage and regional data centers.
In the Interview#
Deep Dive: putting several stories into one designShow
Problem. Design a sticker and GIF platform for a messaging app: 300 million daily users, 5 billion sticker views a day, user uploads, a personalised "trending for you" tray, and real-time delivery inside chats.
Assumptions (handbook's illustration). Views average 58,000 a second with peaks of 200,000. Uploads are 2 million a day. Stickers are immutable once uploaded. The tray can be minutes stale. Chat messages must never be lost.
Delivery (Giphy). Store sticker files in object storage, metadata in a key-value store, and serve through a CDN with a shield tier and request collapsing. With a 99.5 percent hit ratio, the origin sees about 1,000 requests a second at peak.
Tray (Hashnode). Upload and view events go to an event stream. A job scores stickers by recent views, normalised for diversity, and precomputes a tray of 100 sticker IDs per active user in Redis. Inactive users get a regional trending tray.
Upload pipeline (Zapier). Each upload enqueues only its ID; workers load the record, transcode, moderate and publish, with per-user throttling and idempotent steps.
Chat delivery (WeChat). A sticker message is stored first with an index per chat, then the receiver is notified through sharded pub/sub; the client fetches after its last-read index.
Growth and migration (Canva, Tumblr). If the metadata store outgrows its first database, migrate live with ID-only messages, newest first, and a flag to flip reads back.
What this design gives up. Trays are minutes stale; uploads take seconds to become visible; and the CDN is a vendor dependency. All three are acceptable for stickers.
Key Takeaways#
- Smaller company stories show one idea clearly: a CDN shield (Giphy), precomputed feeds for active users (Hashnode), measured cache consistency (Meta).
- Simple, managed and boring stacks go a long way: Khan Academy on App Engine and YouTube, Levels.fyi on Google Sheets, Zapier on MySQL and RabbitMQ.
- Peaks are handled with fail-fast timeouts, circuit breakers, fair queues, idempotency, reconciliation and tenant isolation (Shopify), plus pre-scaling and routing (Razorpay).
- A modular monolith with enforced public interfaces gives most of the benefits of microservices without network calls.
- Live migrations work best with a single source of truth: proxies and automation for a leader move (Tumblr), ID-only messages and hot-first backfill for a database change (Canva).
- Real-time chat at billions of users stores first and notifies second (WeChat).
- In every story, the team gave something up on purpose: timing, personalisation, global consistency, SQL or independent deploys. Name that cost in your own designs.