LazyLayersv9.1.0
Learn caching

How Discord, Meta, Uber and others handle caching

How Discord stores messages, how Facebook memcache avoids stale sets, how Uber serves 40M reads a second: the caching at scale patterns each one wrote about.

Caching at scale is the same few ideas applied under heavy load: let concurrent callers share one load, send each key to one place, stop late writes from restoring old data, delete cached values after a commit, and refresh before a hot key expires. This page reads what Discord, Meta, Uber, Twitter, Slack, Cloudflare, Netflix, Shopify and AWS published, and names the pattern each one shows.

Level: ten to a hundred · You need: Cache stampede and the thundering herd and Distributed cache system design

Every fact about a company on this page comes from the source linked in its section, and nothing is added from memory. These companies do not use lazy-layers-cache. Each section ends with one line that names the lazy-layers-cache option that covers the same problem, so you can compare the idea with code you can run. The full list of sources is on the references page.

Rendering diagram...

How does Discord store and read messages?

Discord's post "How Discord Stores Trillions of Messages" describes a move from Cassandra to ScyllaDB. The part that matters for caching is what they put in front of the database. They wrote "data services", intermediary services between the API monolith and the database clusters, with roughly one gRPC endpoint per database query and no business logic.

The main feature of a data service is request coalescing. In Discord's words, "If multiple users are requesting the same row at the same time, we'll only query the database once." The first request starts a worker task, and later requests find that task and subscribe to it. The worker queries the database and returns the row to all subscribers.

Upstream, Discord routes with consistent hashing. Each request carries a routing key, which is the channel ID for messages, so all requests for the same channel go to the same service instance. Discord says this routing enables more effective coalescing, since requests for one row can only share a task when they reach the same instance. Discord also says that hot partitions still happen, only less often.

Rendering diagram...

The post describes coalescing and routing. It does not describe a cache that stores rows with a TTL, so treat this as the "share one load" half of caching.

Pattern: request coalescing plus consistent hash routing. Source: How Discord Stores Trillions of Messages.

In lazy-layers-cache: callers in one process share a single loader call by default (inflight), and a Redis lease lets one server load while the others wait (distributedLock). Routing a key to one instance is your load balancer's job, not the cache's.

How does Facebook's memcache avoid stale sets and thundering herds?

"Scaling Memcache at Facebook" (Nishtala et al., NSDI 2013) describes memcache as a "demand-filled look-aside cache". A web server asks memcache first, and on a miss it reads the database and fills the cache. On a write the server updates the database and then sends a delete to memcache. The authors delete instead of updating "because deletes are idempotent".

The paper introduces leases for two problems. A stale set happens when concurrent updates to memcache get reordered, so an old value lands after a newer one. The paper defines a thundering herd as a key with heavy read and write activity, where writes keep invalidating the value and many reads fall through to the database. On a miss, memcached gives the client a 64-bit token bound to the key, and it rejects the set if a delete invalidated the token.

The same mechanism limits the herd. By default each server hands out a token once every 10 seconds per key, and other requests are told to wait a short time and retry. For a set of keys prone to herds, the authors measured one week of misses: the peak database query rate was 17K/s without leases and 1.3K/s with them.

Invalidation after a commit is a separate piece. The paper describes mcsqueal, a daemon on each database that reads the SQL statements the database commits, extracts the deletes, and broadcasts them to the memcache deployment in every frontend cluster. Meta's own mcrouter README says mcrouter handles almost 5 billion requests per second at peak.

Pattern: leases against stale sets, token rate limiting against herds, invalidation after commit. Sources: the NSDI 2013 paper (PDF), the Meta post Scaling memcache at Facebook and the mcrouter README.

In lazy-layers-cache: every delete advances a per-key generation, so peers ignore an older set event that arrives late, which is the same job as a lease against a stale set. The Redis lease in distributedLock plays the herd role. See event ordering.

How does Uber's CacheFront keep Redis in step with MySQL?

Uber's post describes CacheFront, an integrated cache for Docstore, which the post calls "Uber's in-house, distributed database built on top of MySQL". Reads use a cache-aside strategy: try Redis and stream the response, retrieve any remaining rows from the storage engine, then populate Redis asynchronously. Without explicit invalidation, entries expire after a configured TTL, 5 minutes by default.

For invalidation, a service named Flux tails the MySQL binlog events, and a consumer invalidates or upserts the changed rows in Redis. The post says that by using binlogs, "we don't run the risk of letting uncommitted transactions pollute the cache", and that with Flux the cache is 99.99% consistent.

The post reports that CacheFront supports over 40M requests per second across all Docstore instances, and that one large use case drives over 6M reads per second with a 99% hit rate. Note that Uber describes this as cache-aside, not read-through, and does not describe request coalescing.

