Library / Case Studies
Standardize and Improve Microservices Caching at DoorDash
DoorDash's in-house caching system offers backend developers a fast, safe, and efficient way to introduce new caches.
By DoorDash engineers · DoorDash · Added 2026-10-12
All content belongs to DoorDash engineers / DoorDash. We only link to it and give credit. Report a problem
Learn this case study
About 37 min left. Your work is saved as you go.
What you are about to study
DoorDash explains a real system. You should know the basics: caching, queues and replication.
Ideas you will meet
- Caching
- Cache-aside, write-through, eviction and invalidation strategies.
- Microservices
- Decompose systems into independently deployable services.
- Distributed Systems
- Consensus, time, failure and the fundamentals of scale-out.
What we already know about this
Our own lessons on these ideas. Read them here before you start, so it makes sense.
Real-World Systems · 11 minHow microservices work togetherSynchronous calls, events, sagas and discovery: how separate services cooperate without becoming one tangled system.Read here
What a microservice architecture is
Instead of one large application, the system is split into small services, each responsible for one business capability (orders, payments, inventory, users). Services are deployed and scaled independently, often by different teams, and talk over the network.
The benefits are independent deployment, team autonomy and targeted scaling. The cost is that everything that used to be a function call is now a network call that can be slow or fail, and data is spread across services.
Ways services talk
Style How Good for Cost Synchronous request and response (REST, gRPC) Caller waits for the answer Queries and steps the user waits for Coupling in time; failures propagate Asynchronous messages and events (queues, streams) Caller publishes and moves on Reactions, workflows, decoupling Eventual consistency; harder to trace 100%Figure SDA-RWS-13-1 · Services: sync calls, events and owned data · © forcsguy.com
100%Figure SDA-RWS-13-2 · Two ways to run a multi-step process · © forcsguy.com
Before: a chain of synchronous calls
100%After: events between services
100%What changed
- A slow service no longer blocks the order
- New services can listen without changing the sender
- The result is eventually consistent, so design for that
Data ownership
Each service owns its own data and exposes it only through its API or events. No other service reads its tables. This keeps boundaries real, but it means you cannot join across services in SQL: you call APIs or keep read models built from events.
Keeping things consistent: sagas
A business action often spans services (take payment, reserve stock, create shipment). A single database transaction cannot cover them. A saga is a sequence of local transactions, each with a compensating action:
- Create the order (pending).
- Reserve stock. Compensation: release stock.
- Charge the payment. Compensation: refund.
- Confirm the order. If any step fails, run the compensations for earlier steps in reverse.
Two ways to run a saga:
- Choreography: services react to each other's events. Simple and decoupled, but the overall flow is spread out and hard to see.
- Orchestration: a coordinator (an orchestrator service or workflow engine) tells each service what to do next and handles failures. The flow is explicit and easier to reason about.
The outbox pattern
A service must update its database and publish an event, and one may succeed without the other. Write the event to an outbox table in the same transaction, and let a separate process publish it. Consumers must be idempotent, because delivery is at least once.
Finding and reaching services
- Service discovery (via the platform, DNS or a registry) tells callers where healthy instances are, since addresses change constantly.
- An API gateway is the front door for external clients: routing, authentication, rate limiting. A backend for frontend shapes responses for a specific client.
- A service mesh adds a sidecar proxy next to each service to provide mutual TLS, retries, timeouts and metrics without changing application code.
Resilience between services
Reuse the reliability tools: timeouts, retries with backoff and jitter, circuit breakers and bulkheads. Prefer asynchronous communication where a user does not need an immediate answer.
Operating many services
- Distributed tracing with a correlation id shows a request's path across services.
- Contract testing and careful API versioning let teams change without breaking each other.
- Beware the distributed monolith: services so entangled they must be deployed together, which gives you all the costs and none of the benefits. Split along business boundaries, not technical layers.
- Start with a well-structured monolith if the team is small. Split when a real need appears.
More on this site
Related reading
- Pattern: Transactional outboxChris Richardson · microservices.ioDocumentation
- Pattern: SagaChris Richardson · microservices.ioDocumentation
- Awesome MicroservicesMehdi Fornos · mfornosGitHub
- Microservices PatternsChris Richardson · ManningBooks
Show 6 moreShow fewer
- Tech Dummies: System Design Case StudiesNarendra L · Tech DummiesYouTube
- Payment Transaction Management in Microservices at MercariMercari engineers · MercariCase Studies
- Circuit BreakerMartin FowlerBlogs
- Avoiding insurmountable queue backlogsAmazon Builders' Library · Amazon Web ServicesBlogs
- Microservice Architecture at MediumMedium engineers · MediumCase Studies
- Back-end at FlickrFlickr engineers · FlickrCase Studies
Messaging and Microservice Patterns · 13 minOperating microservices: config, secrets, feature flags, tracing and loggingThe operational toolkit around a service: configuration and secrets done safely, feature flags for controlled releases, and traces and logs that follow a request across services.Read here
Configuration
Separate configuration from code. Anything that changes between environments (database address, feature limits, endpoints) should come from environment variables, config files or a config service, not be baked into the build ("build once, run anywhere").
- Keep defaults in code and overrides in the environment.
- Validate configuration at start-up and fail fast with a clear message.
- For values that must change at runtime, use a config service or watch a mounted file, and treat changes like deployments (versioned, reviewed, auditable).
- Keep config in version control (as code or templates) so changes are reviewed and reversible.
Secrets
Secrets (passwords, API keys, private keys, tokens) need stricter handling.
- Never commit them, put them in images, or print them in logs.
- Store them in a secrets manager (a cloud service, HashiCorp Vault, or an encrypted platform secret store) with access control, audit logs and encryption at rest.
- Inject at runtime (environment, mounted file or an agent), and use short-lived credentials where possible (cloud roles, dynamic database credentials).
- Rotate regularly and after any suspected leak; design services to reload secrets without downtime.
- Least privilege: each service gets only its own secrets.
Feature flags
A feature flag is a runtime switch controlling whether code runs, separate from deployment.
100%Figure SDA-MSV-05-1 · Deploy is not release · © forcsguy.com
Uses: gradual rollout, kill switches for risky features, A/B tests, per-customer entitlements, and decoupling release from deploy (see the deployment strategies lesson). Cautions: flags multiply test combinations, can be left in place forever, and a flag service outage must fail to a safe default.
Distributed tracing
A request through a microservice system touches many services. A trace records the whole journey as a tree of spans (one per operation), joined by a trace id passed in request headers.
100%Figure SDA-MSV-05-2 · One request traced across services · © forcsguy.com
- OpenTelemetry is the vendor-neutral standard for instrumentation (traces, metrics, logs) and the W3C Trace Context header standardises propagation.
- Propagate the id through every hop, including message queues (put it in message headers).
- Add useful attributes (user type, order size) but never secrets or personal data.
- Sampling: keep all errors and slow traces, a small share of the rest.
Centralised logging
Logs written on many short-lived instances are useless unless shipped to one searchable place.
- Write structured logs (JSON with fields: time, level, service, trace id, message, key attributes) to standard output; let the platform collect them.
- Ship to a central system (the ELK/OpenSearch stack, Loki, Splunk, cloud logging).
- Always include the trace id so logs and traces connect.
- Set levels sensibly; avoid logging personal data and secrets; set retention by value and legal need.
- Alert on log-derived signals sparingly; prefer metrics for alerting.
Health checks
Expose liveness (the process is alive; restart if not), readiness (ready to take traffic; remove from rotation if not) and optionally startup endpoints. Readiness should check what the service truly needs without cascading (a failing optional dependency should degrade, not mark the service unready for everyone).
A minimum for every service
A health endpoint, structured logs with trace ids, the standard metrics (request rate, errors, latency, saturation), propagated trace headers, config and secrets from the environment, and a runbook. The next lesson turns these signals into targets and alerts.
Real-world reading
Related reading
- Feature Toggles (aka Feature Flags)Pete Hodgson · Martin FowlerBlogs
- DevOps Roadmaproadmap.sh community · roadmap.shCourses
- Ensuring rollback safety during deploymentsAmazon Builders' Library · Amazon Web ServicesBlogs
- Dapper: a Large-Scale Distributed Systems Tracing Infrastructure (paper)Sigelman et al. · GooglePapers
Show 6 moreShow fewer
- Blue Green DeploymentMartin FowlerBlogs
- The Twelve-Factor AppAdam Wiggins · 12factor.netDocumentation
- XCMetrics: All-in-One Tool for Tracking Xcode Build Metrics at SpotifySpotify engineers · SpotifyCase Studies
- Going faster with continuous deliveryAmazon Builders' Library · Amazon Web ServicesBlogs
- Unicorn: Remediation System at eBayeBay engineers · eBayCase Studies
- Distributed Tracking, Tracing, and MeasuringOreilly engineers · OreillyCase Studies
System Design Foundations · 11 minCachingHow keeping popular data in fast memory makes systems quicker, and the invalidation problems that come with it.Read here
Why a cache helps
Reading from memory is thousands of times faster than a database round trip (lesson 3). A cache keeps copies of frequently needed data in fast storage so most requests never reach the slower source. The results: lower latency, less load on the database, and lower cost.
100%Figure SDA-FND-06-1 · Cache-aside read path · © forcsguy.com
Before: every read hits the database
100%After: a cache answers most reads
100%What changed
- Most reads never reach the database
- Responses are faster because memory is quicker than disk
- The cache can be stale, so you decide how long is acceptable
Where caches live
- In the browser: controlled with HTTP headers such as
Cache-Control. - At the edge (CDN): copies of pages and files near the user (lesson 9).
- In the application tier: a shared cache like Redis or Memcached.
- Inside the database: buffer pools and query caches.
You can use several at once, each answering whatever it can.
Common strategies
Strategy How it works Good for Cache-aside App checks cache, on miss reads the database and fills the cache the default for most read-heavy data Read-through The cache itself loads from the database on a miss simpler app code Write-through Writes go to the cache and the database together data you read right after writing Write-behind Writes go to the cache first and reach the database later very high write rates, if you can risk losing a little Write-behind is fast but dangerous: if the cache fails before it flushes, writes are lost.
Writes can use the cache in three different ways. The sequence shows when the database learns about the change:
100%Figure SDA-FND-06-2 · Write-through: update the cache and the database together · © forcsguy.com
100%Figure SDA-FND-06-3 · Write-back: acknowledge first, save later · © forcsguy.com
100%Figure SDA-FND-06-4 · Write-around: skip the cache on writes · © forcsguy.com
Watch one read with and without a warm cache. Press Play both together, and use the Simulate tab to slow the network and see the gap grow.
Before: no cache
100%After: cache hit
100%What changed
- The database is not asked at all
- Two network hops disappear from the request
- The saving grows as the network gets slower
The hard part: invalidation
There are only two hard things in computer science: cache invalidation and naming things.
A cache holds a copy, and copies go stale. Your options:
- Time to live (TTL): entries expire after a set time. Simple, but data can be stale until then.
- Explicit invalidation: delete or update the cache entry when the source changes. Fresher, but you must never forget a code path.
- Versioned keys: put a version in the key (
product:42:v7) so a change simply starts using a new key.
Most real systems combine a TTL (a safety net) with explicit invalidation on writes.
100%Figure SDA-FND-06-5 · Defending the database from lookups of keys that do not exist · © forcsguy.com
Eviction: what to drop when full
Memory is limited, so a cache removes items when it fills. Common policies: LRU (least recently used), LFU (least frequently used) and FIFO. LRU is a good default.
Failure modes to know
- Cache stampede: a hot key expires and many requests rebuild it at once. Fix with a lock, request coalescing, or adding random jitter to expiry times.
- Cache penetration: requests for keys that do not exist always miss and reach the database. Fix by caching "not found" briefly, or with a Bloom filter.
- Cold start: after a restart the cache is empty and the database takes the full load. Warm the cache or ramp traffic up.
- Inconsistency: two writers update the cache and database in different orders. Prefer deleting the cache entry on write over updating it.
A worked example: what a cache is really worth
Suppose a product page reads from a database in 20 ms and from a cache in 1 ms, and the site serves 10,000 reads per second.
Cache hit rate Average latency Reads reaching the database 0% (no cache) 20 ms 10,000 per second 50% 10.5 ms 5,000 per second 90% 2.9 ms 1,000 per second 99% 1.2 ms 100 per second The average latency is
hit x 1 + (1 - hit) x 20. Notice two things. First, going from 90% to 99% barely changes the average (2.9 to 1.2 ms) but cuts database load ten times. That is usually the real prize: a cache is a way to protect the database. Second, the first 50% is cheap and the last 9% is expensive: it needs a much bigger cache, because the remaining misses are the long tail of rarely requested items.How big should it be? Traffic is usually skewed: a small share of items gets most requests (often described as "80% of requests go to 20% of items", and for popular content it is more extreme). Estimate your working set: the items requested within your cache lifetime. If 2 million product pages exist but 100,000 get 90% of the traffic, a cache that holds 150,000 of them at about 5 KB each needs only 750 MB. Measure the hit rate while changing the size, and stop growing when the curve flattens.
100%Figure SDA-FND-06-6 · Hit rate rises quickly, then flattens · © forcsguy.com
Stampedes: when a popular key expires
Take a homepage fragment read 5,000 times a second and cached for 60 seconds. At the moment it expires, thousands of requests miss at once, and every one of them rebuilds it from the database. The database, which was lightly loaded because of the cache, suddenly takes a spike. If the rebuild is slow, requests pile up, the spike lasts longer, and the system can fall over exactly when it is busiest.
Ways to defend:
- Request coalescing (single flight). Let one request rebuild the value while the others wait for its result.
- A short lock on rebuild. The first request takes a lock and rebuilds; the rest either wait briefly or serve the old value.
- Stale-while-revalidate. Keep serving the expired value for a few more seconds while one background request refreshes it. Users see slightly old data and never see a spike.
- Jittered expiry. Add a random amount to each TTL (for example 60 seconds plus up to 10) so thousands of keys written together do not all expire together.
- Refresh ahead. For a handful of known-hot keys, refresh them on a schedule before they expire.
100%Figure SDA-FND-06-7 · One request rebuilds, the others wait or use the old value · © forcsguy.com
Mistakes people make
- Caching without a plan for invalidation. "Cache it for an hour" is a promise that users may see hour-old data. Decide what staleness each kind of data tolerates (a like count: minutes; a price or permission: seconds or never).
- Caching per-user data under a shared key. If a personalised page is cached under a key that does not include the user, the next visitor sees someone else's data. Include everything that changes the response in the key, or do not cache it.
- Treating the cache as the source of truth. Caches lose data on restart or eviction. The database must be able to rebuild everything.
- Ignoring the hot key. One enormously popular key can overload a single cache node. Replicate that key across nodes or add a small in-process cache in front.
- Not measuring. Track hit rate, evictions, memory use and the latency of misses. A cache you do not measure is a guess.
Try it yourself
In the System Builder, open "The database becomes the bottleneck". Run it without a cache and watch the database turn red, then add a cache and try different sizes. In the sandbox, raise the "popular-item skew" slider and notice how much a small cache helps when a few items dominate. You can also open the cached design on the free canvas and try wiring the cache in front of different parts.
More on this site
Related reading
- Flannel: An Application-Level Edge Cache to Make Slack ScaleSlack Engineering · SlackCase Studies
- Redis UniversityRedis · Redis Ltd.Courses
- Redis BlogRedis engineers · Redis Ltd.Blogs
- RedisRedis · Redis Ltd.GitHub
Show 6 moreShow fewer
- Redis DocumentationRedis · Redis Ltd.Documentation
- TAO: Facebook's Distributed Data Store for the Social Graph (paper)Bronson et al. · Meta (Facebook)Papers
- Build Your Own XCodeCrafters · GitHubGitHub
- Memory Optimization in Redis at WattpadWattpad engineers · WattpadCase Studies
- Redis Fleet at HerokuHeroku engineers · HerokuCase Studies
- Redis at TrivagoTrivago engineers · TrivagoCase Studies
Go deeper on this
A path through videos, articles, other case studies and code on the same ideas as Standardize and Improve Microservices Caching at DoorDash.
Warm upGet the vocabulary first.
Books · Free from the author
The Architecture of Open Source Applications
Chapters by the creators of real open-source systems explaining their architecture; free to read.
aosabook.orgIntermediate
Documentation
Cloud Design Patterns
A catalogue of design patterns for cloud systems with guidance on when to use each.
Microsoft AzureIntermediate
WatchHow others solve the same problem, on video.
Videos belong to their creators and play from YouTube. More on YouTube (opens in a new tab)
ReadEngineers explain it in their own words.
Blogs
Netflix Technology Blog
Engineering posts on resilience, streaming, data and chaos engineering at Netflix.
NetflixAdvanced
Blogs · Free from the author · Read here
Scalable Web Architecture and Distributed Systems
A full chapter on the building blocks of large websites: availability, performance, reliability, scalability, caches, proxies, indexes, load balancers and queues. Free to read here under CC BY 3.0.
The Architecture of Open Source ApplicationsBeginner40 min
See it in another companyThe same ideas, a different system.
Case Studies · Read here
CDN Services at Spotify
Spotify built its business on flawless content delivery. Our streaming platform serves up more than 50 million tracks (plus an array of images and other assets) to more than 230 million monthly active users around the...
SpotifyIntermediate
Case Studies · Read here
Moving persistent data out of Redis at Github
Historically, we have used Redis in two ways at GitHub: We used it as an LRU cache to conveniently store the results of expensive computations over data originally persisted in…
GithubIntermediate
Read the codeSee how it looks when it is real.
GitHub
Engineering Blogs
A huge directory of company engineering blogs to learn from real production systems.
kilimchoiIntermediate
GitHub
Awesome Scalability
Curated reading list of articles on the architecture of scalable, reliable systems.
binhnguyennusIntermediate
Keep learning
Loading community…