Library / Blogs
Elastic Blog
Search, logging and observability engineering with Elasticsearch.
By Elastic engineers · Elastic · Added 2026-10-12
All content belongs to Elastic engineers / Elastic. We only link to it and give credit. Report a problem
Learn this article
About 37 min left. Your work is saved as you go.
What you are about to study
Elastic wrote this to explain how they thought about a problem. You should know the basics: caching, queues and replication.
Ideas you will meet
What we already know about this
Our own lessons on these ideas. Read them here before you start, so it makes sense.
Software Design Essentials · 11 minClean and hexagonal architectureKeep business rules independent of frameworks, databases and the web: the dependency rule, layers, and ports and adapters.Read here
The problem
In many applications, business rules are tangled with framework code, SQL and HTTP details. Then:
- You cannot test a rule without a database and a web server.
- Changing a framework or database means rewriting business logic.
- The code is organised around technology, not around what the system does.
Several architectures (hexagonal, onion, clean) solve this with the same idea: put business rules at the centre and keep details at the edges.
The dependency rule
100%Figure SDA-SDE-06-1 · Clean architecture: dependencies point inwards · © forcsguy.com
Source code dependencies point inwards only. Entities know nothing about use cases; use cases know nothing about the web or the database. Outer layers depend on inner ones, never the reverse.
Layer Contains Knows about Entities Core business objects and rules that would exist whatever the technology Nothing else Use cases Application-specific actions ("place order", "cancel subscription") that coordinate entities Entities and the ports they define Interface adapters Controllers, presenters, repositories' implementations, mappers Use cases Frameworks and drivers The web framework, database, message queue, UI Adapters Before: logic tangled in the controller
100%After: business rules in the middle
100%What changed
- Business rules can be tested without a web server or database
- The database or framework can be replaced at the edge
- There are more files and layers to maintain
Ports and adapters (hexagonal)
The application is the hexagon. It talks to the outside only through ports: interfaces it owns. Adapters translate between the outside world and the ports.
- Driving (inbound) ports: how the world calls the application (
PlaceOrder). Adapters: REST controller, CLI, message listener, test. - Driven (outbound) ports: what the application needs (
OrderRepository,PaymentGateway,Clock). Adapters: SQL implementation, payment provider client, fake for tests.
// Port owned by the application interface OrderRepository { save(order: Order): Promise<void>; byId(id: string): Promise<Order | null> } interface PaymentGateway { charge(cents: number, token: string): Promise<boolean> } // Use case: pure application logic class PlaceOrder { constructor(private orders: OrderRepository, private payments: PaymentGateway) {} async run(input: { items: Item[]; token: string }) { const order = Order.create(input.items); // entity enforces rules if (!(await this.payments.charge(order.totalCents, input.token))) throw new Error("Payment failed"); await this.orders.save(order); return order.id; } } // Adapters live outside, implementing the ports class SqlOrderRepository implements OrderRepository { /* uses a database */ } class StripeGateway implements PaymentGateway { /* calls the provider */ } // Composition root wires everything together at start-up const placeOrder = new PlaceOrder(new SqlOrderRepository(db), new StripeGateway(key));This is the dependency inversion principle from SOLID applied to a whole system.
Benefits
- Testable: run use cases with in-memory fakes, fast and without infrastructure.
- Replaceable details: change the database, queue or web framework by writing an adapter.
- Focus on the domain: the central code reads like the business process.
- Deferred decisions: you can postpone choosing a database.
Costs and cautions
- More structure: interfaces, mappers and wiring add code. For a small CRUD app it can be overkill.
- Mapping between layers (domain objects, database rows, API shapes) is repetitive; do it deliberately and avoid leaking database entities into the API.
- Do not create layers "because the diagram says so". Add a boundary where a real change or testing need exists.
- It is about dependencies, not folder names: a good folder layout helps but does not guarantee the rule is followed. Enforce it with tests or lint rules.
Related ideas
- Domain-driven design supplies the language for the centre of the hexagon (next lesson).
- Microservices are a deployment choice; each service can use this internal structure.
- Composition root: one place, at start-up, where concrete classes are chosen and injected.
Real-world reading
Related reading
- Cockroach Labs BlogCockroach Labs engineers · Cockroach LabsBlogs
- Fivetran BlogFivetran engineers · FivetranBlogs
- ClickHouse BlogClickHouse engineers · ClickHouseBlogs
- InfluxData BlogInfluxData engineers · InfluxDataBlogs
Show 6 moreShow fewer
- Elastic BlogElastic engineers · ElasticBlogs
- AWS Database BlogAWS database teams · Amazon Web ServicesBlogs
- How SQLite WorksSQLite team · SQLiteDocumentation
- AWS Big Data BlogAmazon Web Services engineers · Amazon Web ServicesBlogs
- Viget Engineering BlogViget engineers · VigetBlogs
- Meituan Blog (Chinese)Meituan engineers · MeituanBlogs
Real-World Systems · 11 minDesign an email system (Gmail)How a message travels between providers over SMTP, how spam and spoofing are filtered, and how a mailbox is stored and searched at huge scale.Read here
The problem
An email system receives and sends messages for billions of mailboxes, stores them for years, keeps spam out, and lets users search and organise (labels, threads).
Requirements
- Reliable delivery: a message is never silently lost.
- Interoperability with every other mail provider.
- Spam, phishing and virus filtering.
- Large attachments, fast search, and strong privacy.
How email moves between providers
Email uses SMTP to send between servers. The key ideas:
- MX records in DNS tell you which servers accept mail for a domain.
- Delivery is store-and-forward: a server accepts a message, persists it, and passes it on, retrying if the next hop is down.
- Clients usually read mail through IMAP (or POP3) or through a provider's web and mobile API.
100%Figure SDA-RWS-02-1 · Servers talk SMTP to each other; readers fetch with IMAP or POP · © forcsguy.com
Image: Tim Sheerman-Chase · CC BY 2.0 · Source · Wikimedia Commons: Old Post Sorting Office, PortsmouthArchitecture
100%Figure SDA-RWS-02-2 · Email delivery architecture · © forcsguy.com
Sending
- The client sends the message to its provider's submission server (with authentication).
- The message is saved and put on an outbound queue, so slow recipients never slow the sender.
- A worker finds the recipient domain's MX hosts, connects with SMTP, and delivers. The worker signs the message (DKIM).
- Temporary failures are retried with backoff for days; permanent failures generate a bounce message.
Receiving
- The incoming server accepts the connection and verifies the sender with SPF, DKIM and DMARC.
- Filters score the message for spam, phishing and malware (rules, reputation, and machine learning).
- The message is written to the user's mailbox: metadata in a scalable database, bodies and attachments in object storage, and an entry in the search index.
- Clients are told (push, IMAP IDLE) that new mail arrived.
100%Figure SDA-RWS-02-3 · Where a received message is stored and how readers are told · © forcsguy.com
Fighting spam and spoofing
Mechanism What it does SPF The domain lists which servers may send for it DKIM The sender signs the message; receivers check the signature DMARC The domain says what to do when SPF or DKIM fail, and gets reports Reputation Track sending behaviour per IP and domain; rate-limit new senders Content filters Spam classifiers, link and attachment scanning Storage design
- A mailbox is append-heavy and read by recent items. Partition by user id, so one user's mail sits together.
- Keep metadata (labels, flags, thread id, snippet) separate from large bodies and attachments.
- Threads group messages by headers (References, In-Reply-To) and subject.
- Search uses an inverted index per user, updated as mail arrives.
- Deduplicate identical large attachments with content hashes.
- Keep multiple replicas and backups: email is people's records.
Scale and reliability
- Queues absorb bursts, for example newsletter sends.
- Rate-limit outgoing mail per account to stop compromised accounts spamming.
- Spread incoming servers across regions; MX records can list several with priorities.
- Privacy: encrypt in transit (TLS between servers) and at rest, and control internal access carefully.
Real-world reading
Related reading
- Marc Brooker's BlogMarc Brooker · brooker.co.zaBlogs
- NATS ServerNATS · CNCF / NATSGitHub
- Confluent BlogConfluent engineers · ConfluentBlogs
- Elastic BlogElastic engineers · ElasticBlogs
Show 6 moreShow fewer
- Moving Core Business Search to Elasticsearch at YelpYelp engineers · YelpCase Studies
- Domain-Driven Design ReferenceEric Evans · Domain LanguageBooks
- Moderating Promotional Spam and Inappropriate Content in Photos at Scale at YelpScale at Yelp engineers · Scale at YelpCase Studies
- Google Research BlogGoogle researchers · GoogleBlogs
- Khan Academy Engineering BlogKhan Academy engineers · Khan AcademyBlogs
- Salesforce BlogSalesforce engineers · SalesforceBlogs
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
Go deeper on this
A path through videos, articles, other case studies and code on the same ideas as Elastic Blog.
Warm upGet the vocabulary first.
Documentation
Elasticsearch Guide
The reference for indexing, searching and scaling Elasticsearch.
ElasticIntermediate
Books · Free from the author
Mining of Massive Datasets
Large-scale data processing: MapReduce, similarity search, recommendation and streams. The authors offer the whole book as a free download.
Stanford UniversityAdvanced
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
eBay Tech
Search, marketplace and platform engineering posts from eBay.
eBayIntermediate
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
ELK (Elasticsearch, Logstash, Kibana) Stack
As part of the widespread movement towards open source software, the ELK Stack has become the most common log management platform in the world.
LogzIntermediate
Case Studies · Read here
Fast Order Search using Data Pipeline and Elasticsearch at Yelp
Fast Order Search Using Yelp’s Data Pipeline and Elasticsearch Dmitriy Kunitskiy, Software Engineer Jun 1, 2018 Since its inception in 2013, Yelp has grown its transactions platform to tens of...
YelpIntermediate
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
CockroachDB
A distributed SQL database built on ranges, Raft and MVCC.
GitHubAdvanced
Keep learning
Loading community…