Library / Case Studies
Protector: Circuit Breaker for Time Series Databases at Trivago
At trivago we store a subset of our realtime metric data in InfluxDB and we are quite impressed by the load it can handle. Despite all the joy, we had to learn some lessons the hard way. It is p...
By Trivago engineers · Trivago · Added 2026-10-12
All content belongs to Trivago engineers / Trivago. 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
Trivago explains a real system. You should know the basics: caching, queues and replication.
Ideas you will meet
- Resilience
- Timeouts, retries, circuit breakers, bulkheads and load shedding.
- Databases
- Schemas, indexes, query plans and choosing a store.
- Time and Ordering
- Logical clocks, vector clocks and bounded clock error.
What we already know about this
Our own lessons on these ideas. Read them here before you start, so it makes sense.
Advanced Distributed Systems · 13 minResilience: timeouts, retries, bulkheads, backpressure and circuit breakersHow to stop one slow or failing dependency from taking everything down: the patterns, how they fit together and where each one goes wrong.Read here
The core problem
In a system of many services, slowness is more dangerous than failure. A dependency that fails fast is easy to handle. One that responds in 30 seconds makes callers hold threads, connections and memory until they too stop responding: a cascading failure. Resilience patterns limit how far a problem can spread.
The toolbox
100%Figure SDA-ADS-06-1 · Resilience layers around a call · © forcsguy.com
Timeouts
Every network call needs a timeout, including connect, read and overall. Pick from measured latency (for example slightly above the 99th percentile), not a guess, and make the caller's budget smaller than its own caller's so work is abandoned in an orderly way. Propagate deadlines across calls.
Retries
Retry only transient failures and only idempotent operations (or use idempotency keys). Use exponential backoff with jitter (random spread) so clients do not retry in lockstep, cap the attempts, and apply a retry budget (for example no more than 10 percent extra traffic). Retry at one layer, not at every layer, or attempts multiply.
Circuit breaker
A breaker watches failures or slow calls. Closed: normal. After too many failures it opens: calls fail immediately (or use the fallback) so the dependency can recover and callers stop wasting resources. After a cool-down it goes half-open: a few trial calls decide whether to close again.
100%Figure SDA-ADS-06-2 · Circuit breaker states · © forcsguy.com
Bulkheads
Partition resources so one dependency cannot consume them all: separate thread pools or connection pools per dependency, separate queues per tenant or per priority, or separate instances for critical paths. A slow recommendation service then cannot starve checkout.
Backpressure and load shedding
If producers outpace consumers, work piles up. Without limits the buffer grows until memory is exhausted or latency becomes huge. Options:
- Bounded queues that reject or block when full.
- Signalling upstream to slow down (credit-based flow in streaming systems, TCP windows, reactive streams).
- Load shedding: deliberately drop low-priority work early (return 429 or 503 quickly) to protect the rest.
- Rate limiting at the edge (see the rate-limiter lesson).
Failing fast and visibly under overload is better than accepting everything and failing slowly.
Fallbacks and graceful degradation
Return something useful when a dependency fails: cached data, a default, a simpler algorithm, or hide a non-essential section. Decide which features are essential before an incident, and test the degraded mode.
How they interact
- A timeout is the minimum; without it nothing else works.
- Retries inside a breaker inside a bulkhead is the usual nesting.
- Everything needs metrics: breaker state, rejected calls, queue depth, timeout counts. Alert on them.
- Test it: inject latency and failures (chaos experiments) to confirm the patterns work before production does it for you.
Common mistakes
Retries with no backoff; timeouts longer than the caller's; unbounded queues; a shared thread pool for everything; breakers that never close; fallbacks that call the same failing service; and testing only the happy path.
Real-world reading
Related reading
- Timeouts, retries, and backoff with jitterAmazon Builders' Library · Amazon Web ServicesBlogs
- Using load shedding to avoid overloadAmazon Builders' Library · Amazon Web ServicesBlogs
- Circuit BreakerMartin FowlerBlogs
- Circuit Breaker patternMicrosoft · Microsoft AzureDocumentation
Show 6 moreShow fewer
- Google SRE Book: Addressing Cascading FailuresGoogle SRE team · GoogleBlogs
- Chaos Monkey (source)Netflix · GitHubGitHub
- Bulkheads: Partition and Tolerate Failure in One PartSkife engineers · SkifeCase Studies
- Protector: Circuit Breaker for Time Series Databases at TrivagoTrivago engineers · TrivagoCase Studies
- Autoscaling Jenkins at TrivagoTrivago engineers · TrivagoCase Studies
- Troubleshooting a Connection Timeout Issue with tcp_tw_recycle Enabled at eBayeBay engineers · eBayCase Studies
Databases Deep Dive · 12 minReplication topologies and multi-region databasesSingle-leader, multi-leader and leaderless replication, how they handle conflicts and lag, and what changes across regions.Read here
Why replicate
Replication keeps copies of data on several machines for three reasons: availability (survive a node failure), read scaling (serve reads from replicas) and latency (put data near users). The hard part is keeping copies consistent while writes continue. (Basics are in the replication and sharding lesson of the foundations course; this lesson compares the topologies.)
Single-leader (primary and replicas)
One node, the leader (primary or master), accepts writes and ships its changes to followers (replicas), which serve reads.
100%Figure SDA-DDV-04-1 · Single-leader replication · © forcsguy.com
- Synchronous replication waits for a follower before acknowledging: safer, slower, and a stalled follower can block writes. Asynchronous is faster but a failover can lose the latest writes. A common compromise: one synchronous follower, others asynchronous.
- Failover must detect failure, choose the most up-to-date replica, redirect clients and ensure the old leader does not come back believing it still leads (split brain).
- Replication lag causes stale reads. Techniques: read-your-writes (route a user's reads to the leader shortly after they write), monotonic reads (keep a user on one replica), and checking replica position.
Multi-leader
Several nodes accept writes (often one per region) and replicate to each other. Benefits: local write latency and continued operation if a region is cut off. Cost: write conflicts.
Conflict handling options:
- Avoid them: route all writes for one record to one leader (for example by user or region).
- Last write wins by timestamp: simple, but silently drops one of two concurrent updates and depends on clocks.
- Merge values (union of sets, counters) using mergeable data types (CRDTs; see the collaborative editing lesson).
- Custom resolution in application code, or ask the user.
Multi-leader also appears in offline-capable apps (each device is a leader) and collaborative editing.
Before: single leader
100%After: multi-leader across regions
100%What changed
- Users in each region write to a nearby database
- Concurrent edits to the same row need conflict handling
- More moving parts to run and monitor
Leaderless (Dynamo-style)
Any replica accepts writes; clients write to several replicas and read from several, using quorums (
W + R > N) to get fresh data (see the key-value store lesson). Background anti-entropy and read repair fix stale copies; versions or vector clocks detect conflicts. It favours availability and is typical of Cassandra and DynamoDB-style stores.100%Figure SDA-DDV-04-2 · Choosing a replication model · © forcsguy.com
Multi-region designs
- Active-passive: one region serves writes; another is a warm standby. Simple; failover loses a little data (the replication lag) and takes minutes.
- Active-active: several regions serve traffic. Requires either partitioning data by home region (each record has one home, cross-region reads are replicas) or true multi-leader conflict handling.
- Global databases use consensus across regions (see the consensus lesson) for strong consistency at the cost of cross-region write latency; some offer tunable consistency per query.
- Latency numbers matter: a cross-ocean round trip is around 100 ms or more, so synchronous cross-region replication adds that to every write.
- Data residency laws may require keeping certain users' data in a region.
Partitioning and replication together
Real systems shard data into partitions and replicate each partition (a leader per partition spreads write load across nodes). Rebalancing, hot partitions and cross-partition transactions are the new problems (see sharding and the consistent-hashing lesson).
Master/slave naming
You will see "master/slave", "primary/replica" and "leader/follower" for the same single-leader idea; most current documentation prefers the last two.
Checklist
- What happens to writes if the leader or a region is lost, and how long?
- How much data can we lose (RPO) and how long can we be down (RTO)?
- How do we handle stale reads from replicas?
- Who resolves conflicts, and how?
- Have we practised failover?
Real-world reading
Related reading
- Active-Active for Multi-Regional ResiliencyNetflix Engineering · NetflixCase Studies
- Designing Data-Intensive ApplicationsMartin Kleppmann · O'ReillyBooks
- Read Consistency with Database Replicas at ShopifyShopify engineers · ShopifyCase Studies
- Uber Schemaless: A Scalable MySQL DatastoreUber Engineering · UberCase Studies
Show 6 moreShow fewer
- Mitigating MySQL Replication Lag and Reducing Read Load at GithubGithub engineers · GithubCase Studies
- Cassandra architecture overviewApache Cassandra · Apache Software FoundationDocumentation
- How Discord Stores Trillions of MessagesBo Ingram · DiscordBlogs
- Spanner: Google's Globally Distributed Database (paper)Corbett et al. · GooglePapers
- Scaling Multitenant Architecture Across Multiple Data Centres at Shopify - Weingarten, Engineering Lead at ShopifyShopifyYouTube
- MIT 6.824: Distributed SystemsRobert Morris · MITCourses
Databases Deep Dive · 13 minChoosing a database typeA practical map from workload to database: relational, document, key-value, wide-column, search, graph, time-series and vector stores.Read here
Start from the access pattern
There is no best database; there is a best database for a workload. Ask:
- What are the main queries (by key, by range, by search, by relationship)?
- How much data and how fast does it grow? Read/write ratio?
- What consistency and transaction guarantees are needed?
- What latency is required, and where are users?
- What can your team operate?
The families
100%Figure SDA-DDV-05-1 · Map from need to database family · © forcsguy.com
Relational (PostgreSQL, MySQL)
Tables, SQL, joins, constraints, ACID transactions. The default for most business data. PostgreSQL has rich features (JSON, full-text, extensions, many index types); MySQL is widely deployed and simple to operate. They scale vertically very far, and read replicas and sharding extend them. Choose when data is structured, relationships matter and correctness is critical.
Document (MongoDB and similar)
Stores JSON-like documents; flexible schema; related data can be embedded in one document so a single read gets everything. Good for content, catalogues and objects read whole. Watch for duplicated data, joins you must do in code, and weaker multi-document transaction habits.
Key-value (Redis, Memcached; DynamoDB as a key-value/wide hybrid)
Lookup by key at very low latency. Redis adds data structures (hashes, sorted sets, lists, bitmaps), persistence and clustering (see the Redis lesson). Ideal for caches, sessions, counters, rate limits, leaderboards. Not for ad-hoc queries.
Wide-column and partitioned key stores (Cassandra, DynamoDB, HBase)
Data is partitioned by a partition key across many nodes; you design tables around queries. Excellent write throughput, horizontal scale and availability. Cost: limited query flexibility, careful key design (hot partitions), eventual consistency by default. Good for event logs, messaging history, time-ordered user data.
Search engines (Elasticsearch, OpenSearch, Solr)
Build an inverted index (word to documents) for full-text search, relevance scoring, filters and facets. Usually a secondary copy of data from a primary database, kept in sync. Not a system of record: treat it as a derived index that can be rebuilt.
Graph (Neo4j and others)
Stores nodes and relationships and answers questions that follow connections: friends of friends, fraud rings, recommendations, dependency analysis. Where many-hop traversals would need expensive recursive joins in SQL, a graph database is natural.
Time-series (InfluxDB, TimescaleDB, Prometheus)
Optimised for append-heavy, timestamped data with time-range queries, downsampling and retention. Used for metrics, IoT and finance ticks (see the metrics monitoring lesson). Keep tag cardinality low.
Vector databases (and vector indexes in other databases)
Store embeddings (arrays of numbers representing meaning) and find the nearest neighbours, using approximate indexes (graph-based or clustering) for speed. Used for semantic search and retrieval for AI applications. Many general databases now offer vector indexes, which can be enough for moderate scale and avoids another system.
A quick chooser
Need First choice Business data with relationships and transactions Relational Flexible, self-contained records Document Cache, session, counter, leaderboard Redis Massive write volume, simple access by key Wide-column / DynamoDB-style Full-text search and facets Search engine Many-hop relationship queries Graph Metrics and sensor data Time-series Semantic similarity Vector index Analytics on large history Warehouse or lakehouse (see the big data course) Polyglot persistence and its price
Many systems use several stores, each for what it does best: a relational database as the source of truth, a cache, a search index and a metrics store fed from it. The cost is keeping them in sync (change events, outbox pattern, rebuild jobs), more to operate and more failure modes. Add a store only when a measured need justifies it.
SQL versus NoSQL, honestly
"NoSQL" is a family of different designs, not one thing. Relational databases scale further than many assume; NoSQL stores often give up joins and some consistency for scale and flexibility. Decide on requirements, not fashion. If in doubt, start relational and specialise later.
Questions before committing
- Can we model our top ten queries easily?
- What happens at 10 times the data? At a regional failure?
- How do we back up, restore, migrate and monitor it?
- Does the team know it, and is it supported well on our platform?
Real-world reading
Related reading
- Redis UniversityRedis · Redis Ltd.Courses
- RedisRedis · Redis Ltd.GitHub
- Redis DocumentationRedis · Redis Ltd.Documentation
- Build Your Own XCodeCrafters · GitHubGitHub
Show 6 moreShow fewer
- Redis persistenceRedis · Redis Ltd.Documentation
- Moving Food Feed from Redis to Cassandra at ZomatoZomato engineers · ZomatoCase Studies
- Scale with Redis ClusterRedis · Redis Ltd.Documentation
- Improving key expiration in Redis at TwitterTwitter engineers · TwitterCase Studies
- Migrating MySQL from 5.6 to 8.0 at FacebookFacebook engineers · FacebookCase Studies
- Decreasing RAM Usage by 40% Using jemalloc with Python & Celery at ZapierZapier engineers · ZapierCase Studies
Go deeper on this
A path through videos, articles, other case studies and code on the same ideas as Protector: Circuit Breaker for Time Series Databases at Trivago.
Warm upGet the vocabulary first.
Documentation
Druid - Real-time Analytics Database
Apache Druid, a real-time analytics database: the project site and its documentation.
ApacheIntermediate
Books · Free from the author
Site Reliability Engineering
How Google runs production systems: SLOs, error budgets, monitoring and incident response. Free to read online from Google.
GoogleIntermediate
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
GitHub Engineering
Architecture, scaling and incident write-ups from GitHub.
GitHubIntermediate
Papers · Read here
Cassandra: A Decentralized Structured Storage System (paper)
The paper describing Cassandra's design: a Dynamo-style ring and replication with a Bigtable-style data model and storage engine.
FacebookIntermediate
See it in another companyThe same ideas, a different system.
Case Studies · Read here
Roshi: Distributed Storage System for Time-Series Event at SoundCloud
Let’s talk about the stream. The SoundCloud stream represents stuff that’s relevant to you primarily via your social graph, arranged in time order, newest-first. The atom of that data model, an event, is a simple enou...
SoundCloudIntermediate
Case Studies · Read here
Druid at eBay
Large scale event processing from logs to provide monitoring insights
eBayIntermediate
Read the codeSee how it looks when it is real.
GitHub
Build Your Own X
Tutorials for building your own Redis, database, Docker, web server and more, to learn how they work.
GitHubIntermediate
GitHub
Chaos Monkey (source)
The source of Netflix's tool for randomly terminating instances to test resilience.
GitHubIntermediate
Keep learning
Loading community…