Pattern: cache-aside reads, short TTL as a safety net, invalidation driven by committed changes. Source: How Uber Serves Over 40 Million Reads Per Second from Online Storage Using an Integrated Cache.

In lazy-layers-cache: getOrSet is the cache-aside read, ttlMs is the safety net, and invalidate or invalidateByPattern after your database commit clears every server's copy over an event bus. The Redis Streams outbox bus is the closest match to a log-driven pipeline.

What did Twitter learn from 153 cache clusters?

The OSDI 2020 paper by Yang, Yue and Rashmi analyzes traces from 153 Twemcache clusters at Twitter, "sifting through over 80 TB of data". It reports that in-memory caching does not always serve read-heavy workloads: write-heavy workloads, defined as a write ratio above 30%, occur in more than 35% of the clusters. It also finds that TTL limits the effective working set, and that "FIFO often shows similar performance as LRU" at reasonable cache sizes.

Twitter's open source Pelikan README describes Pelikan as "Twitter's framework for developing cache services". S3-FIFO, the default L1 policy in lazy-layers-cache, comes from a different paper whose authors include Yang, Yue and Rashmi, who also wrote the Twitter study.

Pattern: measure your own workload before choosing eviction, and expect writes and TTLs to matter as much as reads. Sources: Yang et al., OSDI 2020 (PDF) and Pelikan.

In lazy-layers-cache: L1 eviction is a setting, levels: { L1: { policy: 's3fifo' } }, and you can switch to lru, lfu, sieve or fifo. See LRU cache and eviction policies.

How does Slack's Flannel cache at the edge?

Slack's engineering post describes Flannel as "an application-level caching service developed in-house and deployed to our edge points-of-presence". When a client connects, Flannel caches data about users, channels and bots and exposes query APIs, instead of the client loading everything at startup. Flannel holds a WebSocket connection to Slack servers in the main AWS region to stay current by consuming real-time events.

Slack uses consistent hashing to choose which Flannel host a user connects to, so users on the same team from the same networking region reach the same instance, which Slack says gives optimal cache efficiency. New or reconnecting users are served from the Flannel cache, which reduces the effect of reconnect storms on the backend. The post reports 4 million simultaneous connections and 600K client queries per second at peak.

Pattern: an edge cache close to users, with consistent hashing for team affinity. Source: Flannel: An Application-Level Edge Cache to Make Slack Scale.

In lazy-layers-cache: L1 keeps a copy next to each server and an event bus keeps copies in step, but the library does not route users to hosts. Do that routing in your load balancer. A Workers deployment can use Cloudflare KV as the shared layer.

How does Cloudflare avoid a cache lock?

Cloudflare's post "Sometimes I cache" starts from the usual fix for a stampede, a cache lock that lets one request go to the origin, called request collapsing. It then proposes a lock-free alternative: "For every request going to the origin, we simulate a die roll." Most requests stay on the stale copy, and the chance of revalidating rises as expiry approaches.

The post is honest about the trade. A lock is deterministic for the same key and scales well, but it adds latency and can be unavailable. The probabilistic approach has no external service to call, at the cost of "not guaranteeing the number of requests going to the origin server". The author then says the approach is close to what Vattani, Chierichetti and Lowenstein present in their VLDB 2015 paper, which uses a continuous exponential probability instead of fixed steps.

Pattern: probabilistic early revalidation, also called XFetch. Sources: Sometimes I cache and Optimal Probabilistic Cache Stampede Prevention.

In lazy-layers-cache: earlyRefresh: 0.8 reloads a key in the background after 80% of its TTL, the fixed-threshold form of the idea. The random version above spreads that choice across readers. The stampede lesson shows both in TypeScript.

What is Netflix's EVCache?

The EVCache README is short. It describes EVCache as "a memcached & spymemcached based caching solution that is mainly used for AWS EC2 infrastructure for caching frequently used data". The name is an abbreviation: Ephemeral (the data lives for the duration of its TTL), Volatile (the data can disappear at any time, for example by eviction) and Cache (an in-memory key-value store).

That definition is the useful part for beginners. A cache may lose any entry at any moment, so every read path needs a loader that works without it.

Pattern: treat the cache as ephemeral and volatile. Source: Netflix/EVCache.

In lazy-layers-cache: failSafe serves the last stored value when the loader fails, and a Redis outage falls back to memory and the loader. In a recorded run, a 4 s Redis freeze caused 0 errors. See failure handling.

How does Shopify's IdentityCache expire data?

The IdentityCache README calls it "Opt in read through ActiveRecord caching used in production and extracted from Shopify". Memcached is the backend, and the database is only hit when a copy of the object cannot be found there. It uses an after_commit hook to expire cached objects, and any objects up the tree, when they change.

