Summary#
Textbook patterns become convincing when you see them survive production. This page takes six engineering write-ups and breaks each one into its problem, constraints, rejected options, chosen fix, trade-offs, and what the write-up leaves unsaid. Every company fact here comes from the summaries of those posts in this handbook's reference set; the explanations of the underlying mechanisms are general engineering knowledge.
- Shopify: inventory reservations moved from Redis to MySQL.
- The problem: reservations lived in Redis while the ledger lived in MySQL. Because the two writes couldn't commit together, a crash between them either hid stock or oversold it.
- The fix: a bounded pool of rows, one per reservable unit, claimed with
SELECT … FOR UPDATE SKIP LOCKEDinside the ledger's own transaction. - The hardening: a clustered primary key, READ COMMITTED isolation, and consistent lock ordering.
- The lesson: if two things must commit together, put them in the same database.
- Discord: trillions of messages moved from Cassandra to ScyllaDB, with a request-coalescing layer in front.
- The problem: popular channels made hot partitions. Compaction backlogs and JVM garbage-collection pauses made the cluster fragile.
- The fix: ScyllaDB made each read cheaper. Rust data services, routed by
channel_idwith consistent hashing, coalesced duplicate in-flight reads. - The result: 177 nodes became 72, and p99 reads went from 40–125 ms to a steady 15 ms.
- The lesson: a faster database and less database work are different fixes.
- Slack: Kafka in front of the Redis job queue.
- The problem: the whole backlog lived in Redis RAM. A slow database filled memory, and the queue locked up and couldn't even dequeue.
- The fix: Kafka became a durable on-disk buffer, with a throttled relay feeding Redis. Redis kept the job semantics the app relied on.
- The lesson: keep the backlog where it can't run out of memory, and let the fast layer hold only what's in flight.
- Figma: multiplayer editing on "simplified CRDTs".
- The design: a document is a tree of objects, and every property is a last-writer-wins register ordered by a single server process per document. The parent link is just another property, moves that would create cycles are rejected by the server, and sibling order uses fractional positions.
- The lesson: trade a hard algorithms problem for a smaller infrastructure problem.
- Spotify: point queries on an exabyte Parquet data lake (RAP, Random Access Parquet).
- The design: bucketing and Bloom filters prune 90,000 candidate files to about 12. An external multimap index then resolves a key directly to file and row numbers, so the reads run in parallel. Writing pages per key and covering values in the index shrink or remove the read.
- The lesson: a cheap third option between scanning the lake and copying everything to a key-value store.
- Meta: ZGateway in front of ZippyDB.
- The design: a reverse proxy for over a million client hosts applying five techniques: connection pooling, batching, request coalescing, read-through caching with fill locks and CDC freshness, and admission control with bounded per-use-case queues.
- The lesson: find where the database actually spends its resources before choosing how to scale it.
- Recurring themes:
- put atomic things in one transaction boundary;
- separate concerns that compete for one resource;
- reduce work before making work faster;
- route related work to one place so it can be merged or ordered;
- bound every queue and pool;
- revisit old conclusions when tools change;
- evolve systems incrementally ("organic system design") instead of rewriting them.
Why It Exists#
Patterns pages tell you what tools exist. Production write-ups show you why a team picked one, what it cost, and what broke first. That knowledge is hard to get any other way, for four reasons:
-
Real constraints are messier than interview prompts. Shopify had years of code built on MySQL as the ledger. Slack had application code depending on exact Redis queue semantics. Spotify had exabytes of Parquet already in object storage. In each case the "best" textbook answer lost to the answer that fit the existing system. Learning to design within constraints is the core senior skill.
-
Failure modes teach more than success stories. Each write-up starts with something breaking:
- a dual write that couldn't be atomic;
- one hot partition slowing unrelated queries;
- a full Redis that couldn't even dequeue;
- a conflict-resolution scheme that was too hard to get right.
Knowing the failure tells you when a pattern is actually needed.
-
The same few ideas keep recurring. Request coalescing appears at both Discord and Meta. "One row per unit" connects Shopify to ticket booking. "A durable log in front of a fast layer" connects Slack to countless pipelines. "A single owner orders the writes" connects Figma to every leader-based system. Seeing the repeats builds the intuition interviewers look for.
-
Interviews reward grounded examples. "Discord ran into exactly this with hot channels, and coalescing reads by channel fixed most of it" is more persuasive than "we could add a cache". The examples also give you vocabulary for trade-offs: Discord chose coalescing over caching to avoid invalidation, and Slack accepted leader-only acks for latency.
This page is a companion to Choosing the Right Pattern. That page tells you which pattern solves which problem; this one shows each pattern under real load.
How It Works#
How to read an engineering write-up#
Read every case on this page, and every engineering blog you meet later, with the same seven questions. They turn a story into reusable design knowledge.
- What was the workload? Its shape (read-heavy, write-heavy, bursty, skewed), its numbers, and the critical path.
- What broke, or what was about to? The symptom ("latency spikes", "queue down") and the underlying cause ("two writes can't commit together", "the burst buffer shares RAM with dispatch").
- What constraints were fixed? Existing systems, data volume, code that depends on current behaviour, team skills, cost targets.
- Which options were rejected, and why? This is often the most valuable part. Slack rejected rebuilding on Kafka alone, RabbitMQ, SQS, beanstalkd and Redis persistence, each for a specific reason.
- What was chosen, and what mechanism makes it work? Not "they used MySQL" but "they used
SKIP LOCKEDover a pool of unit rows inside the ledger transaction". - What did it cost? New processes to run, added latency, memory, operational risk, lost features.
- What's not said? Missing numbers, unmentioned failure paths. The Shopify post doesn't describe how expired holds are reclaimed, and the Spotify post gives no production latency figures. Treat unmeasured claims with healthy scepticism.
Lesson 1: Shopify, inventory reservations from Redis to MySQL#
The workload. Shopify handles more than 14% of U.S. e-commerce. Every inventory-backed checkout passes through an oversell-protection system: when a buyer starts paying, their items are reserved for a few minutes, so nobody else can take them mid-payment. Payment success claims the units, deducting them permanently from the merchant's inventory ledger. Failure or timeout releases them. Both kinds of mistake cost merchants money:
- selling the last hoodie twice forces a cancellation;
- hiding a hoodie still in the warehouse loses a sale.
At Shopify's scale, even rare errors happen often.
The old design and why it had to go. Temporary reservations lived in Redis, one counter per item. Redis executes commands one at a time, so concurrent reservations of the last unit were safely serialised. As a concurrency mechanism, it worked. But the merchant's permanent ledger lived in MySQL, so a successful payment needed two writes in two databases: deduct in MySQL, then clear the hold in Redis. No transaction can span both.
Changing the order only changes which failure you get; the gap between the two writes remains. The standard remedies didn't close it:
- Two-phase commit needs both stores to take part in one coordination protocol, and Redis can't (Distributed Transactions: 2PC, Sagas and Outbox).
- An outbox or a reconciliation job eventually repairs a mismatch, but inventory is wrong until it does. In a flash sale, even briefly wrong can mean selling the same unit twice.
The obvious MySQL design had already failed. A single row per item with a counter:
-- The failed first attempt, simplified
UPDATE reservations SET available = available - 1
WHERE inventory_item_id = 42 AND available >= 1;InnoDB grants that row's lock to one transaction at a time. In a flash sale, thousands of checkouts for one item queue on one row lock and run one after another. That's the classic hot row (Pattern: Dealing with Contention).
The new design: one row per reservable unit, claimed with SKIP LOCKED.
- A pool of unit rows. Each row in
reservation_unitsis one unit that can currently be reserved. To reserve three, a transaction locks three available rows, deletes them from the pool, and writes one hold (with quantity and deadline) intoreserved_quantities, all in the same transaction as any ledger changes. SKIP LOCKED(added in MySQL 8). A normalFOR UPDATEwaits when it reaches a row another transaction has locked.SKIP LOCKEDpasses over locked rows and takes the next free one. Two buyers of the same item lock different rows and commit in parallel. It's the same move as one row per seat in ticket booking (Design a Ticket Booking System (Ticketmaster)), applied to fungible units.- A bounded pool. One row per unit of a merchant's entire stock would mean hundreds of thousands of mostly idle rows per item, across millions of items, with scans slowing as the table grew. So the pool is capped at 1,000 rows per item, and a replenishment process tops it up. If a rush drains the pool faster than the background process refills it, the reservation request refills inline. A lock ensures only one transaction performs the refill, while others for that item wait, so capacity isn't added twice. That request is slower, but no buyer is turned away while the ledger still shows stock. (The post doesn't say how much latency this adds, or how orders larger than 1,000 units are handled.)
Making InnoDB's locks behave. The basic design removed the hot row, but production traffic exposed three locking problems:
- Double locking through a secondary index. The first prototype had an auto-increment primary key, and the reservation query searched a secondary index. InnoDB stores rows in primary-key order (a clustered index), so a locking read through a secondary index locks both the index entry and the underlying row. Making the query columns the primary-key prefix,
PRIMARY KEY (shop_id, inventory_item_id, inventory_group_id, id), let the query scan and lock table rows directly. That's one lock per unit instead of two, halving lock traffic on the hottest path (Database Indexing). - Gap locks on an empty pool. Under REPEATABLE READ, MySQL's default isolation level, a locking scan also locks the gaps between index records, to stop concurrent inserts into the scanned range. With an empty pool there are no rows to lock, so the scan locks the gap at the end of the index. That's exactly where replenishment inserts, so reservations blocked or deadlocked with refills. Switching these transactions to READ COMMITTED, which doesn't take those gap locks for such scans, removed the conflict. It was the first non-default isolation level anywhere in Shopify's codebase (ACID Transactions and Isolation Levels).
- Lock-order deadlocks. Different code paths touched the two tables in different orders, so two transactions could each hold what the other needed. The fix was to make every path acquire locks in the same order: remove unit rows first, then insert the hold (Concurrency Control and Database Locking).
What the post doesn't cover: holds that are never paid. A reservation has three possible endings:
- Payment succeeds, and the hold is claimed.
- Payment fails or the buyer exits. That's an explicit signal, so the hold is released.
- The deadline passes with no signal at all. A closed laptop sends nothing. Something still running must give the units back, or a flash sale shows "sold out" while the warehouse has stock.
The deadline has to live in the data, and some always-running process has to act on it. The handbook's reference analysis reasons through both eras:
- Old system (Redis counter). A TTL on the counter key would delete the whole counter, not one buyer's hold.
- Per-reservation keys with TTLs work well for locks on specific things like a seat, where the key's existence is the state. But fungible inventory needs a count across all live holds, and Redis can't count matching keys without scanning the keyspace. That's why the counter existed in the first place.
- Expiry has no side effects. Redis expiry deletes the key and can't run the
INCRthat returns the unit. Keyspace notifications are fire-and-forget pub/sub, so if the worker is down, the event is lost. - A sorted set scored by deadline is more robust. Workers pop due holds, and an atomic script removes each hold and restores the counter in one step.
- Expired holds can also be reclaimed inline on each reserve. The same atomic script first reclaims a few past-due holds, then takes the new reservation. Cap how many it reclaims, because Redis blocks everything while a script runs. Background sweepers are still needed for items that stop getting traffic.
- New system (MySQL). Nothing needs to "fire" at the deadline. Replenishment already computes the pool's target as roughly the ledger count minus active holds. Define active as
expires_at > NOW(), and a hold silently stops counting once its deadline passes. The next refill, background or inline, restores the capacity. A cleanup job still deletes dead holds, but that's garbage collection, not correctness. If it runs late, nothing is oversold or lost. Holds aren't long-held locks either: a hold is a row with a deadline, and locks exist only during millisecond-long transactions.
The lessons:
- Atomicity decides placement. If the hold and the ledger must commit together, they must live in the same database. Redis was correct at counting the whole time; it had to go because it couldn't join the ledger's transaction. If they don't need to commit together, a Redis counter is still the simpler tool.
- Spread contention across rows. A pool of claimable rows plus
SKIP LOCKEDturns one hot lock into many parallel ones. - Re-check old conclusions. "MySQL can't do this" was true before MySQL 8 shipped
SKIP LOCKED, and false when Shopify revisited it. - Every design moves cost somewhere. The replenishment process is a new component to run, monitor and page on, and its natural failure mode is an empty pool mid-sale. The trade came out ahead because the new part sits inside the transaction boundary that mattered.
- It works under load. The rebuilt system handled Black Friday 2025, when merchant sales peaked at a record $5.1 million per minute.
Lesson 2: Discord, trillions of messages from Cassandra to ScyllaDB#
The workload. Discord has stored messages in Cassandra since 2017. By early 2022 the cluster held trillions of messages on 177 nodes. All messages lived in one table:
CREATE TABLE messages (
channel_id bigint, bucket int, message_id bigint,
author_id bigint, content text,
PRIMARY KEY ((channel_id, bucket), message_id)
) WITH CLUSTERING ORDER BY (message_id DESC);How the schema works:
- The partition key is
(channel_id, bucket). A channel is one chat room inside a server, and the bucket is a time window. Together they put one channel's messages from one period into one partition, replicated on three nodes. message_idis the clustering key, newest first. Reading recent messages is a single sequential slice.- The time bucket bounds partition size. Without it, a busy channel's whole history would pile into one ever-growing partition (Apache Cassandra in Practice).
The schema spread writes well, and Cassandra suited the write-heavy workload. Reads were the problem.
Problem 1: hot partitions caused by popular data. Live reads for a channel target its newest bucket, and channel popularity varies enormously. A busy public channel concentrates thousands of reads on one partition and its three replicas. More buckets wouldn't fix it: the partition was hot because the data was popular, not because there were too few buckets. Sharding further would complicate the main query, which reads a channel in order.
Why one hot channel slowed unrelated ones. Cassandra's write path is cheap: append to the commit log, write to an in-memory memtable, flush to immutable SSTables. Reads, though, may need to check the memtable and several SSTables and merge the results, with compaction periodically merging files to keep that bounded (Storage Engines: B-Trees vs LSM Trees). Thousands of readers on one partition make its three replicas repeat that relatively expensive read work. Those same nodes also hold thousands of quieter channels' partitions. Because Discord read and wrote at quorum (two of three replicas must answer), an overloaded replica slowed unrelated queries that needed it (Quorums and Leaderless Replication).
Problem 2: compaction debt and GC pauses.
- Compaction fell behind. More uncompacted SSTables made reads slower, slower reads used more resources, and that left less capacity for compaction: a vicious cycle. Compacting more aggressively doesn't help, because compaction competes with live traffic for the same CPU and disk. Engineers resorted to a manual "gossip dance": take a node out of service, let it compact, bring it back, let it replay missed writes, then repeat on the next node.
- JVM garbage-collection pauses caused latency spikes. The worst forced reboots, with nodes nursed back into the cluster.
The cluster was becoming fragile and labour-intensive even before the hot-partition traffic.
Solution part 1: ScyllaDB, a faster storage layer. ScyllaDB speaks the same query language and data model as Cassandra, so the schema stayed. It's implemented in C++, so there are no JVM GC pauses, and it uses a shard-per-core architecture where each CPU core owns its own slice of data and requests. That gave more performance per machine and faster repairs, cutting operational toil. But a faster database can't stop thousands of people asking for the same partition. That needed less work to reach the database.
Solution part 2: data services with request coalescing.
- A data-service tier. A fleet of Rust data services sits between the API and the database. The API keeps the business logic; the data services own database access.
- Routing related requests together. Consistent hashing on
channel_idsends all requests for a channel to the same instance, and keeps that mapping mostly stable as instances are added or removed (Consistent Hashing). - Coalescing in-flight reads. The first request for a key starts the database query. Identical requests arriving while it runs subscribe to the same task, and one result is fanned out to all of them. The core is a map from query key to the in-flight task, with an atomic "get or start".
- Why the data service is the right place. The database's caches can reuse low-level work, but the database doesn't know that two RPCs are the same logical request. The data service sees the whole request, including its key, so it can merge them before either becomes a database read.
Why coalescing rather than caching? A cache would also absorb requests that arrive after the first query finishes, so it has a higher hit rate. But it brings expiry and invalidation. Coalescing never serves an old result; it only shares work the database is already doing for overlapping requests. Discord gave up some hit rate for much simpler consistency (Cache Failure Modes: Stampedes, Hot Keys and Penetration).
Incremental delivery. The data services shipped while Cassandra was still primary. They didn't remove hot partitions, but they sharply cut the duplicate reads hitting them, making latency incidents rarer and keeping Cassandra manageable while ScyllaDB was tested and tuned.
Results. The cluster went from 177 nodes to 72, and p99 read latency went from a range of 40–125 ms to a steady 15 ms.
The lessons:
- Hot partitions are a traffic problem. Faster storage makes each read cheaper but doesn't reduce how many arrive. Reducing duplicate work is a separate fix, and both were needed.
- Route related work to one place. Consistent hashing by the hot key gives duplicate requests a place to meet. This is reusable anywhere: per-user, per-document or per-item routing enables coalescing, batching and ordering.
- Pick the narrowest tool that works. Coalescing removes duplicate concurrent reads with no staleness, while caching would remove more reads but add invalidation. Match the tool to the consistency you need.
- Operability is a requirement. GC pauses and compaction debt were reasons to migrate on their own, independent of throughput.
- A compatible replacement lowers migration risk. Keeping the data model and query language meant the schema and access patterns carried over.
Lesson 3: Slack, Kafka in front of the Redis job queue#
The workload. Slack's asynchronous job queue runs nearly everything too slow for a web request: posting messages, push notifications, URL unfurls, calendar reminders, billing calculations. On its busiest days it handled over 1.4 billion jobs, peaking at 33,000 per second. Jobs take from a few milliseconds to several minutes (Pattern: Managing Long-Running Tasks).
The original design: everything in Redis RAM. The queue ran on a fleet of Redis clusters with pools of polling workers:
- Enqueue. The web app built a job identifier from the job type and arguments, then hashed it with the logical queue name to choose a Redis host.
- Dedup. That host ran limited deduplication, dropping a job if an identical one was already waiting.
- Dispatch. Workers moved jobs from the pending queue to an in-flight list before running them, so a dead worker's job stayed recoverable.
- Retry. Failures retried, and eventually landed in a permanently-failed list for manual repair.
Slack doesn't say exactly which Redis structures it used. In a typical Redis task queue:
- pending jobs sit in a list per queue;
- dedup uses a set or hash keyed by job ID;
RPOPLPUSHmoves the oldest job into an in-flight list at constant cost;- removing a specific job by value (
LREM) scans the list.
That scan gives dequeue a cost linear in queue length, which matches the behaviour Slack described.
The outage. Contention in the database layer slowed job execution. Jobs piled up in Redis until it hit its configured maximum memory, and then:
- Enqueue failed, so every feature depending on the queue broke.
- Dequeue also failed. Moving a job to the processing list needs a little free memory, and a full Redis had none. Even after the database recovered, the queue stayed stuck until extensive manual intervention.
The structural flaw was that the burst buffer and the dispatch workspace shared one bounded pool of RAM. Overload ended in lockup rather than lag.
Other problems the post-mortem found:
- Connection fan-out. Every queue client connected to every Redis instance, forming a complete bipartite graph.
- Workers couldn't scale independently. Each added worker adds polling load on Redis, so adding execution capacity could push an overloaded Redis further under.
- A second feedback loop. Linear-cost dequeue meant a longer queue slowed every dequeue, exactly when draining mattered most.
- Vague semantics. The queue's exact behaviour was never pinned down, so engineers were wary of building on it or changing dedup behaviour.
Requirements from the post-mortem:
- a durable backlog that can't run out of memory, whether jobs flood in or drain slowly;
- real rate limits and priorities in scheduling;
- execution capacity that scales without adding Redis polling load.
Rejected options, each for a reason:
- Rebuild the queue on Kafka alone. Kafka is a durable, partitioned, append-only log, bounded by retention on disk rather than by RAM. But consumers track an offset per partition, not per-job state, so acknowledgements, retries, dedup and in-flight tracking would all have to be built on top. Plenty of teams do that, but Slack already had those semantics in Redis with years of application code depending on them. It would have turned an availability fix into a rewrite.
- RabbitMQ, SQS or beanstalkd. All persist to disk, but each has its own delivery semantics, so it would be the same rewrite against a different API.
- Turn on Redis persistence. A Redis dataset must still fit in RAM. The outage was about capacity, not durability.
- Keep Redis alone. That was the design that had just failed.
The chosen design: the "minimum viable change".
- Kafka as the durable buffer. The web app enqueues into Kafka. During a buildup, the backlog grows on disk, bounded by retention instead of RAM.
- Kafkagate (the enqueue path). A stateless Go service exposing a simple HTTP POST with topic, partition and job content. It holds persistent broker connections, follows partition leadership changes, and writes synchronously, so callers get an ack or an error.
- It waits only for the partition leader's acknowledgement, not for replication. That's the lowest latency, with a small risk of losing a job if a broker dies before replicating, which Slack judged acceptable for most jobs (Delivery Guarantees: At-Most, At-Least and Exactly-Once).
- Hosts prefer a Kafkagate in their own availability zone and fail over to others. This also removed the enqueue half of the connection fan-out: the web app talks to a nearby gateway instead of holding connections to fifty Redis clusters.
- JQRelay (the drain). One instance relays one Kafka topic into its matching Redis cluster.
- Ownership is coordinated with Consul locks. On startup an instance tries to acquire a topic's lock. If it loses the lock, it releases everything and restarts, so another instance can take over. Instances run in an auto-scaling group (Leader Election and Coordination Services).
- The core loop: write the job to Redis, retrying indefinitely while Redis is down, and commit the Kafka offset only after the Redis write succeeds. A crash replays from the last committed offset, so delivery is at-least-once. The limited Redis-side dedup can absorb a replayed job that's still waiting, but jobs should be safe to run twice.
- Failing jobs are re-enqueued to Kafka, so one bad job doesn't block the partition.
- Rate limits live in Consul and are picked up live through its watch API. During a buildup, the web app keeps enqueueing at full speed while operators turn the relay down to match what workers can execute. That's backpressure, under explicit control (Resilience Patterns: Timeouts, Retries and Circuit Breakers).
- The Kafka configuration. 16 brokers, 32 partitions per topic, replication factor 3, two days of retention, and rack-aware replication mapped to availability zones. Unclean leader election was enabled, so Kafka can promote a stale replica to restore availability at the risk of losing acknowledged writes. That's consistent with choosing availability over the last few jobs (Apache Kafka in Practice).
Proving it safely:
- Load tests at expected production rates.
- Failure drills: broker loss, a forced unclean leader election, a full cluster restart. All met the availability goals.
- Double writes plus a shadow relay. Every job went to both paths, while JQRelay read everything from Kafka and dropped it. Real traffic exercised every new component with zero user impact.
- Counting jobs at every hop (web app → Kafkagate → Kafka → Redis), plus heartbeat canaries: one per partition per minute across all 1,600 partitions (50 topics × 32), with alerts on end-to-end flow and timing.
- Gradual rollout. A few weeks of internal use, then customers one job type at a time.
The surprise: serialisation differences between runtimes. JQRelay (Go) decoded and re-encoded each job's JSON. Go escapes <, > and & by default, while PHP escapes /. Identical data produced different bytes depending on the runtime, which caused real trouble. Lesson: adding a second language to a pipeline means checking byte-level compatibility of serialisation, not just logical equivalence.
The lessons:
- Separate the backlog from the dispatch state. Keep the backlog somewhere that can't run out of memory, and let the fast layer hold only what's in flight.
- Overload should degrade into lag, not lockup. If a component can't serve requests once it's full, or can't recover without free resources it doesn't have, it will eventually fail hard.
- The minimum viable change beats the rewrite when existing code depends on exact semantics. Add a layer, keep the interfaces, and migrate incrementally.
- Make throttles controllable at runtime. Operator-adjustable rate limits between layers turned an outage scenario into a managed backlog.
- Modern tools absorb this separation. Kafka consumer groups back many job systems directly. SQS bundles durable buffering with acknowledgements, retries and dead-letter queues. Durable-execution engines like Temporal persist each step of a job (Temporal and Workflow Engines). Redis Streams, added a year after the post, offers a log with consumer groups and acks, though in a typical deployment its data still has to fit in RAM.
Lesson 4: Figma, multiplayer editing on simplified CRDTs#
The context. Figma launched multiplayer editing in September 2016, when no other design tool had live collaboration, and many designers disliked the idea, fearing "design by committee". About three years later, co-founder Evan Wallace published how the syncing works.
The requirements:
- Convergence. When edits stop, every editor's copy must be identical.
- Instant feel. Each client applies its own edits immediately and syncs afterwards, so copies briefly disagree.
- Offline editing. A designer on a plane keeps working, which stretches the "disagreement window" from seconds to hours. The system must absorb whole batches of stale edits.
- A tree, not text. Pages contain frames, frames contain shapes, shapes contain text. Concurrent restructuring can do things no single-user editor faces, such as two people moving the same object into different frames at once. The system must never duplicate an object or lose part of the document.
Two candidate approaches, both cut down:
- Operational transformation (OT), the algorithm family behind Google Docs, represents edits as operations and transforms each against concurrent ones. An insert at position 5 becomes an insert at position 8 if someone added three characters earlier. It's notoriously hard to get right. Wallace quoted researchers Li and Li on how complicated and error-prone OT's correctness proofs are, even for just insert and delete on plain text. A design document has far more operation types. Ruled out.
- CRDTs (conflict-free replicated data types) let each replica accept edits independently, with merges that give the same result in any order.
- The simplest is a grow-only set: merging is set union, so order and separation time don't matter.
- Mutable values need a last-writer-wins (LWW) register: every write carries a timestamp, and a merge keeps the newer one. If you set the venue to "park" on Monday and I set it to "beach" on Tuesday, both copies converge on "beach".
- The costs are timestamp metadata, and tombstones for deletes so late replicas don't resurrect items. Most of that machinery exists because there's no one in charge of ordering.
The key insight: Figma has a central server. Every edit already flows through it, so the server's arrival order can decide "last". That removes the timestamps and most of the bookkeeping. Figma went through the CRDT literature cutting everything a central server makes unnecessary. What was left: every property of every object is an LWW register, minus the timestamp, with "last" meaning last to reach the server.
The document model. A tree much like the HTML DOM: a root document, with pages under it, then frames, shapes and text. Every object has an ID and a set of properties, so the whole document is:
type Document = Map<ObjectID, Map<Property, Value>>;How conflicts resolve:
- Different properties both survive. You recolour a rectangle while a teammate resizes it, and both edits land.
- Same property, same object: the last value to reach the server wins. The property value is the unit of atomicity. If text "B" becomes "AB" on one client and "BC" on another, the result is "AB" or "BC", never "ABC". That would be unacceptable in a text editor, but it's right for visual properties: there's no meaningful merge of red and blue, so one winning outright is what designers expect.
- Client-side flicker is suppressed. Edits apply locally before the server acknowledges them, so a client can receive an older conflicting value relayed from someone else. It would briefly overwrite the local value, then flip back on ack. Fix: the client ignores incoming changes that conflict with its own unacknowledged writes.
Creating and deleting objects:
- Creation adds a map entry. Clients mint object IDs with a unique client ID embedded, so IDs never collide and creation works offline (Unique ID Generation).
- Deletion removes the entry entirely, with no tombstone. Documents live for years, and remembering every deletion would grow them forever.
- A property write can never create an object. That rule makes deletion safe: a stale edit aimed at a deleted ID simply hits nothing and is dropped.
- Undo still works. The deleting client kept the properties in its local undo history and can restore them.
Reparenting: the parent is just another property. Wallace called this the most complicated part.
- Move as delete-plus-recreate breaks multiplayer. The recreated object has a new ID, so a teammate's concurrent recolour targets a vanished ID and is lost.
- Instead, the parent link is a property on the child. A move is an ordinary property write: identity is kept, and concurrent edits to other properties land untouched. Duplication is impossible to express, because one property holds one value, so no object can have two parents.
- Cycles still need a check. Client 1 sets A's parent to B while client 2 sets B's parent to A. Each write is valid alone, but together they create a cycle, and no per-property rule can catch that. The server rejects any parent update that would create a cycle. A client that applied a move optimistically may briefly see a cycle, so it hides the cycled objects until the server's answer arrives.
- Sibling order uses fractional positions. Integer indexes (1, 2, 3) would force renumbering on every insert: many writes, many collisions. Each child's position is instead a fraction strictly between 0 and 1, and siblings render sorted by it. Inserting between 0.25 and 0.5 gives 0.375, and nothing else changes. Because a position only has meaning among one parent's children, parent and position are one atomic property:
set("parent", { parentID, position: 0.375 }).
The infrastructure: one process per document.
- One place sees every write. "Last to reach the server" is only meaningful if a single place sees every write, so every editor of a file connects to the same process, and no cross-server coordination is needed. This is one of the two standard ways to fan out realtime updates; the other is pub/sub with clients on any server (Pattern: Pushing Realtime Updates).
- Joining is simple. Opening a file downloads a complete copy, then a WebSocket carries edits both ways.
- Reconnecting needs no session resumption. The client downloads the document again, replays its unacknowledged edits on top, and opens a new socket. Offline support comes for free: four hours offline is handled the same way as a four-second disconnect.
- The infrastructure has to handle crashes. Something must detect a dead document process and hand the file to a replacement without two processes ever accepting writes for the same file, which is a single-owner or leadership problem (Distributed Locks). For clients, it's the same reconnect path again.
The lessons:
- Simplify to fit the domain. Design edits mostly set one obvious property, and a lost race is visible on screen, so whoever cares can redo it. Per-property LWW covers nearly everything. Simultaneous text editing is the stated exception.
- Trade algorithmic difficulty for infrastructure. A single process per document turns "agree on the order of events", the hardest problem in the literature, into arrival order. The infrastructure problem that remains is smaller: agree on which process owns each document, decided per session rather than per edit.
- Choose representations that make bad states unexpressible. A single parent property rules out duplicate parents. Fractional positions avoid renumbering storms.
- The design became the industry default. Sync engines like Zero, and Linear's own homegrown equivalent, use a server ordering optimistic mutations with per-property LWW. One process per document is now a cloud primitive: Cloudflare Durable Objects. Concurrent text still needs a real CRDT, where Yjs has become the default (Conflict Resolution, OT and CRDTs, Design a Collaborative Editor (Google Docs)).
Lesson 5: Spotify, point lookups on a Parquet data lake#
The context. Spotify keeps exabytes of data in Google Cloud Storage (GCS) as a data lake of Parquet files. A data lake is a pile of open-format files in cheap object storage that many engines can read. Trino and BigQuery read these files, and so do ML training and feature pipelines. The appeal is cost and a single copy of the truth: no warehouse loads, no ETL copies drifting out of date (Data Pipelines, Warehouses and Lakes, Object Storage and Blob Storage).
Why Parquet suits scans. A Parquet file is columnar:
- Each column is stored contiguously.
- Columns are cut into row groups (typically tens to hundreds of MB), and each row group's column data into pages of up to about a few MB.
- A footer at the end describes where everything lives and holds min/max statistics.
So a query like "average listening time by country" reads two columns and skips everything else, which is exactly what analytics wants.
The problem: point lookups. "What did user X listen to last month?" is the opposite shape. It wants a handful of rows scattered across thousands of files.
- Any engine still has to plan a distributed query, then open files and pull whole pages to find a few rows.
- Spotify's write-up is clear that object storage isn't the culprit. A GCS request takes about 30–100 ms, and newer low-latency tiers like S3 Express One Zone and GCS Rapid Storage are in the single-digit milliseconds. The slowness comes from how many dependent reads a lookup needs and how much each one fetches.
- The usual fix is to copy the data into a serving database (Bigtable, DynamoDB) keyed by user. That works, but every gigabyte is paid for twice and kept in sync with a pipeline. Teams end up rationing which data is allowed to be served online.
Stage 1: prune files. Assume about 1,000 files per day, so a 90-day question starts with 90,000 candidate files.
- Bucketing. Write each user's rows into bucket
hash(user_id) % 1000, encoded in the path, e.g.date=2026-07-14/bucket=0427/part-00031.parquet. A lookup now opens only its bucket per day: 90,000 files become 90. - Per-file Bloom filters. Store a Bloom filter on
user_idfor each file and cache the filters in a metadata store. A Bloom filter answers "definitely not here" or "maybe here" (Probabilistic Data Structures for Big Data). The user appears on only some of those days, so 90 files become about 12.
Stage 2 is where it still hurts. Inside each surviving file, a lookup runs a chain of dependent reads:
- Read the footer.
- Find the row groups whose min/max could contain the user.
- Read the key column chunk.
- Consult the column and page indexes.
- Fetch the pages.
Each step needs the previous step's answer, so they can't be parallelised. At 30–100 ms per round trip, five sequential trips cost hundreds of milliseconds per file, even when the files are fetched in parallel.
The fix: Random Access Parquet (RAP). RAP is an external index that lives beside the data files and never modifies them.
- How it's built. A builder job reads each file's footer and page locations and scans the key columns.
- It's append-only. Each run writes a new index fragment covering the newly arrived files; old fragments are never rewritten. This matches how lakes grow: new partitions, rarely edits.
- It's a multimap. One key maps to many entries, and each entry records:
- the key, which may be compound (e.g.
user_id + date); - the file, as a dictionary-encoded ordinal (a small integer, not a long path);
- the row numbers in that file;
- optionally a value count, for pagination.
- the key, which may be compound (e.g.
- It's small. Roughly gigabytes of index per terabyte of data, and terabytes per petabyte. Large indexes are themselves bucketed by key hash.
How RAP compares with Parquet's built-in structures:
- Min/max column and page indexes are exact but can only rule out ranges. A popular key range still overlaps many pages.
- Bloom filters are probabilistic: "maybe" costs a read that may find nothing.
- RAP is definitive. It resolves a key directly to rows in effectively constant time.
- Combined with cached file metadata, the rows map to byte ranges fetched with parallel ranged GETs. Five dependent reads become three independent ones, issued at once.
The remaining limit: the page is the atomic unit. Parquet compresses and encodes a page as a whole, so reading one ~100-byte row still means fetching and decoding its entire page, up to about 4 MB. An index can point at a page but can't make the page smaller. Respect the atomic unit of your storage format. You don't fight it, you shape the data so the unit is small where it matters.
Write-side fixes that shape the data:
- Sort by key, and start a new page when the key changes. A user's rows then sit together in their own small page. Each extra page boundary costs only about 20 bytes of header, and the files remain standard Parquet, readable by every existing engine.
- Copy small values into the index itself. This is a covering index: the answer lives in the index, so no data read is needed. It can include precomputed aggregates such as event count and total play time per user per day, which answer common questions with no storage read at all (Database Indexing).
- The result: a lookup becomes one ranged read of a few KB per file, or zero reads when the index covers the query.
Secondary indexes without migrations. A marketplace table might need lookups by buyer_id and by seller_id. Rows can only be sorted one way, but a second RAP index is just another access structure over the same files: no rewrite, no copy. In the article's words, a new index costs you an index, not a migration. Contrast DynamoDB's global secondary indexes, which are managed copies of the data with their own storage and write cost (Amazon DynamoDB in Practice). Lookups on a secondary key scatter more, because rows aren't clustered by that key. Merging adjacent byte ranges into fewer, larger reads softens that.
What the write-up doesn't give. There are no production latency numbers or adoption figures. The cost advantage over a serving copy is argued from first principles, not measured publicly. Treat RAP as a well-reasoned design rather than a benchmark result.
The lessons:
- Find out which reads are dependent. Latency is (number of sequential round trips) × (round-trip time). Collapsing a chain matters more than shaving each hop.
- Index, don't copy. An external, append-only index brings lookups to the data instead of moving the data into a lookup system.
- Shape writes for reads. Sorting and page boundaries are cheap at write time and decisive at read time.
- Organic system design. RAP bolts onto infrastructure Spotify already had, with no new storage engine and no format fork. That's usually how real systems evolve.
- Demand is shifting. AI agents and online features issue far more point questions against analytical data than dashboards ever did, so "lake as serving layer" is becoming a real requirement (Pattern: Scaling Reads).
Lesson 6: Meta ZGateway, five techniques for a database with a million clients#
The context. ZippyDB is Meta's shared key-value database, used by hundreds of internal teams from more than a million client hosts. At that scale, the database's problem is less the queries themselves than everything around them:
- Connections cost money even when idle. Each one holds memory for state and buffers. Opening one costs CPU for authentication and encryption setup. Meta describes typical clients holding tens of thousands of outgoing connections, and individual ZippyDB hosts accepting tens of thousands of incoming ones.
- Restart storms. If many applications restart together, the database must re-establish all their connections while still serving queries, and that extra work can overwhelm it.
- Per-request overhead. Every small request must be received, decoded and dispatched. If a thousand applications read the same profile, the database may do the same lookup a thousand times, and again a second later even if nothing changed.
- Noisy neighbours. One team's spike can fill shared queues and slow everyone else, even teams whose traffic didn't change.
The solution: a reverse proxy, ZGateway, between applications and ZippyDB. Applications talk to the gateway, and the gateway owns the database connections. Traffic from many applications now meets in one place the ZippyDB team controls. There the gateway can combine work the applications would otherwise do separately, and limit how much work gets through (API Gateway and Backend-for-Frontend).
1. Connection pooling, shared across clients. A pool keeps connections open and reuses them, so each query skips the open, authenticate and close cost.
- Per-application pools don't solve this. Each new instance brings another pool, and the database still holds connections from all of them.
- Gateway pools do. Each client connects to a small set of ZGateway hosts, and the gateways forward requests over shared pools to ZippyDB. A new client uses existing backend connections instead of opening its own to every database host. Connection count at the database is decoupled from the number of clients.
2. Batching: different keys travel together. Three application instances fetch profiles 73, 81 and 92 for the same use case and the same shard. The gateway sends one backend request carrying all three keys, then routes each result back to its caller.
- The database still does three lookups. What's shared is the fixed cost: serialisation, network transmission and request handling.
- It works for writes too. Independent updates travel together and are still applied as separate changes.
- It stretches rate-limit budgets. Fewer backend requests count against a use case's limit, so it can do more operations before being throttled.
- The cost is latency. The request for 73 could go immediately, and holding it lets 81 and 92 join. Longer waits make more efficient batches but delay the first caller.
- ZGateway bounds the trade-off. It flushes on a timer or a size/request-count limit, whichever comes first, and caps how many batches can be in flight to protect its memory when the database slows. Batch size and wait time must fit the workload's latency budget (Pattern: Scaling Writes).
3. Request coalescing: the same key shares one lookup. Caller A asks for user:73, and the gateway starts a lookup. Before it returns, B and C ask for the same key. They attach to the in-flight lookup, and all three get the result. This is the technique Discord used in Lesson 2.
- Batching vs coalescing. A batch of three different keys still costs three lookups. Three requests for the same key cost one. Coalescing shines when one record suddenly gets hot: thousands of simultaneous reads collapse into a few.
- The conditions. Requests must reach the same gateway while the lookup is still running, for the same record with compatible read requirements (a request demanding fresher data can't share a weaker read). Each gateway tracks only its own outstanding work.
- The cost is memory. The gateway must track running lookups and their waiting callers. If the database slows, waiters pile up. It needs limits on outstanding work and cleanup on completion or timeout.
- The gap. Coalescing stops helping when the lookup completes. A request one millisecond later finds nothing to join, which is why a cache comes next.
4. Read-through in-memory cache. The gateway checks its local memory first. On a miss it fetches from ZippyDB and keeps a copy (Caching Strategies: Cache-Aside, Read-Through, Write-Through, Write-Behind).
- Thundering herd defence. When a popular entry expires or is invalidated, many callers miss at once. A per-key fill lock lets one request fetch while the others wait for its result. That's coalescing again, with the result kept afterwards (Cache Failure Modes: Stampedes, Hot Keys and Penetration).
- Freshness. Cached values can go stale. A change-data-capture (CDC) stream from the database invalidates or refreshes entries, under an agreed limit on how far cached reads may lag writes (Change Data Capture and the Outbox Pattern).
5. Admission control: protect capacity for work that can finish. Requests go into bounded queues by use case and priority, and the gateway takes turns serving them.
- Overflow is isolated. When one team's queue fills, its excess is rejected while other teams keep progressing. That's isolation by construction, a bulkhead (Resilience Patterns: Timeouts, Retries and Circuit Breakers).
- Overload is avoided. CPU and memory pressure also limit how much the gateway admits.
- The trade-off. Some callers get an error instead of waiting. That's deliberate: a queue that grows without bound just converts overload into timeouts for everyone. Callers must back off before retrying, or they recreate the overload (Rate Limiting and Throttling).
The lessons:
- Diagnose before you scale. Find where the database actually spends its resources. Too many connections → pooling at a shared tier. Repeated identical reads → coalescing and caching. Many small distinct requests → batching. More traffic than capacity → admission control. Each technique fixes one cause and does nothing for the others.
- A shared tier creates leverage. Work can only be combined where it meets. A gateway is the meeting point, at the cost of an extra hop, extra latency and another service to run. At Meta's scale, all five techniques earn their place.
- These are the standard read and write scaling toolkits, assembled in one place (Pattern: Scaling Reads).
Recurring themes across the six lessons#
Read side by side, the six write-ups repeat a few ideas. These are the parts worth carrying into any design.
| Theme | Where it shows up | The principle | Handbook pattern |
|---|---|---|---|
| One transaction boundary for things that must agree | Shopify moves reservations into the ledger database | Two systems can't commit atomically without a protocol, so don't split atomic state across them | Pattern: Dealing with Contention |
| Remove duplicate work before buying capacity | Discord and Meta coalescing, Meta batching and fill locks | A faster database and less database work are separate levers, and the second is often cheaper | Pattern: Scaling Reads |
| Separate the durable backlog from the fast working set | Slack puts Kafka in front of Redis | Bursts belong on disk; RAM holds only what's in flight | Pattern: Managing Long-Running Tasks |
| Use a single owner to make ordering trivial | Figma has one process per document | A central sequencer turns a hard distributed-ordering problem into arrival order | Conflict Resolution, OT and CRDTs |
| Index, don't copy | Spotify's RAP sits beside the Parquet files | An access structure is cheaper than a second dataset you have to keep in sync | Database Indexing |
| Collapse dependent round trips | Spotify turns 5 sequential reads into 3 parallel ones | Latency scales with sequential steps, not total bytes | Latency, Throughput and Performance vs Scalability |
| Bound every queue, and reject early | Meta's admission control, Slack's memory exhaustion | An unbounded buffer turns overload into a total outage | Resilience Patterns: Timeouts, Retries and Circuit Breakers |
| Migrate incrementally, behind a seam | Slack's shadow mode and heartbeat canaries, RAP bolted onto existing files | Big-bang rewrites are where outages come from; keep the old path as the fallback | Online Data Migrations and Schema Evolution |
| Respect the storage atomic unit | Spotify's 4 MB pages, Figma's property-level atomicity, Shopify's row locks | Whatever the smallest unit is (page, property, row), design so it matches the access | Storage Engines: B-Trees vs LSM Trees |
The flowchart below turns the themes into a quick diagnostic: start from the symptom, and it points to the lesson that addressed it.
When to Use It#
Use these lessons whenever a design discussion is about to rely on a pattern you've only read about. Specific triggers:
- An inventory, booking or allocation system that holds stock in a cache but records sales in a database. Shopify's dual-write failure is the warning, and the bounded unit pool is a drop-in alternative (Design a Ticket Booking System (Ticketmaster), Design a Flash Sale and E-commerce Checkout).
- A partitioned store where a few partitions get most of the traffic: celebrity channels, viral posts, popular products. Discord shows coalescing in front of the database, and why it's different from adding a cache.
- An async job system with bursty producers and a broker that holds everything in RAM. Slack's design tells you where to put the backlog and how to throttle the relay (Design a Distributed Job Scheduler).
- A collaborative editor for structured documents (diagrams, whiteboards, design files, spreadsheets with cell-level edits). Figma shows the simplest design that converges.
- A request for online point lookups over data that already lives in a lake. Spotify's progression (bucket, Bloom filter, external index, write shaping) is the menu to work through before proposing a copy into a key-value store.
- A shared database or service used by many teams, where connections, duplicate reads or one noisy tenant cause trouble. Meta's gateway is the template (Design a Distributed Cache).
- System design interviews. "How would you handle a hot key?" or "what if the queue backs up?" are best answered with a mechanism plus a real precedent. "Discord did exactly this and went from 177 to 72 nodes" is stronger than a hypothetical.
When NOT to Use It#
Pick something else instead when:
- The scale doesn't justify the machinery. Discord's coalescing layer and Meta's gateway are extra services with extra latency. A system with one database and a few application servers should use per-client connection pools, a simple cache and indexes first (Scaling from Zero to Millions of Users).
- The conflict semantics differ. Figma's per-property last-writer-wins would lose characters in a text editor. Concurrent prose needs OT or a sequence CRDT, as Figma itself notes for text.
- The data isn't in a lake. RAP's value comes from avoiding a copy. If the data is born in an operational database, index it there.
- Low latency is truly needed. RAP still pays object-storage round trips: tens of milliseconds on standard GCS, single digits on the express tiers. Sub-millisecond, high-QPS serving still belongs in Redis, DynamoDB or Bigtable (Redis in Practice).
- You'd be copying a conclusion without its constraints. Slack kept Redis because years of application code depended on its job semantics. A greenfield system might go straight to Kafka or SQS. Shopify moved into MySQL because the ledger was already there; a system with no ledger nearby might instead use a single Redis Lua script (Choosing the Right Pattern).
How to Implement It#
Turning a write-up into your own design is a repeatable process:
- Match the symptom, not the company. Use the diagnostic flowchart above. You're borrowing a mechanism for a cause, not a brand name.
- Write down the constraints that made the original choice right, and check each against your system. Do you have a central server (Figma)? Is the ledger already relational (Shopify)? Is there dependent code (Slack)?
- Size it with your own numbers. For coalescing: duplicate rate within one database round trip. For batching: requests per shard per millisecond. For a unit pool: maximum concurrent holds.
- Pick the smallest version first. In-process single-flight before a coalescing service. A
SKIP LOCKEDtable before a reservation microservice. Kafka in front of the existing queue, not a rewrite. - Add the bounds the write-ups insisted on: caps on in-flight work, timeouts on waiters, bounded queues, expiry for holds.
- Roll out behind a seam: failure drills, shadow traffic, counts at every hop, heartbeat canaries, then a gradual cut-over (Slack moved one job type at a time), with the old path kept as the fallback.
- Measure the claim. Each lesson has a measurable promise (fewer database reads, fewer nodes, no oversells, flat p99). Instrument it before and after (Observability: Logs, Metrics and Traces).
A minimal version of the coalescing step that Discord and Meta both use, plus Meta's bound on outstanding work:
// Request coalescing (single-flight) with a cap on in-flight keys and a waiter timeout.
type Loader<V> = (key: string) => Promise<V>;
class Coalescer<V> {
private inflight = new Map<string, Promise<V>>();
constructor(private load: Loader<V>, private maxInflight = 10_000, private timeoutMs = 200) {}
get(key: string): Promise<V> {
const existing = this.inflight.get(key);
if (existing) return this.withTimeout(existing); // join the running lookup
if (this.inflight.size >= this.maxInflight) {
return Promise.reject(new Error("overloaded")); // admission control: shed, caller backs off
}
const p = this.load(key).finally(() => this.inflight.delete(key)); // cleanup on success or failure
this.inflight.set(key, p);
return this.withTimeout(p);
}
private withTimeout(p: Promise<V>): Promise<V> {
return new Promise<V>((resolve, reject) => {
const t = setTimeout(() => reject(new Error("timeout")), this.timeoutMs);
p.then(v => { clearTimeout(t); resolve(v); }, e => { clearTimeout(t); reject(e); });
});
}
}
// Route by key (consistent hashing) so duplicates land on the same coalescer:
// const node = ring.lookup(channelId); node.coalescer.get(`messages:${channelId}:${before}`);Technologies that implement each lesson's mechanism:
| Technology | Fits when |
|---|---|
MySQL 8 / PostgreSQL FOR UPDATE SKIP LOCKED | Claiming one of many interchangeable rows (stock units, seats, job rows) inside the same transaction as the business write (PostgreSQL in Practice) |
| Redis Lua scripts / sorted sets | Atomic counters and expiring holds when the cache is the system of record, or a strict TTL index is needed |
| ScyllaDB / Cassandra | Huge append-mostly, time-ordered datasets partitioned by entity, such as messages and events (Apache Cassandra in Practice) |
Go singleflight, Nginx proxy_cache_lock, a custom gateway | Coalescing duplicate in-flight reads, in-process or at a proxy tier |
| Kafka | A durable, replayable buffer in front of a fragile or in-memory consumer (Apache Kafka in Practice) |
| Consul / etcd / ZooKeeper | Service discovery and a single owner (Slack's relay config; one owner per Figma document) (Leader Election and Coordination Services) |
| Yjs / Automerge | True CRDT merging where per-property LWW is too coarse, e.g. concurrent text |
| Cloudflare Durable Objects | One single-threaded, addressable process per document or room, managed for you |
| Parquet + Iceberg/Delta + Bloom filters | Lake tables that need pruning by key; add an external index when point lookups matter |
| ProxySQL / PgBouncer / a custom gateway | Sharing database connections across many clients, plus batching and admission control |
Trade-offs#
Each lesson chose one side of a classic trade-off. The table puts the chosen option next to the obvious alternative.
| Option | Pros | Cons | Pick when |
|---|---|---|---|
| Reservations in the ledger database (Shopify) | Atomic with the sale; crash-safe; no reconciliation job | Row locks on hot SKUs; database load per hold; expiry needs a sweep | The ledger is relational and correctness of stock matters more than peak hold rate |
| Reservations in Redis | Very fast counters and TTLs; offloads the database | Dual write with the ledger; drift after crashes; reconciliation needed | Redis is the system of record for stock, or holds are advisory |
| Coalescing layer (Discord, Meta) | Cuts duplicate reads on hot keys to one per round trip; no staleness | Extra hop; memory for waiters; works only within one in-flight window | Bursts of identical reads on a few keys |
| Cache in front | Absorbs repeat reads over time | Staleness; invalidation; thundering herd on expiry | Repeated reads of slow-changing data; pair with a fill lock |
| Durable log in front of the queue (Slack) | Bursts land on disk; replayable; protects the fast queue | Another system; extra latency; only partial dedup | Producers are bursty and the in-memory broker can't hold the backlog |
| Replace the queue wholesale | One system; cleaner long term | Rewrites every consumer; big-bang risk | Greenfield, or consumers are few |
| Single owner per document (Figma) | Arrival order is the order; simple LWW; offline replay is trivial | Ownership, placement and failover to run; one hot document is bounded by one process | Central servers are acceptable and documents fit one process |
| Peer-to-peer CRDTs | No central server; works across devices with no coordinator | Metadata and tombstone growth; more complex algorithms | Local-first apps, or truly decentralised editing |
| External lake index (Spotify RAP) | No data copy; new indexes without migrations; standard files | Object-storage latency remains; index builds; no published numbers | Data already lives in the lake, and tens-of-ms lookups are acceptable |
| Copy to a key-value store | Single-digit-ms lookups at high QPS | Paying for storage twice; sync pipelines; rationing | Hot online serving with tight latency SLOs |
| Shared gateway (Meta) | Shared pools, batching, coalescing, caching and admission control in one place | Extra hop and latency; a critical service to run | Many clients and teams share one database |
Common Pitfalls#
- Copying the solution without the constraint. "Figma uses last-writer-wins, so we will too" breaks a text editor. "Slack kept Redis" doesn't mean you should start with Redis.
- Calling coalescing "caching". Coalescing shares an in-flight result and never serves stale data. A cache keeps results after completion and introduces staleness. You usually need both, with the fill lock linking them.
- Coalescing without routing. If duplicate requests land on different nodes, nothing coalesces. Discord routes by
channel_idwith consistent hashing for exactly this reason. - Unbounded waiters, queues or batches. Every write-up adds a bound: Meta's cap on in-flight batches and waiter cleanup, Slack's memory lesson, Shopify's cap of 1,000 rows in the pool. An unbounded buffer just postpones the outage and makes it larger.
- Holding locks across network calls. Shopify's deadlocks came from lock ordering and gap locks. Holding a row lock while calling a payment provider makes it far worse. Keep claims short and transactional.
- Retrying rejected work immediately. Admission control only helps if callers back off with jitter. Otherwise the rejected load comes straight back.
- Treating unmeasured claims as benchmarks. Spotify's write-up has no production latency numbers. Discord's do exist. Know which kind of evidence you're quoting.
- Big-bang migrations. Slack shadowed traffic and watched heartbeat canaries on every partition. Discord's coalescing layer was cutting hot-partition incidents while Cassandra was still the primary store, before the move to ScyllaDB finished. Neither flipped a switch.
Real-World Examples#
How each lesson maps onto common interview problems in this handbook:
- Shopify's unit pool → ticket booking, flash sales, hotel rooms, limited-stock checkouts: anything that claims one of N interchangeable units. The pool,
SKIP LOCKEDand expiry handling are the core of the "no double-booking" deep dive. - Discord's coalescing and hot partitions → chat systems, live comments, news feeds with celebrity accounts, any "hot key" follow-up. The bucketed
(channel_id, bucket)partition key is the template for time-series partitioning. - Slack's durable buffer → job schedulers, notification systems, webhook delivery, any "what if the consumer is slow?" question.
- Figma's single owner and LWW → collaborative editors, whiteboards, multiplayer games, shared state per room or document.
- Spotify's lake index → analytics systems that also serve online features, ML feature lookups, "show me my history" pages over event data.
- Meta's gateway → distributed caches, key-value stores, rate limiters, and any shared platform with many tenants.
Go deeper with company blogs. Each lesson here has a fuller treatment in the engineering-blog pages, which read real production posts lesson by lesson. Start with How to Study an Engineering Blog for the method, then More Company Architectures for short stories (Giphy, Hashnode, Khan Academy, Levels.fyi, Shopify, Tumblr, WeChat, Zapier, Canva), and the company pages such as Zerodha, Swiggy and Razorpay.
Case studies that use this pattern#
- Design a Ticket Booking System (Ticketmaster): unit claims with
SKIP LOCKEDand expiring holds (Shopify). - Design a Flash Sale and E-commerce Checkout: inventory contention and bounded reservation pools (Shopify).
- Design a Chat System (WhatsApp): message storage partitioned by channel and bucket, hot channels (Discord).
- Design Live Comments (Facebook Live): hot keys and coalesced fan-out reads (Discord, Meta).
- Design a Distributed Job Scheduler: durable backlog in front of workers (Slack).
- Design a Notification System: bursty producers, buffering and throttled delivery (Slack).
- Design a Collaborative Editor (Google Docs): the OT/CRDT choice from the text side, versus Figma's structured documents.
- Design a Music Streaming Service (Spotify): listening history as point lookups over analytical data (Spotify RAP).
- Design a Distributed Cache: coalescing, fill locks and CDC invalidation (Meta).
- Design a Distributed Key-Value Store (Dynamo-style): connection fan-in and admission control at a shared tier (Meta).
In the Interview#
Common follow-ups:
- "Your inventory is in Redis and orders are in Postgres. What could go wrong?" A crash between the two writes. Decrement Redis and then fail the order, and stock is hidden. Write the order first and then fail the decrement, and you oversell. Either reconcile continuously or put the reservation in the order database's transaction, as Shopify did, using a pool of unit rows claimed with
FOR UPDATE SKIP LOCKED. - "How is coalescing different from caching?" Coalescing merges requests that overlap in time while one lookup is in flight; it never serves stale data and holds nothing afterwards. Caching keeps a result for later requests and so accepts staleness. Combine them with a per-key fill lock so a cache miss on a hot key also coalesces.
- "Coalescing won't work if requests go to different servers. How do you fix that?" Route by the key: consistent hashing on
channel_idsends all readers of one channel to the same data-service node. Add replicas for very hot keys only if one node can't keep up. - "Your queue lives in Redis. What happens during a 10× burst while the database is slow?" Workers slow down, the backlog grows in RAM, and Redis hits its memory limit, at which point it can't even dequeue. Put a durable log (Kafka) in front, relay into Redis at a controlled rate, and alert on log lag rather than memory.
- "Why didn't Figma use OT or a full CRDT?" OT is notoriously hard to prove correct even for plain text. Full CRDTs mostly pay for decentralisation. With every edit passing through one server process per document, arrival order resolves conflicts, so per-property last-writer-wins is enough. The cost moved to infrastructure: placing, discovering and failing over document processes.
- "Two users move objects into each other at the same time. What happens?" Each move is a valid parent-property write alone, but together they form a cycle. The server rejects the second write that would close the cycle. Clients that applied the move optimistically temporarily hide the cycled objects until the server's answer arrives.
- "Product wants per-user lookups over the event lake. Do you copy it to DynamoDB?" First prune with bucketing and Bloom filters, then consider an external index from key to file and row so reads become parallel byte ranges, and shape writes so each key gets its own page. Copy to a key-value store only if the latency SLO is below what object storage can do.
- "A thousand services connect directly to your database. What breaks first?" Connection memory, TLS and auth CPU, and restart storms, then duplicated reads and noisy neighbours. A gateway tier with shared pools, batching, coalescing, a read-through cache and bounded per-tenant queues addresses each in turn, at the cost of one extra hop.
Deep Dive: Contention internals behind Shopify and FigmaShow
Why SKIP LOCKED turns a hot row into a pool of cold rows.
- The single-counter design serialises everything. A design with one
availablecounter per SKU means every reservation runsUPDATE stock SET available = available - 1 WHERE sku = ? AND available > 0. All of them take an exclusive lock on the same row. Throughput for that SKU is then bounded by 1 / (lock hold time). If a transaction holds the lock for 5 ms (the write, plus the ledger insert, plus commit and fsync), the ceiling is about 200 reservations per second per SKU, however many servers you add. - A unit pool removes the shared row. Each interchangeable unit is a row. A reservation runs
SELECT id FROM units WHERE sku = ? LIMIT 1 FOR UPDATE SKIP LOCKED, which means "give me one unit nobody else is holding right now". Concurrent transactions skip each other's locked rows instead of queueing behind them, so with N unlocked rows up to N transactions proceed in parallel. Contention moves from "one row" to "how many units are free".
Why a bounded pool with inline refill.
- Rows still cost something. A million units of stock as a million rows is wasteful, and most would never be touched before a refill. Shopify capped the pool at 1,000 rows and refilled it inline as it drained.
- Sizing intuition. The pool needs at least as many rows as there are concurrent in-flight claims. By Little's law, concurrency = arrival rate × hold time. At 2,000 claims/s and 5 ms per claim transaction, that's about 10 concurrent claims, so 1,000 rows is two orders of magnitude of headroom. (This is an illustrative calculation; the write-up gives the cap, not the arithmetic.)
The InnoDB details that bit.
- The clustered primary key matters. InnoDB stores rows in primary-key order (a clustered index). With a PK prefixed by SKU, a pool's rows sit physically together, so the locking scan touches only that SKU's index range.
- Gap locks are what blocked refills. Under REPEATABLE READ, a locking read also locks the gap after the last matching record, to stop phantom inserts. On an empty or nearly empty pool, the scan's next-key lock covers exactly the range where the refill would insert. Claim and refill then wait on each other. READ COMMITTED drops gap locking for these reads, so the conflict disappears. The price is that phantom protection is gone, which this access pattern didn't need.
- Why consistent lock ordering is a complete fix for deadlocks. A deadlock needs a cycle in the "waits-for" graph. If every transaction acquires locks in one global order (units, then holds), then any transaction waiting for a lock holds only locks earlier in the order than the one it wants. A cycle would need some transaction to wait for a lock earlier than one it holds, which contradicts the ordering. So no cycle can form.
Expiry: the part the post skips. A hold must eventually release its unit. The two standard mechanisms:
- A sorted set keyed by expiry time (
ZADD holds <expires_at> <hold_id>, then periodicallyZRANGEBYSCORE holds 0 <now>), with reclaim done inline by whoever next touches the SKU. - A relational predicate on reads, such as
WHERE expires_at > NOW(), so expired holds stop counting immediately, plus a sweeper that deletes them and returns the units.
The predicate approach makes correctness independent of the sweeper's timing: the sweeper only affects space, never truth.
Figma's LWW is a real CRDT, with the server as the clock.
- A state-based CRDT is a set of states with a join (merge) that is commutative, associative and idempotent. Merges then converge whatever the order and duplication.
- A per-property LWW register qualifies. Its state is (value, version), and its join keeps the higher version. Figma's "version" is the server's sequence number: the order in which the single document process applied writes. Because one process stamps every write, versions are totally ordered with no clock skew. That removes the classic LWW hazard where a skewed wall clock makes an older write "win" (Time, Clocks and Ordering).
- The map of maps is a product of registers, and a product of CRDTs is a CRDT. That's why changes to different properties never conflict.
- Deletion without tombstones is safe only because of the server. In a peer-to-peer CRDT, a replica that hadn't seen a delete could re-propagate the object. Figma's rule that "property writes never create objects", applied centrally, makes late writes harmless.
The limits of fractional positions.
- Bisection consumes precision. With 64-bit floats, repeatedly inserting between the same two neighbours halves the gap each time. After roughly 50 inserts at the same spot, the midpoint becomes indistinguishable from an endpoint.
- Arbitrary-precision keys fix it. Production implementations typically use arbitrary-precision fractions encoded as strings, which can always be extended (between "a" and "b" lies "aV"), and occasionally rebalance positions in the background.
- Two clients can pick the same position. If both insert at the same gap concurrently, a deterministic tie-breaker (such as object ID) still yields one order on every client.
The cost of cycle checks.
- The check walks up the tree. Rejecting a parent change that would create a cycle means walking from the new parent to the root and checking whether the moved object appears. That's O(depth), cheap for design files where depth is in the tens.
- The check must be serialised. Two moves that are each acyclic alone can form a cycle together, so the check has to run against the current tree with every earlier write already applied. A single document process does exactly that for free.
- Without a single owner it gets much harder. A peer-to-peer system needs a dedicated move-operation CRDT. Kleppmann et al. describe one in "A highly-available move operation for replicated trees" (2021), and its undo-redo of concurrent moves shows how much work the single owner saves.
Deep Dive: The arithmetic of coalescing, batching, Bloom filters and lake indexesShow
How much does coalescing save?
- Model. Requests for one key arrive at rate λ (Poisson), and a database lookup takes L seconds. When a lookup starts, every request arriving before it completes joins it. Each lookup therefore serves itself plus, on average, λL joiners. The database sees one lookup per cycle: the lookup lasts L, then the gap until the next arrival averages 1/λ.
- Formula. Database rate ≈ 1 / (L + 1/λ) = λ / (1 + λL).
- Worked example. A hot channel gets λ = 10,000 reads/s with L = 10 ms, so λL = 100. The database sees about 10,000 / 101 ≈ 99 reads/s, a 100× reduction. A cold key with λ = 1/s gets λL = 0.01 and essentially no benefit.
- Coalescing self-tunes to hotness. Savings scale with λ, so they're greatest exactly where hot partitions hurt. Better still, when the database slows, L grows and coalescing gets stronger: a negative feedback loop, the opposite of retries.
- The memory side. Waiters per hot key ≈ λL = 100. Across 10,000 simultaneously hot keys that's a million waiting requests, which is why Meta bounds outstanding work and times out waiters.
How much does batching save?
- Cost model. Say each backend request has fixed cost c (framing, syscalls, scheduling, a network round trip) and per-key cost w. A batch of n keys costs c + n·w, so the per-key cost is c/n + w.
- Worked example. With c = 200 µs and w = 20 µs: n = 1 costs 220 µs per key, n = 10 costs 40 µs, and n = 50 costs 24 µs. Most of the gain comes in the first ten keys.
- What it costs in latency. If keys for one shard arrive at rate r and the flush timer is T, the batch size is about min(rT, size cap), and the average added wait is about T/2. At r = 20,000/s per shard, T = 0.5 ms gives n ≈ 10 for an added 0.25 ms. That's why timer-plus-size flushing (Meta's choice) works: high-rate shards fill to the cap before the timer, and low-rate shards are bounded by T.
- Little's law sizes the in-flight cap. In-flight batches = batch rate × backend latency. If the backend latency spikes 10×, in-flight batches would rise 10× unless capped.
Bloom filter sizing, applied to Spotify's pruning.
- The formula. A Bloom filter with m bits, n keys and k hash functions has false-positive rate p ≈ (1 − e^(−kn/m))^k. The best k is (m/n)·ln 2, which gives about 1.44·log₂(1/p) bits per key: roughly 9.6 bits per key for 1%, and 14.4 for 0.1% (Burton Bloom, "Space/time trade-offs in hash coding with allowable errors", 1970) (Probabilistic Data Structures for Big Data).
- Applied. Of the 90 bucketed files, the user is really present in about 12. With p = 1%, the other 78 contribute about 0.78 false-positive files on average, so the reader opens about 13 files. That's why the article can say "about 12".
- The memory cost. A file holding 1 million distinct users needs about 1.2 MB of filter at 1%. Across 90,000 files that's around 100 GB. The filters are worth caching in a metadata store, as Spotify does, but too big to fit in every client.
Why dependent reads dominate.
- Latency is the critical path, not the total. It's about (sequential steps) × (round-trip time) plus transfer time.
- Without an index. The five dependent reads (footer, row-group metadata, key column, page index, pages) at ~50 ms each give about 250 ms per file, even when all 12 files are read in parallel.
- With RAP and cached metadata. Rows map straight to byte ranges, and the remaining three reads are independent, so they're issued together. Critical path ≈ one round trip, about 50 ms on standard GCS or single-digit ms on an express tier.
- With a covering index. Zero reads; the answer comes from the index lookup itself.
- (These per-step numbers are illustrative, from the 30–100 ms request range quoted in the write-up.)
Why the index is "GBs per TB".
- An illustrative estimate. A terabyte of ~1 KB rows is about 10⁹ rows. An index that lists every row number at ~4 bytes each is ~4 GB, plus small per-entry overhead for the key and file ordinal.
- Sorting shrinks it further. If writes are sorted by key, each key's rows in a file form a contiguous range, and one (start, count) pair replaces many row numbers. That's why write shaping helps the index as well as the reads.
- Scaling up. At a petabyte, the same ratio gives terabytes, consistent with the write-up's figures. That's large enough that the index itself is bucketed by key hash, so a lookup touches one index bucket.
The page is the floor. A ~100-byte row in a 4 MB page has a read amplification of 40,000×. Sorting by key and starting a page per key change makes a key's page about the size of that key's rows. The amplification falls toward 1, at ~20 bytes of header per page. With 10⁶ keys per file, that's ~20 MB of headers on what may be a multi-GB file: a fraction of a percent.
Deep Dive: Buffers, backpressure and admission control (Slack and Meta)Show
Why an in-memory queue fails all at once.
- The backlog grows linearly. If producers enqueue at λ jobs/s and workers drain at μ, the backlog grows at (λ − μ) per second. Normally μ > λ and the backlog hovers near zero.
- An illustrative burst. When the database slows, μ drops. Say λ = 50,000/s, μ falls to 30,000/s, and jobs average 2 KB. The backlog grows by 20,000 jobs/s, or 40 MB/s. A 16 GB Redis instance with headroom for its working set fills in a few minutes. (These numbers are illustrative; Slack's post describes the failure, not these figures.)
- Then everything stops at once. In Redis, the backlog and the dispatch machinery share one memory pool. When memory is full, the operations needed to dequeue (moving a job to an in-flight structure, writing state) can fail too. The system can't even drain the backlog that caused the problem. That's the cliff Slack hit: not slower, but stopped.
Why a log fixes it.
- Disk holds the burst. Kafka appends to disk segments and serves recent data from the page cache. A cluster with tens of terabytes absorbs that 40 MB/s burst for days.
- The relay controls the drain. It (JQRelay in Slack's design) moves jobs into Redis no faster than a configured rate. So Redis holds only the in-flight working set, which is bounded by worker concurrency × job size, not by the burst.
- The backpressure point moves. Overload becomes consumer lag, a number you can alert on and drain later, instead of memory exhaustion (Asynchronous Processing and Message Queues).
- The trade-off is visible. A job now waits in Kafka during a burst instead of failing at enqueue. For jobs with deadlines (notifications that are useless after a minute), the consumer must check age and drop stale work. A buffer doesn't make old work useful.
Why queues near saturation explode, and why admission control rejects early.
- Queueing theory. For a single server with random arrivals (M/M/1), the mean time in system is W = 1 / (μ − λ). Writing ρ = λ/μ for utilisation, W = (1/μ) · 1/(1 − ρ).
- Worked numbers:
- at 50% utilisation, latency is 2× service time;
- at 90%, 10×;
- at 99%, 100×. This is why a modest overload turns into enormous queueing delay, and why queues must be bounded. Past a certain wait, the work will time out anyway, so holding it wastes memory and blocks fresher work.
- Little's law sets the bound. If a request is useless after 200 ms and the service handles 5,000/s, a queue longer than about 1,000 requests guarantees some of them will be served after their caller gave up. Reject beyond that and the rejected caller learns instantly.
Fair turns between tenants.
- Isolation by construction. Meta's per-use-case, per-priority queues "served in turns" are a form of round-robin fair queueing. Each queue gets a share of service regardless of how full it is.
- Weighted variants. Weighted fair queueing and deficit round robin, which deals with variable request costs, generalise this so a heavy tenant can be given a larger share without being able to starve others.
- The effect. One team's spike fills only its own queue and is rejected there, while every other team's latency stays flat. It's the same bulkhead idea as separate thread pools, applied to a shared service (Resilience Patterns: Timeouts, Retries and Circuit Breakers).
Rejection only works if retries are disciplined.
- Naive retries keep the overload. If clients retry rejected requests immediately, the offered load stays at overload level and the rejection rate climbs.
- The standard client discipline:
- exponential backoff with jitter, so retries spread out instead of synchronising;
- a retry budget (for example, retries at most 10% of requests), so retries can't multiply traffic during an outage;
- honouring server hints such as a retry-after value.
- Both sides must cooperate. Meta's note that callers must back off is the client half of the contract. Admission control without it just converts CPU spent on work into CPU spent on rejections.
Shadow mode and heartbeat canaries as risk control.
- Shadow mode. Slack double-wrote every job to both paths while the new relay read everything from Kafka and dropped it. Real traffic exercised every new component with zero user impact.
- Counting at every hop plus heartbeat canaries. Jobs were counted at each stage (web app, Kafkagate, Kafka, Redis), and one canary per partition per minute across all 1,600 partitions proved end-to-end flow and timing. A silent stall on any partition would raise an alert.
- Why it's safe. The rollout needs only one property: at every step, turning the new path off returns the system to a known-good state (CI/CD and Deployment Strategies).
Key Takeaways#
- Read write-ups with seven questions: workload, what broke, fixed constraints, rejected options, chosen mechanism, costs, and what's left unsaid. The rejected options and the constraints are what make a lesson transferable.
- Shopify: if two pieces of state must change together, keep them in one database and one transaction. A bounded pool of unit rows claimed with
SKIP LOCKEDturns one hot row into many cold ones. Isolation level and lock order then decide whether it deadlocks. - Discord: a faster database and less database work are separate levers. Routing by key plus coalescing in-flight reads removes duplicate work, and the saving grows with hotness, about λ/(1 + λL).
- Slack: keep the burst backlog on disk (Kafka) and let the fast layer (Redis) hold only what's in flight. Throttle the relay at runtime. Prove the change with shadow writes, per-hop counts and heartbeat canaries before cutting over.
- Figma: a single owner per document makes arrival order the conflict rule, so per-property LWW, client-minted IDs, no tombstones, parent-as-property, server-side cycle rejection and fractional positions add up to a simple, convergent editor. Text is the exception that needs a real CRDT.
- Spotify: prune files with bucketing and Bloom filters, collapse dependent reads with an external append-only index, then shape writes so a key fills its own page. Index the lake instead of copying it, but remember the latency floor of object storage and that no production numbers were published.
- Meta: a gateway is where work from many clients meets, so it can share connections, batch distinct keys, coalesce identical ones, cache with fill locks and CDC freshness, and reject excess per tenant. Diagnose which bottleneck you have before picking a technique.
- Recurring themes: bound every queue, collapse sequential round trips, respect the storage format's atomic unit, migrate incrementally behind a seam, and borrow mechanisms only when their constraints match yours.