The sample configuration sets expires_in: 6.hours.to_i with the comment "in case of network errors when sending a cache invalidation". That is the same safety net as Uber's TTL: if a delete is lost, the entry still ages out.

Pattern: invalidate in a commit hook, and keep a TTL for the lost-message case. Source: Shopify/identity_cache. The transactional outbox pattern, described by microservices.io, is the general way to make "update the database and send a message" reliable.

In lazy-layers-cache: call invalidate, invalidateByPattern or invalidateTags after the commit, and keep a finite ttlMs. The cache invalidation lesson covers the order of operations.

What does the AWS Builders' Library recommend?

The Builders' Library article "Caching challenges and strategies" compares on-box (in-process) caches with external caches. It says in-memory caches are susceptible to "cold start" issues, where a new server launches with an empty cache and sends a burst of requests to the dependency, and that request coalescing can address this. External caches avoid cold starts during deployments because the cache stays populated, but add a fleet to operate.

For thundering herds, the article says they use request coalescing, "where the servers or external cache ensure that only one pending request is out for uncached resources". For resilience it describes two TTLs, a soft TTL and a hard TTL: the client tries to refresh at the soft TTL, and if the downstream service does not respond, it keeps using the cached data until the hard TTL. The article also recommends a negative cache with a TTL different from positive entries, and warns that falling back to the dependency during a long cache outage causes a spike in traffic to it.

Pattern: coalescing, soft and hard TTL, negative caching, and a plan for cache outages. Source: Caching challenges and strategies.

In lazy-layers-cache: inflight coalesces, failSafe with timeouts: { softMs, hardMs } and staleWhileRevalidate: true cover the soft and hard behavior, and negativeCache is on for 10 s by default. The loader limits (maxConcurrent, maxQueued) cap the fallback spike.

Which pattern did each company show?

PatternWho wrote about itLesson on this sitegetOrSet option
Request coalescingDiscord, AWS Builders' Library, groupcache, singleflight, VarnishCache stampedeinflight
Lease against herds and stale setsMeta, NSDI 2013Cache stampededistributedLock
Ignore late writesMeta, NSDI 2013Cache invalidationAutomatic: every delete advances a generation
Consistent hashingDiscord, Slack, Karger et al.Distributed cache designNone: routing is your load balancer or Redis Cluster
Invalidate after commitMeta, Uber, ShopifyCache invalidationinvalidate, invalidateByPattern, tags
Probabilistic early refreshCloudflare, Vattani et al.Cache stampedeearlyRefresh
Soft and hard TTL, serve staleAWS Builders' Library, RFC 5861, Varnish grace mode, FusionCache fail-safeCache stampedefailSafe, staleWhileRevalidate, timeouts
Negative cachingAWS Builders' LibraryCache stampedenegativeCache
Ephemeral cache, loader always worksNetflix EVCacheWhat is caching?failSafe, ttlMs
Pick eviction from your workloadTwitter, OSDI 2020LRU cache and evictionlevels: { L1: { policy } }

What should you take from this?

Most of these systems added the same few things in the same order: share one load, delete after commit, keep a TTL as a safety net, and plan for the cache being empty or down. None of them describes a cache that never serves stale data. They describe how long stale data lives and how a stale write is stopped.

Pick the one row of the table that matches your next incident, read its source, and then try the matching option in getOrSet. The references page lists every paper, post and library cited in this course.

Back to the course overview.

Questions

How does Discord stop hot partitions when reading messages?

Discord put data services between its API and its ScyllaDB clusters. When several users request the same row at once, the service queries the database one time and shares the answer with every waiting request. Discord also routes by channel ID with consistent hashing, so requests for one channel reach the same instance.

What is request coalescing?

Request coalescing means concurrent requests for the same key share one in-flight load. The first request starts the work and later requests wait for its result. Discord's data services do this for database rows, the AWS Builders' Library recommends it against thundering herds, and Go ships it as singleflight.

What are leases in Facebook's memcache?

A lease is a 64-bit token that memcached gives a client on a cache miss, bound to that key. The client must present it when it sets the value, and memcached rejects it if the key was deleted in the meantime. That blocks stale sets. By default a token is handed out once every 10 seconds per key, which also slows a thundering herd.

How does Uber keep its Redis cache in step with MySQL?

Uber's CacheFront reads from Redis first and fills misses from the storage engine. Entries expire after 5 minutes by default. A change data capture service named Flux tails the MySQL binlog and a consumer invalidates or upserts rows in Redis, so uncommitted transactions never reach the cache.

What can a small team learn from how large companies cache?

The same few patterns apply at any size. Share one load among concurrent callers, delete cached values after the database commit, give stale values a short life, and plan for the cache to be empty or down. Start with these in one process, and add shared layers only when a measurement asks for them.

On this page