What Is Primary-Replica Synchronization in Elasticsearch?
A complete, plain-English guide to how Elasticsearch keeps several copies of every shard identical: how each write travels from the primary to its replicas, how the cluster knows which copies are trustworthy, and what happens when a copy falls behind, fails, or is promoted.
Imagine a teacher dictating important notes to a class, while two assistants sit in the back and copy everything word for word. The teacher does not say “done” until both assistants have written the line down. If one assistant falls asleep, the teacher tells the principal, who crosses that assistant off the list of reliable note-takers. If the teacher faints, the principal picks one of the reliable assistants to take over, and the new teacher first checks that everybody has the same lines before continuing. At the end of the day, every reliable copy of the notes is exactly the same, even though people fainted and fell asleep along the way.
That classroom is the heart of primary-replica synchronization in Elasticsearch. Every shard of an index has one primary copy and, usually, one or more replica copies on other machines. Writes go to the primary first and are copied to the replicas. The cluster keeps careful books about which copies are fully up to date, so that an acknowledged write is never lost, even when machines crash or networks break. This guide starts from zero, opens the machinery step by step, and ends with the numbers, the failure stories, and the habits that keep copies healthy in production.
1What Primary-Replica Synchronization Actually Is
Three plain ideas, put together: copies, order, and trust. Once each is clear, the rest follows naturally.
Elasticsearch stores documents in indexes, and every index is cut into pieces called shards. Each shard is a small, complete search engine of its own. To protect the data, and to spread out reading work, Elasticsearch keeps more than one copy of each shard. The main copy is called the primary. The extra copies are called replicas. All the copies of one shard together are called its replication group, and they live on different nodes, so that the loss of one machine does not lose the data.
Copies are only useful if they agree. If the primary has a document and the replica does not, then a search that happens to hit the replica will miss it, and if the primary then fails, the document is gone. Synchronization is the set of rules and mechanisms that keep the copies identical: how a change is sent from the primary to the replicas, in what order, how the replicas confirm it, how a replica that missed changes catches up, and how the cluster decides which copies can be trusted.
The third idea is trust. It is not enough to copy changes. The cluster must also know which copies are fully up to date, because that knowledge decides what is safe to do when something breaks. A copy that is known to hold every acknowledged change may be promoted to primary. A copy that missed changes must catch up first. Elasticsearch keeps this knowledge in the cluster state, in a list called the in-sync set.
Think of three friends keeping the same shopping list on three phones. The rule is that a new item counts as added only when all three phones show it. If one friend’s phone runs out of battery, the group agrees to cross that phone off the “reliable” list until it is charged and updated. The list of reliable phones is the in-sync set.
What it is not
Three things sound similar but are different. First, a snapshot is a backup stored in an outside repository at a point in time. It is not a live copy. Second, cross-cluster replication is a separate feature that copies indexes from one cluster to another, asynchronously, and is normally a paid feature. Third, reindexing copies documents from one index into another by reading and writing them again. Primary-replica synchronization is none of these. It is the continuous, automatic, per-shard copying that happens inside one index, within one cluster, on every single write.
This guide describes the standard model used by self-managed Elasticsearch and the usual hosted deployments, where each replica indexes the operations itself. Some newer cloud-native deployment styles separate storage from compute and replicate in different ways. The ideas of ordering and trust remain useful there, but the details differ.
The one-sentence version
If you remember one line from this chapter, make it this: primary-replica synchronization is the process by which the primary shard assigns every write a sequence number, forwards it to all in-sync replicas, waits for their confirmation, and tells the master to drop any copy that fails, so that every acknowledged write is present on every trusted copy.
2Why It Exists: Machines Fail, Data Must Not
Every design has a problem behind it. Here the problem is that hardware breaks and users still expect their data to be there.
In a cluster with dozens or hundreds of machines, something is always failing somewhere: a disk, a power supply, a network cable, a software bug, a planned restart. If each shard existed in only one place, every failure would make part of the data unavailable, and some failures would destroy it. Replication answers this with three benefits at once.
- Availability. If the machine holding a primary fails, a replica on another machine can take over within seconds, and users keep reading and writing.
- Durability. An acknowledged write exists on more than one machine. Losing any single machine does not lose it.
- Read capacity. Replicas can answer searches and lookups, so that read traffic is spread across more machines, and popular data does not overload a single node.
But copying has its own difficulties, and these are what synchronization is about. Copies can receive changes at different times. Network messages can arrive out of order. A replica can be slow, or disconnected, or restarted in the middle of a change. A primary can crash halfway through sending a change, so that some replicas have it and others do not. Each difficulty needs a clear rule, or the copies would slowly drift apart, and nobody would know which was right.
Think of a bank that keeps three copies of every ledger in three buildings. It is not enough to make copies once a year. Each new entry must reach all three ledgers in the same order, and if one building loses power, the bank must know exactly which ledgers are complete before it decides which one to trust.
A short history
Early days: copy and hope
Early versions copied writes to replicas and, after failures, brought replicas up to date by copying whole files from the primary. It worked, but recovery could be slow, and reasoning about exactly which copy had which changes was difficult.
Version 5: tracking the in-sync copies
The cluster began to record which copies were known to be in sync, and to promote only those. This closed a class of bugs where an out-of-date copy could become primary and silently lose data.
Version 6: sequence numbers
Every operation received a sequence number and every primary election a primary term. Checkpoints built on them let the system know exactly what each copy had processed. This also enabled the resync that follows a promotion.
Version 7: history retention
Soft deletes and retention leases allowed the primary to keep just enough history so that a replica that was briefly away could catch up by replaying missing operations, not by copying files. Recovery of a restarted node became much faster.
Today: safe by design
The model is a well-defined protocol: numbered operations, in-sync tracking, checkpoints, and operation-based recovery. The operator’s job is mostly to size, place, and monitor it.
The exact release for each step is worth double-checking in the release notes of your version. The direction of travel is what matters: from “copy and hope” toward “number every operation and prove every copy.”
Why not simply copy files?
One could imagine replicas that just copy the primary’s files every few seconds. Some systems work that way, and it has real advantages, such as saving the replica from repeating the indexing work. But file copying makes it harder to acknowledge a write as durable on several machines at once, and it delays the moment a write appears on replicas. The standard Elasticsearch model instead sends each operation to the replicas, which repeat the indexing work and keep their own transaction logs. That choice gives strong per-write guarantees, at the price of extra CPU on every copy.
3Core Concepts You Need First
A dozen words explain nearly everything about synchronization. Learn them here, and later chapters will read like common sense.
Primary shard
The copy that receives every write first. It decides the order of operations and checks for conflicts.
Replica shard
A copy that repeats the operations chosen by the primary. It never decides order on its own.
Replication group
The primary and all of its replicas for one shard. Each group is synchronized separately from other groups.
In-sync set
The list, kept in the cluster state, of copies known to hold every acknowledged write. Only these may become primary.
Sequence number
A counter, assigned by the primary to each operation, that goes up by one each time. It fixes the order of history.
Primary term
A counter that goes up each time a new primary is chosen. It lets copies ignore commands from an old primary.
Local checkpoint
For each copy, the highest sequence number up to which it has processed every operation with no gaps.
Global checkpoint
The highest sequence number that every in-sync copy is known to have processed. Everything at or below it is safe.
Translog
A running diary on disk of recent operations. Every copy keeps its own, so it can recover after a crash.
Soft deletes and retention leases
Mechanisms that keep a window of past operations available, so a copy that was away can replay what it missed.
Peer recovery
Bringing a copy up to date from another copy, after a restart, a move, or the creation of a new replica.
Resync
The step after a promotion, in which the new primary aligns the other replicas with its own history.
Who decides what
Three parties share the work. The primary decides the order of operations and their outcome, for example whether a conflicting update is accepted. The replicas obey: they repeat what the primary decided. The master node keeps the official list of which copies exist, where they are, and which of them are in sync. The primary may propose changes to that list, such as “drop this replica,” but only the master can make them official.
In a courtroom, the judge (primary) decides each ruling. The clerks (replicas) write down exactly what the judge ruled, in the same order. The chief justice (master) keeps the list of which clerks’ records are complete. If a clerk misses a ruling, the judge reports it, and the chief justice crosses that clerk off the list of reliable records.
Why order matters so much
Suppose two operations touch the same document: first “set price to 10,” then “set price to 12.” If a replica applied them in the wrong order, it would end with price 10, while the primary has 12. The copies would disagree for as long as nobody touched that document again. Network messages can arrive out of order, so the arrival order cannot be trusted. Sequence numbers solve this. Each operation carries its number, and the replica uses it to decide which of two conflicting operations is newer, no matter which arrived first.
Why “in sync” is stronger than “alive”
A replica can be alive and yet not in sync. It might have been offline for ten minutes, missing thousands of operations. It is running, and it holds old data, but it is not trustworthy. Elasticsearch therefore separates the two ideas. A copy joins the in-sync set only when it has caught up, and it is removed from that set the moment it is known to have missed something. Reads may be served only by started copies, and promotions use only the in-sync ones.
A green cluster color does not mean every replica is perfectly current at every instant. It means all copies are assigned and started. Tiny lags are normal. What matters is that every acknowledged write is on all in-sync copies.
Quick glossary
| Word | Plain meaning |
|---|---|
| Acknowledgment | The success answer sent to the client after the write has been safely handled. |
| Idempotent | Safe to repeat: doing it twice gives the same result as doing it once. |
| Stale copy | A copy that has missed acknowledged operations and must not be trusted or promoted. |
| Zombie primary | An old primary that has been replaced but has not yet realized it, for example after a network split. |
| Refresh | The moment when recently indexed documents become visible to searches. |
| Flush | Saving segments safely to disk and trimming old translog. |
| Segment | A small, sealed, read-only set of files inside a shard. |
| Optimistic concurrency | Checking, at write time, that the document has not changed since you read it. |
4Architecture and Components
Where do the copies live, who talks to whom, and which parts of the cluster take part in keeping them together?
Every shard has a replication group spread over different nodes. The rules of placement guarantee that two copies of the same shard never live on the same node, because one crash would then destroy both. When zone awareness is configured, copies are also spread across zones or racks. The master node keeps the list of copies and marks which are in sync. The primary talks directly to its replicas over the network to forward operations.
flowchart TB
Client["Client sends a write request"] --> Coord["Coordinating node: finds the shard using the document id or routing value"]
Coord --> P["Primary shard copy on Node A"]
subgraph Group["Replication group of one shard"]
P
R1["Replica copy on Node B"]
R2["Replica copy on Node C"]
end
P -->|forwards each operation| R1
P -->|forwards each operation| R2
M["Master node: cluster state with the in-sync copy list"] -.->|tracks which copies are in sync| Group
Read the picture from top to bottom. A client sends a write to any node, which acts as coordinating node. It works out which shard owns the document and sends the operation to the node that holds that shard’s primary. The primary executes it and forwards it to the replicas on other nodes. The dotted line shows that the master does not carry the data. It only keeps the official record of who is in the group and who is in sync.
The main components
Coordinating node
Receives the request, decides which shard should handle each document, and forwards work to the right primaries.
Primary shard
Runs the operation first, assigns its sequence number and term, and drives replication to the replicas.
Replica shard
Applies each operation exactly as the primary decided, keeps its own translog, and reports its progress.
Replication tracker
Inside the primary, it keeps the checkpoint of every copy and computes the global checkpoint.
Cluster state
Holds the routing table, the primary terms, and the in-sync sets. It is the official truth about the group.
Recovery service
Moves data from a source copy to a target copy when a replica needs to catch up or a new one is built.
Translog and history
On every copy, the record of recent operations that allows recovery after a crash or after an absence.
Allocation service
Chooses which node holds which copy, avoiding the same node twice and honoring zone rules.
One synchronization per shard
An index with five primary shards and one replica each has five separate replication groups. Each is synchronized on its own. A slow replica in one group does not slow the others. This is why the cluster can scale writes by adding shards: each new group adds capacity, and no group needs to talk to any other.
A newspaper has several sections, each with its own editor and two proofreaders. The sports editor and her proofreaders work together, while the business section works separately. If one proofreader is slow in sports, business is not affected.
Walking one write through the machine
The client sends the write
A single document or a bulk request reaches any node.
The coordinating node routes it
It finds the target shard and forwards the operation to the node holding that shard’s primary.
The primary validates and numbers it
It checks conflicts and assigns the next sequence number and its primary term.
The primary executes it locally
It indexes the document and records the operation in its translog.
The operation is sent to the replicas
All in-sync replicas receive it in parallel, execute it, and record it in their own translogs.
Replicas confirm to the primary
The confirmations carry each replica’s progress, which updates the checkpoints.
The client gets its answer
The primary responds, and the response says how many copies were involved and how many succeeded.
Every write does its work once per copy and waits for the slowest in-sync replica. So write speed is set by the primary and by the slowest in-sync copy, not by the average of the group. One struggling replica can slow every write to its shard, until the cluster removes it from the in-sync set.
5The Write Path, Step by Step
Now we open the box and follow a single write from the moment it arrives to the moment it is acknowledged.
flowchart TD
A["Index or bulk request arrives at the coordinating node"] --> B["Routed to the primary shard"]
B --> C["Primary validates the operation and checks versions"]
C --> D["Primary assigns sequence number and primary term"]
D --> E["Primary indexes locally and writes its translog"]
E --> F["Primary sends the operation to all in-sync replicas in parallel"]
F --> G["Each replica indexes and writes its own translog"]
G --> H{"Did every in-sync replica confirm?"}
H -- Yes --> I["Primary acknowledges success to the client"]
H -- No --> J["Primary asks the master to drop the failed copy from the in-sync set"]
J --> I
Step one: routing to the right shard
The coordinating node decides which shard owns a document by taking a hash of the routing value, which is by default the document’s identifier, and reducing it to a shard number using the count of primary shards. Because this depends on the number of primary shards, that number cannot be changed on an existing index without rebuilding it. The same identifier always leads to the same shard, so updates and deletes find the right home.
Step two: the primary validates
The primary is the only copy that makes decisions. It checks that the operation is well formed. If the operation carries a condition, such as “only update if the document is still at version 7,” it checks that condition against the current state of the document. If the check fails, the operation is rejected here, and no replica ever sees it. If it passes, the primary decides the outcome, for example whether the operation creates a new document or replaces an old one.
Step three: numbering
The primary assigns the operation a sequence number, the next number in an unbroken series, and stamps it with the current primary term. From this moment, the operation is a fixed piece of history: replicas will apply it as it is, with this number, and no replica may renumber it.
Think of a court reporter numbering each page of a transcript in order. Page 100 always comes after page 99, even if someone hands page 100 to a reader before page 99. The page number, not the order of delivery, decides where it belongs.
Step four: local execution
The primary indexes the document into its in-memory buffer and appends the operation to its translog. By default, the translog is synced to disk before the request finishes, so that a crash cannot lose an operation that has been acknowledged. The primary does this before, or while, it forwards the operation, and in the standard flow it does not wait to hear from replicas before doing its own work.
Step five: forwarding in parallel
The primary sends the operation to every copy in the group that is either in sync or currently recovering, all at the same time, not one after the other. For a bulk request, it sends the whole batch destined for that shard as one message, already carrying the sequence numbers. Sending in parallel means that the time cost of having three replicas is not three times the time cost of having one. It is closer to the time of the slowest one.
Step six: replicas execute
Each replica receives the operation with its sequence number and primary term. It first checks the term: if the term is older than the newest term the replica knows about, the operation comes from an old primary and is refused. Otherwise it applies the operation to its own index and translog. If operations arrive out of order, the replica uses the sequence numbers to make sure that an older operation never overwrites a newer one.
Step seven: acknowledgment
When all in-sync replicas have confirmed, the primary responds to the client. The response contains a small summary of the shards involved: how many copies were involved, how many succeeded, and how many failed. If a replica failed, the primary has already reported this to the master, which removes that copy from the in-sync set before the acknowledgment is sent.
| Stage | Who acts | What is guaranteed after it |
|---|---|---|
| Routing | Coordinating node | The operation reaches the shard’s primary |
| Validation | Primary | Conflicts are decided in one place |
| Numbering | Primary | The operation has a fixed place in history |
| Local execution | Primary | The primary holds the change durably |
| Parallel forwarding | Primary to replicas | Every in-sync replica receives the same numbered operation |
| Replica execution | Replicas | Every in-sync replica holds the change durably |
| Acknowledgment | Primary | The client knows the change is on all in-sync copies |
What the write does not wait for
Acknowledgment does not mean that the document is yet visible to searches. Visibility depends on the refresh, which happens separately on every copy, on its own schedule. A document can be safely stored on all copies and still not appear in search results for up to a refresh interval. The acknowledgment is a promise about safety, not about search visibility. Chapter 11 explores the consequences.
Many people assume that “acknowledged” means “searchable.” It does not. If you must see a document in search right after writing it, use the refresh options of the write request, at a cost, or design the application so that it does not need to.
6Sequence Numbers, Primary Terms, and Checkpoints
These three ideas are the bookkeeping that makes everything else safe. Once you understand them, failures stop feeling mysterious.
Sequence numbers: a fixed order for history
Every operation that changes a shard, whether it adds, replaces, or deletes a document, receives a sequence number from the primary. The numbers form an unbroken series: 0, 1, 2, 3, and so on. Once assigned, a number is never changed and never reused within the same shard. This gives each shard a single, agreed history, like a numbered list of everything that ever happened.
Primary terms: which leader gave the order
Each time a new primary is chosen for a shard, a counter called the primary term goes up by one. Every operation carries the term of the primary that issued it. Replicas remember the highest term they have seen, and refuse any command carrying a lower one. This is how the group protects itself from a zombie primary: an old primary that was cut off by a network problem, has been replaced, and does not yet know it. Its commands carry an old term, and every replica that has heard about the new primary ignores them.
Think of a country with successive governments, each numbered. A decree signed by “Government 7” is worthless once Government 8 has taken over, even if a messenger delivers it late. The number of the government, the term, tells everyone which decrees are still valid.
Local checkpoints: how far each copy has got
Each copy tracks its own local checkpoint. This is the highest sequence number such that the copy has processed every operation from the beginning up to that number, with no gaps. If a copy has processed operations 0 to 97 and 99 but not 98, its local checkpoint is 97, not 99, because a gap is still open. The local checkpoint moves forward only as gaps are filled.
The global checkpoint: what is safe everywhere
The primary collects the local checkpoints of all in-sync copies. The lowest of them is the global checkpoint. It is the number up to which every in-sync copy is known to have processed every operation. Everything at or below the global checkpoint is safe: it exists on all trusted copies, and it will never be rolled back.
flowchart LR
P["Primary: local checkpoint 105"] --> G(("Lowest local checkpoint of all in-sync copies"))
R1["Replica 1: local checkpoint 103"] --> G
R2["Replica 2: local checkpoint 104"] --> G
G --> V["Global checkpoint 103: all operations up to 103 are safe on every in-sync copy"]
In the picture, the primary has processed everything up to operation 105, one replica up to 103, and another up to 104. The global checkpoint is 103. Operations 104 and 105 are probably on most copies, but not yet proven to be on all of them, so they are not yet counted as globally safe.
Three students copy a long text from the blackboard. One is on line 105, another on line 103, and a third on line 104. The teacher can only say “everyone has finished up to line 103.” That line, the slowest student’s position, is the global checkpoint.
How checkpoints travel
Replicas tell the primary their local checkpoint in every confirmation. The primary recomputes the global checkpoint and sends it back to the replicas, attached to later replication messages. When no writes are flowing, a background task sends the latest global checkpoint to replicas at a regular interval, thirty seconds by default, so that quiet shards still learn the news. The global checkpoint is therefore always known to be safe on a copy, but it might lag slightly behind the primary’s own view.
What checkpoints are used for
Fast catch-up
A copy that was away knows its own checkpoint. The primary can send only the operations after it, instead of copying files.
Safe takeover
When a replica becomes primary, everything up to the global checkpoint is known to be safe, and only operations above it need to be re-aligned.
Translog trimming
A copy can discard translog entries below the global checkpoint that are safely stored in committed segments.
Filling gaps
If numbers are missing, checkpoints show it, so the missing operations, or no-ops that stand for them, can be supplied.
Rollback boundary
On restart, a copy can safely go back to a commit at or below the global checkpoint and replay from there.
Monitoring
Comparing checkpoints across copies shows how far behind a replica is.
Handling out-of-order arrival
Networks do not promise order. A replica might receive operation 51 before operation 50. If both touch the same document, the replica must not let the older operation overwrite the newer one. It compares sequence numbers: when an older operation arrives after a newer one for the same document, the replica recognizes it as outdated. It records it in its history so that its checkpoint can advance, but it does not let it replace the newer state of the document. This gives every replica the same final result, whatever order the messages arrive in.
Gaps and no-ops
Sometimes a sequence number is assigned to an operation that then fails on the primary, for example because of a problem discovered after numbering. If nothing were done, that number would remain a permanent gap, and checkpoints could never move past it. To avoid this, the primary sends a special operation called a no-op for that number. It changes nothing, but it fills the gap, so that the series of numbers stays unbroken and checkpoints can advance.
The shard-level statistics report, for each copy, the highest sequence number seen, the local checkpoint, and the global checkpoint. Comparing them is the most direct way to see how far each replica lags behind the primary.
7The In-Sync Set and What Happens When a Replica Fails
A replica can fail in many ways: it can crash, stall, lose its network, or hit an error. The rule that governs them all is short and strict.
The rule
A write may be acknowledged only if every copy in the in-sync set has confirmed it, or has been removed from the in-sync set. There is no third option. A copy that could not confirm is never silently left in the set. This single rule means that when the client hears “success,” any copy still in the set has the write, and any copy without the write has been officially marked as untrustworthy.
flowchart TD
A["Replica fails to apply an operation or stops responding"] --> B["Primary reports the failed copy to the master"]
B --> C{"Does the master accept the report for this primary term?"}
C -- Yes --> D["Master removes the copy from the in-sync set in the cluster state"]
D --> E["Primary may now acknowledge the write"]
E --> F["Master arranges for a new replica to be built"]
C -- No --> G["Primary is stale: it steps down and does not acknowledge"]
Step by step through a replica failure
The primary sends an operation and gets no good answer
The replica returns an error, or the request times out, or the connection breaks.
The primary reports the failure to the master
It says “copy X did not confirm operation N,” including the primary term under which it acts.
The master checks the report
If the primary’s term is current, the report is accepted. If the term is old, the report is rejected, which tells the primary that it has been replaced.
The master updates the cluster state
The copy is removed from the in-sync set, and the change is published to the cluster as a new state.
The primary acknowledges the write
The response tells the client that fewer copies succeeded than were planned, which shows up in the summary of shards.
The cluster repairs itself
The allocation service schedules a new replica, on the same node after a delay if it is expected back, or on another node if not.
A teacher dictates a line and notices that one assistant did not write it down. Before announcing “done,” she must send a note to the principal, who officially strikes that assistant off the list of reliable note-takers. Only after the principal has recorded this can the teacher say “done,” because from then on nobody will trust that assistant’s notes until she has caught up.
Why the master must be involved
The primary could simply stop sending operations to a failed replica. But the cluster, and above all the master, would still think that copy was current, and might later promote it, or route reads to it, as if nothing had happened. Making the removal official through the master closes this gap. It also serves as a safety check on the primary itself: if the master rejects the primary’s report because the term is outdated, the primary knows that it is a zombie and must not acknowledge anything.
What if the primary cannot reach the master?
Suppose a network problem cuts the primary off from the master, while some replicas are on the other side. The primary cannot make its report, so it cannot complete any write that involves a failed replica, and it will not acknowledge. Meanwhile, the master, on the healthy side, may already have chosen a new primary from the replicas it can reach, with a higher term. When the network heals, the old primary learns of the higher term and steps down. No acknowledged write was lost, because none was acknowledged in isolation.
flowchart LR
subgraph Isolated["Cut-off side"]
OP["Old primary: cannot reach the master"]
end
subgraph Healthy["Connected side"]
M["Master"]
NR["Replica promoted to new primary with a higher term"]
end
OP -. "network partition" .- M
M --> NR
OP --> X["Old primary cannot acknowledge writes and later steps down"]
What the client sees
The write response carries a small summary: the total number of shard copies involved, the number that succeeded, and the number that failed. Normally, the successful count equals the total. If a replica was dropped, the numbers differ, and the client can see that the write, though acknowledged, was made with reduced protection. Well-built monitoring watches for such answers, since they are an early sign of trouble.
How many copies must be available to start a write
By default, a write proceeds as long as the primary is active. A setting, which can be given per request or per index, lets you insist that a certain number of copies be active before the write even begins. For instance, requiring two active copies prevents writes from being accepted when only the primary is alive. This is a check made before the write starts, not a guarantee made after it. A copy that was active at the start can still fail during the write, and the in-sync rule then handles it as described.
The active-copies setting is often misread as “write to N copies.” It is only a pre-check. The real durability rule is the in-sync rule: all in-sync copies confirm, or the failing copy is removed.
When all replicas are gone
If every replica has been dropped, the primary continues alone, and the write is safe only on one machine. The cluster health shows yellow. The data is available but exposed to the failure of that one node. This is the moment when speed of repair matters, and why alerts on yellow status that lasts too long are so important.
8Primary Failure, Promotion, and the Primary-Replica Resync
The hardest day for a replication group is the day the primary dies. Here is exactly how the group stays correct.
flowchart LR
F1["Primary node fails or is cut off"] --> F2["Master detects the loss"]
F2 --> F3["Master picks an in-sync replica as the new primary"]
F3 --> F4["Primary term increases by one"]
F4 --> F5["New primary resyncs the other replicas above the global checkpoint"]
F5 --> F6["Master rebuilds the missing replica copies"]
F6 --> F7["The group is fully in sync again"]
Step one: detection
The master finds out that the node holding the primary is gone, through the regular health checks between nodes. It removes the node from the cluster state. Until a new primary is chosen, that shard cannot accept writes, though replicas can still serve reads.
Step two: choosing the successor
The master looks at the in-sync set and picks one of its members as the new primary. It must be in the set, because only those copies are known to hold every acknowledged write. The master also raises the primary term by one, and records both in the cluster state. Then it publishes the new state, and the chosen replica learns that it is now the primary.
Step three: the new primary starts work
The new primary knows the global checkpoint, which says that everything up to that number is safe on all in-sync copies. But above that number, things are uncertain. Operations that were in flight when the old primary died might have reached some replicas and not others. Some of them were never acknowledged, so the client may have received an error or a timeout. The other replicas might hold a different set of these uncertain operations than the new primary does.
Step four: the resync
To align everybody, the new primary performs a primary-replica resync. It takes the operations it holds above the global checkpoint, from its translog, and sends them to all the other replicas, stamped with the new term. It also sends no-ops to fill any gaps in the numbering. The replicas apply what they lack, and they discard any unconfirmed operations from the old term that do not match the new primary’s history. After the resync, all in-sync copies share exactly the same history, up to the new primary’s latest operation.
The teacher faints while dictating page 50. The principal picks the assistant with the most complete notes as the new teacher. She then reads aloud everything she has after the last page that everybody confirmed, page 45, so that all assistants end up with the same pages 46 to 50, and no assistant has an extra page that the new teacher lacks.
What happens to writes that were in flight
A write that was in flight when the primary died has an unknown outcome. It may have been applied on the new primary, in which case the resync will spread it to every copy, and it will survive. It may not have reached any surviving copy, in which case it is lost, and the client received no acknowledgment. What can never happen is that a write is acknowledged and then lost, because acknowledgment required all in-sync copies. This is why clients that retry after a timeout should expect that a write might be applied twice, and should use identifiers that make repeating them harmless.
Step five: rebuilding the missing copy
With the old primary gone, the group has one copy fewer than planned. The allocation service schedules a new replica. If the failed node is expected to return soon, the master waits, by default about a minute, before starting to build a replacement elsewhere. This avoids wasting effort on copying large amounts of data when the node was only restarting. If the node returns in time, its data is reused, and only the missing operations are replayed.
When no in-sync copy survives
If every copy in the in-sync set is lost, the cluster does not promote a stale copy. It leaves the shard unassigned, and the health turns red, because a stale copy might be missing acknowledged writes. An operator can, as an explicit and dangerous decision, tell the cluster to use a stale copy and accept the data loss. That decision should be made with full understanding, and ideally after trying to bring the lost nodes back, because they may hold the missing writes.
Forcing a stale copy to become primary can bring an index back to life, but it discards every write that the stale copy missed, silently and permanently. Use it only as a last resort, after other options are exhausted, and record what was lost.
The whole sequence in a table
| Moment | What the cluster knows | What it does |
|---|---|---|
| Primary fails | The node is gone | Shard cannot accept writes for a moment |
| Promotion | Which copies are in sync | Picks one, raises the term, publishes the state |
| Resync | The global checkpoint | Sends operations above it to align all replicas |
| Normal operation | New primary and replicas share history | Writes resume, with fewer copies |
| Repair | One copy is missing | Builds a new replica after a delay |
| Full health | All copies are in sync | Cluster returns to green |
9Peer Recovery: Bringing a Replica Up to Date
A replica that was away, or is brand new, must catch up before it can rejoin the trusted set. The process is called peer recovery.
When recovery happens
- A node restarts and its replicas must catch up on what they missed.
- A new replica is created, for example when you increase the number of replicas.
- A shard is moved to another node for balance, maintenance, or disk space.
- A replica was dropped from the in-sync set after a failure and now returns.
flowchart TD
S["Replica needs recovery"] --> Q{"Does the primary still hold history from the replica's last safe point?"}
Q -- Yes --> O["Operation-based recovery: replay only the missing operations"]
Q -- No --> F["File-based recovery: copy missing segment files first"]
F --> O2["Then replay the operations that arrived during the copy"]
O --> D["Replica catches up and is marked in sync"]
O2 --> D
Operation-based recovery: the fast path
If the replica was only away briefly, its data is still on disk, and it knows its own local checkpoint. The primary still holds the history of operations after that point. Then the recovery only needs to send those missing operations, in order, and the replica replays them. This is usually fast, because the amount of data is small: only what changed during the absence.
A student misses two days of class. She does not need to copy the whole textbook again. Her friend simply gives her the notes from those two days, and she adds them to her own notebook.
File-based recovery: the slow path
If the primary no longer holds the needed history, or the replica has no usable data at all, the recovery must first copy files. The primary compares the segment files that the target already has with its own, using checksums. Files that are identical are reused. Missing ones are sent over the network. Once the files are in place, the primary replays operations that arrived during the copy, so that the replica ends up fully current. File-based recovery can take a long time for large shards, and it uses a lot of network and disk.
The phases in order
Assignment
The master assigns the replica to a node, and the routing table marks it as initializing.
Start of recovery
The target node contacts the primary and describes what it already holds.
Choice of method
The primary decides between replaying operations and copying files, based on the history it still holds.
Copy of files, if needed
Missing segment files are streamed to the target, within bandwidth limits.
Replay of operations
Missing operations are sent in order and applied by the target.
Finalization
The primary confirms that the target has caught up, and asks the master to mark it in sync.
Started
The routing table shows the copy as started. It counts toward the global checkpoint, and may serve reads.
Writes keep flowing during recovery
Recovery does not pause writes. While the target catches up, the primary keeps accepting new operations and also forwards them to the recovering copy, which applies them in the right places by sequence number. The recovering copy is not yet in the in-sync set, so acknowledgments do not wait for its confirmation to be counted in the rules. Only once it has caught up is it added, and from then on writes wait for it like any other member.
Recovery from the local disk
When a node restarts, its own shards first recover from local files. Each replays its translog up to the point that is known to be safe, using the global checkpoint as a guide, and opens from a commit that is not beyond it. Only then does it ask the primary for any operations that it missed while it was down. This two-step sequence, local first and peer second, is why a rolling restart of a healthy cluster is usually quick.
Limits and pacing
Recovery competes with normal traffic for disk, network, and CPU. To protect the cluster, there are limits: the number of recoveries a node may run at once, and the bandwidth that recoveries may use. Modern versions can also adapt the bandwidth limit to the hardware. Raising the limits makes recovery faster but can slow searching and indexing during the process. Lowering them protects live traffic but leaves the cluster exposed for longer. Balance is a decision to make deliberately, considering how long you can live with reduced protection.
| Recovery kind | Typical cost | When it happens |
|---|---|---|
| Local, from own disk | Very low | Node restart |
| Peer, operation-based | Low, only missing operations | Short absence with history retained |
| Peer, file-based | High, copies segment files | New replica, long absence, or lost history |
| From a snapshot | Depends on repository speed | Restoring an index |
A recovery API and a compact listing show every recovery in progress, with its stage, the amount of data copied, and the operations replayed. When a cluster is yellow after a restart, this is the first place to look for progress.
10The Translog, Soft Deletes, and Retention Leases: Keeping History Alive
Fast recovery depends on one thing: keeping just enough recent history. Here is how it is kept and how much it costs.
Every copy has its own translog
Each copy, primary or replica, appends every operation it applies to its own translog before acknowledging it. The translog is a simple, ordered file on disk. If the node crashes, it can replay the translog to recover operations that were not yet saved into committed segments. Because each copy keeps its own, a replica can recover on its own after a crash, and does not need the primary for that.
A bank teller writes every transaction in a paper log before entering it into the computer. If the computer crashes, the log is used to enter what was missed. Each teller has her own log, so one teller’s problem never needs another’s.
Durability of the translog
By default, the translog is synced to disk before each request finishes, on the primary and on every replica. That is why an acknowledged write survives even a simultaneous power failure of all nodes: it has been written to disk on every in-sync copy. A setting can relax this, syncing every few seconds instead, which speeds up writes but risks losing the last few seconds of operations on a copy that crashes. For data that cannot be recreated, keep the default.
The problem of history
The translog alone is not enough for long absences. It is trimmed regularly, once operations are safely saved in committed segments and are below the global checkpoint. If a replica is away for an hour, the primary might already have discarded the old translog parts. Something else must preserve history for the replica. That something is a pair of features working together.
Soft deletes
Normally, when a document is updated or deleted, Lucene marks the old version as deleted and it disappears from searches, until a merge removes it for good. With soft deletes, the old version is not fully removed. It is kept in the index, marked in a way that hides it from searches but preserves it as a record of what happened. This turns the index itself into a store of history. A recovering replica can read from this history to find the operations it missed.
Retention leases
But history costs disk space, so it cannot be kept forever. A retention lease is a promise made by the primary: “I will keep history at least back to sequence number N, for this copy, for a limited time.” Each copy has a lease, which moves forward as the copy catches up. The primary keeps the history required by the oldest lease. If a lease expires, because its copy has been away too long, the history it protected can be dropped, and that copy must later recover by copying files instead. The default lease period is twelve hours.
Fast recovery after restarts
A node that returns within the lease period recovers by replaying a small set of operations.
Less network traffic
Whole-file copies are avoided in most routine cases.
Extra disk space
Retained history occupies space, especially for indexes with many updates and deletes.
Slower cleanup by merges
Segments carrying history cannot shed old versions until leases release them.
Lease expiry
A copy away longer than the lease period loses the fast path and needs a file-based recovery.
Other features
Cross-cluster replication also relies on retained history to let followers catch up.
A numbers walkthrough
Let us use invented numbers. Suppose a shard receives 2,000 operations per second, and a node hosting one of its replicas is down for a ten-minute restart. That is 1,200,000 operations missed. With history retained, the recovery replays these operations, which may amount to a few hundred megabytes and takes a short time. Without history, the recovery would copy the shard’s files, which might be tens of gigabytes, and take many times longer. The retained history acts as a cheap insurance against long copy operations.
Now suppose the same node is down for two days, longer than the lease period. The lease has expired, and the history has been released. The replica returns, finds that the primary cannot supply the missing operations, and goes through file-based recovery. Planned maintenance that takes longer than the lease period will therefore incur the higher cost, and it is worth knowing that before starting.
Older versions
Before soft deletes became the standard, Elasticsearch kept extra translog files for a while, controlled by retention settings on the translog. Those settings were later deprecated in favor of soft deletes and leases, which use disk space more efficiently and are tied to what copies actually need. If you upgrade an old cluster, check the release notes for the changes in these settings.
If a node must be down for longer than the lease period, expect file-based recoveries when it returns. For very large clusters, it may be worth extending the lease period ahead of long maintenance, in exchange for more disk space, to keep recoveries cheap.
11Reads, Search Visibility, and Consistency Guarantees
Copies that agree about history can still show slightly different pictures to a searcher. Knowing exactly what is and is not guaranteed prevents many confusing bugs.
Who answers a read
Read requests can be served by any started copy of a shard, primary or replica. By default, the coordinating node spreads requests among the copies, and modern versions use adaptive replica selection: the node prefers copies that have recently answered quickly and have short queues. This spreads load well, and it also routes around a struggling copy.
Refresh is per copy
Here is the key subtlety. Synchronization guarantees that every in-sync copy has processed every acknowledged operation. It does not guarantee that every copy has refreshed at the same moment. Each copy refreshes on its own timer, by default once a second, and only after a refresh does a document become visible to searches on that copy. So right after a write, the primary may have refreshed and the replica not yet, and the same search may return different results depending on which copy answers.
Three shops receive the same new stock at the same time. Each shop’s staff puts the items on the shelves at a slightly different moment. A customer who asks “do you have it?” might hear “yes” in one shop and “not yet” in the next, even though both shops have the item in the back room.
The bouncing results problem
A user runs the same search twice, and the second time an item that was present disappears, or one that was missing appears. This happens when the two requests are served by different copies that are at different points of their refresh cycle. It is harmless for most applications, but confusing for a user who sees the result list change without doing anything. The cure is to make repeated requests from the same user go to the same copies, by giving the search a stable preference value, such as a session identifier. The same copies then answer each time, and results change only when the data does.
Real-time lookups
Fetching a document by its identifier is different. This lookup is real-time: it can see a write even before the next refresh, by consulting recent operations directly. Because an acknowledged write is present on all in-sync copies, a real-time lookup returns the newest version from any in-sync copy. That makes lookups by identifier the right tool when you must read your own write right away.
Waiting for visibility
Write requests offer options to deal with search visibility. One option forces a refresh as part of the request, which makes the change visible at once but is expensive, especially in bulk. Another makes the request wait until the normal refresh has made the change visible. Both have costs in speed, so use them sparingly, for example in tests or in user actions that truly need instant visibility.
| Question | Answer |
|---|---|
| After an acknowledged write, is the document on every in-sync copy? | Yes. This is the central guarantee. |
| After an acknowledged write, will a search on any copy find it immediately? | Not necessarily. It depends on each copy’s refresh. |
| Will a lookup by identifier find it immediately? | Yes, from any in-sync copy, because lookups are real-time. |
| Can two copies return different search results at the same instant? | Yes, briefly, because of independent refreshes. |
| Can an acknowledged write be lost if one machine fails? | No, as long as at least one in-sync copy survives. |
| Can a write with an unknown outcome, such as a timeout, be applied later? | Yes. Treat the outcome as unknown and retry safely. |
| Can a stale copy serve reads? | Only after it has recovered and rejoined. Copies dropped from the in-sync set are not used until caught up. |
Where this sits in the bigger picture
People sometimes ask which of the classic trade-offs Elasticsearch chooses. For writes inside one replication group, it favors consistency: it will not acknowledge a write that is not safe on all trusted copies, and it will pause writes rather than let copies diverge when a partition prevents the primary from confirming with the master. For searches, it favors availability and speed: any started copy can answer, and small differences in visibility are accepted. Understanding this split explains most of the behavior you will observe.
Build applications so that they do not depend on search seeing a write instantly. Show the user the data they just entered from the write response, and let the search index catch up in the background. This is faster, cheaper, and more robust than forcing refreshes.
12Configuration and Tuning
Synchronization has a small number of knobs. Each one trades speed, safety, or cost.
| Setting | Default | What it controls |
|---|---|---|
index.number_of_replicas | 1 | How many replica copies each primary has. Dynamic, can be changed at any time. |
index.auto_expand_replicas | Off | Lets the number of replicas follow the number of nodes, useful for small, critical indexes. |
index.write.wait_for_active_shards | 1 | How many copies must be active before a write starts. A pre-check only. |
index.translog.durability | Sync on every request | Whether each request is synced to disk before it is acknowledged. |
index.translog.sync_interval | 5 seconds | How often the translog is synced when durability is relaxed. |
index.soft_deletes.retention_lease.period | 12 hours | How long history is kept for a copy that is away. |
index.global_checkpoint_sync.interval | 30 seconds | How often idle shards spread the global checkpoint. |
index.unassigned.node_left.delayed_timeout | 1 minute | How long the master waits before rebuilding replicas of a departed node. |
index.refresh_interval | 1 second | How often each copy makes new documents visible to searches. |
| Recovery concurrency and bandwidth limits | Modest | How many recoveries a node runs at once and how fast they may copy data. |
| Allocation awareness attributes | None | Spreads copies over zones or racks. |
The defaults above are documented values for recent versions and may differ in yours, so check the documentation of the version you run.
Choosing the number of replicas
No replicas
Fastest writes and half the storage, but any node failure loses data. Only for loads that can be repeated, or for data that is easy to rebuild.
The usual choice
One replica survives one node failure and doubles read capacity. It costs twice the storage and roughly twice the indexing work.
Critical data
Two replicas survive two simultaneous copy failures, and are common where zone loss and a node failure could overlap.
Read-heavy small indexes
More replicas can spread heavy read traffic for small indexes, at a multiplying cost in writes and storage.
Keeping important papers safe is a matter of how many copies you make and where you keep them. One extra copy in another building protects against a fire in the first. Three copies protect against very unlikely disasters, but cost more to make and store, and every change to a paper must be copied to all of them.
Changing the number of replicas
Raising the count creates new copies, which must be built by recovery from the primary. This uses network and disk, so do it during quiet periods and one index at a time for large indexes. Lowering the count simply removes copies, which is immediate. Neither change requires downtime. The change is a cluster state update, and takes effect as the allocation service carries it out.
Relaxing durability
Setting the translog to sync only every few seconds makes writes faster, because they no longer wait for a disk sync on every copy. The price is that a copy that crashes may lose the last few seconds of operations that it had acknowledged. The other copies may still hold them, and the group can often repair itself, but a simultaneous failure of several copies could lose data. Use it only where losing a few seconds is acceptable, or where the source data can be replayed.
Zone awareness
Telling the cluster which zone each node lives in lets the allocation rules keep copies of a shard in different zones. Then the loss of a whole zone leaves at least one copy alive. To make this work, you need enough nodes in each zone to hold the copies, and the number of copies should match the number of zones or divide evenly across them.
Delayed rebuilding
The short delay before rebuilding replicas of a departed node avoids wasteful copying when a node just restarts. For fleets where nodes commonly take longer to return, such as during a rolling upgrade of large machines, raising the delay may save effort. For fleets where nodes rarely return, lowering it restores protection sooner. The best value depends on how long your typical restart takes.
Each setting above has a safety side. Change one at a time, note why in your records, and measure the effect on both speed and the time it takes to return to green after a failure.
13Performance and Scalability
Replication multiplies work. Understanding the multiplication tells you where speed is won and lost.
Write amplification
In the standard model, every replica repeats the whole indexing job. With one replica, the cluster does the analysis, indexing, and translog work twice for each document. With two replicas, three times. Storage grows in the same way. The network carries each operation from the primary to each replica. So the total resource cost of a write is roughly the cost of one copy multiplied by the number of copies.
A numbers walkthrough
Let us use invented numbers. Suppose an application sends 100 megabytes per second of documents into an index with one replica. The cluster receives 100 megabytes per second at the front, but the primaries then send another 100 megabytes per second to the replicas, so 200 megabytes per second are indexed in total, and 100 megabytes per second cross the internal network between nodes. With two replicas, the total indexed becomes 300 megabytes per second, and the internal network carries 200. A cluster sized for the incoming rate alone would be short of processor and network capacity by a large factor.
If a printing office must produce one copy of a report for each of three buildings, then a report that takes an hour to print takes three hours of printer time in total. The number of reports that arrive matters, but so does the number of copies each needs.
What sets the write speed
The primary’s own work
Validation, analysis, indexing, and the translog sync on the primary are the first cost.
The slowest in-sync replica
The write waits for every in-sync copy. A slow one sets the speed of the whole group.
Bandwidth between nodes
Each operation crosses the network once per replica. Saturated links slow replication.
Translog syncs and merges
Every copy syncs its translog and merges segments. Slow disks slow everything.
Write queues and memory limits
Replicas have their own write queues and memory guards for in-flight work. Overload there causes rejections that come back to the primary.
Balance of primaries
Uneven spread of primaries concentrates work on a few nodes while others idle.
Replicas do not speed up writes
A common misunderstanding is that more replicas make the cluster faster. They make reads faster, because more copies can answer, but they make writes slower and more expensive. Write capacity scales with the number of primary shards and the machines behind them, not with the number of replicas. If writes are your bottleneck, adding replicas will only make it worse.
Bulk loading tricks
Because replication multiplies cost, loading a large amount of data into a new index is much faster with zero replicas, followed by adding them at the end. The replicas then are built by copying finished segment files, which is cheaper than indexing each document again. The risk is that, during the load, there is no second copy, so the load must be repeatable. Restore the replicas as soon as the load finishes.
Memory guards for in-flight writes
Recent versions track the memory used by operations in flight at three stages: at the coordinating node, at the primary, and at the replica. When the limit at a stage is exceeded, new work at that stage is refused with a “too many requests” answer. The limit for the replica stage is somewhat higher than for the primary stage, because refusing at the replica would waste work already done on the primary. The result is that the cluster protects itself, and clients should be ready to slow down and retry.
Read scaling
Replicas do add read capacity. If searches are the bottleneck and the index is small enough to hold several copies, adding replicas can help. Adaptive replica selection sends requests to the healthiest copies, and requests are spread among all started copies. For very large indexes, adding replicas is expensive in storage, so consider whether caching, better queries, or more shards would serve better.
Recovery cost and shard size
The time to recover a copy grows with shard size when file copying is needed. Very large shards, hundreds of gigabytes, can take hours to rebuild and leave the group exposed for that time. Moderately sized shards, in the tens of gigabytes, rebuild faster and rebalance more easily. This is one more reason to avoid oversized shards.
Measure the incoming rate
Know how many megabytes per second arrive at the front of the cluster.
Multiply by the number of copies
Estimate the real indexing rate, and the internal network traffic.
Check the slowest link
Find the node, disk, or network path with the least headroom.
Test failure behavior too
Measure how long recovery takes after a node loss, because exposure time matters as much as speed.
14Advantages, Disadvantages, and Trade-offs
Every design carries a price. Here is the honest balance sheet of synchronizing copies this way.
Advantages
- Acknowledged writes are safe on every trusted copy.
- Fast, automatic failover with no data loss for acknowledged writes.
- Numbered operations give a single, agreed history.
- Fast recovery after short absences, using operation replay.
- Replicas add read capacity and spread search load.
- Stale copies can never be promoted by mistake.
- Zombie primaries are stopped by terms and the master’s check.
Disadvantages
- Every copy repeats the indexing work, multiplying CPU cost.
- Storage and network use grow with each replica.
- A slow in-sync replica slows writes until it is removed.
- Search visibility differs slightly between copies.
- Long absences force expensive file-based recovery.
- Retained history costs disk space on busy indexes.
- Timeouts leave writes with unknown outcomes.
| Trade-off | Leaning toward speed or cost | Leaning toward safety |
|---|---|---|
| Replica count | Zero or one: cheaper, faster writes | Two or more: survives more failures, higher cost |
| Translog durability | Relaxed: faster writes, may lose seconds on a crash | Per request: safe, a disk sync on every copy |
| Refresh interval | Longer: cheaper indexing, data visible later | Shorter: data visible sooner, more work |
| Retention lease period | Short: less disk used, more file-based recoveries | Long: cheap recoveries, more disk used |
| Recovery bandwidth | Low: protects live traffic, longer exposure | High: quick repair, may slow searches and writes |
| Delayed rebuilding | Long: avoids needless copying, longer with fewer copies | Short: restores protection sooner, may copy needlessly |
| Shard size | Very large: fewer shards, slow recovery | Moderate: faster recovery, more shards to manage |
Keeping several careful copies of a diary is safer than keeping one, but every entry takes longer to write, and the cupboard fills up. A sensible person keeps as many copies as the diary is worth, and puts them in different houses.
How strict should you be?
| Situation | Recommended stance |
|---|---|
| Development sandbox with fake data | Relaxed: zero or one replica, defaults everywhere |
| Production search over data rebuilt from a database | One replica, default durability, zone awareness if possible |
| Logs and metrics that can tolerate small loss | One replica on recent data, snapshots for history, careful tuning of refresh |
| Records of business value that are hard to recreate | Two replicas, zone awareness, per-request durability, tested snapshots |
| One-time bulk migration | Aggressive: zero replicas during the load, restore right after, verify counts |
15High Availability and Reliability
A design is only proven by how it behaves when things go wrong. Here is what happens in each failure, and how to prepare.
| Failure | What the group does | What users notice |
|---|---|---|
| A replica’s node crashes | Primary drops the copy from the in-sync set, writes continue, replica is rebuilt later | Yellow health for a while, no data loss |
| A replica is very slow | Writes slow down until the copy times out and is dropped | Slower writes, then recovery of speed |
| The primary’s node crashes | An in-sync replica is promoted with a higher term, then resyncs the others | A brief pause in writes to that shard, reads continue |
| Network splits the primary from the master | Primary cannot acknowledge, master promotes a replica on its side | Some errors or timeouts on writes, no acknowledged write is lost |
| All replicas fail, primary survives | Primary continues alone | Yellow, no redundancy, urgent to repair |
| Primary and all in-sync replicas fail | Shard stays unassigned rather than using a stale copy | Red health, part of the data unavailable |
| A node’s disk fills up | Watermarks stop new shards, and at the flood level indexes with shards there become read-only for writes | Write rejections on affected indexes |
| A whole zone is lost | Copies in other zones are promoted and serve traffic | Yellow, and no loss if copies were spread across zones |
| All nodes restart together | Shards recover from local disks, replicas catch up | A period of unavailability, then recovery |
A relay team keeps a spare runner for each leg. If a runner trips, the spare steps in, and the coach makes sure the spare knows exactly how far the race has gone before she runs. If the runner and the spare both trip, the team refuses to use a runner who did not watch the race, because she might run the wrong way.
Designing for resilience
- Enough copies. At least one replica for anything you cannot afford to lose, and two where multiple failures could overlap.
- Copies in different zones. Configure awareness so that one zone never holds all copies of a shard.
- Capacity to absorb a failure. Keep enough free disk and headroom on the remaining nodes to take over the shards of a lost node.
- Healthy masters. Three or more dedicated master-eligible nodes, since promotions need the master.
- Snapshots. Regular, tested snapshots protect against losing every copy, or against mistakes that replicate to all copies.
- Practice. Test failover in a non-production environment, and measure how long recovery takes.
Replication copies every change, including mistakes. If someone deletes an index, or a bug writes bad data, all copies obey. Replicas protect against hardware failure, not against human error. Only snapshots can bring back data that was deleted or damaged on purpose or by accident.
Rolling restarts
To restart nodes without losing availability, limit shard allocation before you start so that the cluster does not rebuild replicas for a node that will be back within minutes, restart one node at a time, wait for it to rejoin and for its shards to be recovered, then restore normal allocation and wait for green health before moving on. Because history is retained by leases, a node that returns within the lease period recovers by replaying operations, and the whole process is quick. Never restart several nodes at once if they hold copies of the same shard, since that could leave no in-sync copy running.
Confirm green health
Do not begin while any shard is unassigned or recovering.
Limit allocation
Prevent needless rebuilding while a node is briefly away.
Restart one node
Wait until it rejoins and its shards start.
Restore allocation
Let any remaining replicas catch up.
Wait for green, then continue
Only then move to the next node. Confirm at the end that no maintenance settings remain changed.
Dealing with unknown outcomes
When a write times out, or the connection breaks, the client cannot know whether it was applied. The correct response is to design writes to be safe to repeat. Supplying your own document identifiers achieves this, since repeating the operation overwrites the same document. With generated identifiers, a repeated write after an uncertain timeout can create a duplicate, so deduplicate later or avoid this pattern for critical data.
16Security Considerations
Replication moves your complete data between machines all day long. That traffic and those copies deserve protection.
The traffic between nodes carries full documents
Every operation the primary forwards to a replica contains the complete document. On an unprotected network, anyone who can watch traffic between nodes can read your data. Enable encryption for node-to-node communication. This also authenticates nodes to each other, if certificates are used properly, which brings the next point.
Who may join and receive copies
A node that joins the cluster can be assigned shard copies, and recovery would then send it entire shards. An attacker who could start a node that joins your cluster would receive real data. Prevent this by requiring certificates for cluster membership, by restricting network access to the ports nodes use to talk to each other, and by giving each cluster a unique name and credentials.
If anyone could walk into the copying room of a bank and declare “I am also a ledger keeper, please give me a copy,” they would be given the bank’s records. Badges at the door, and a guest list, prevent that.
Privileges to change replication
Changing the number of replicas, moving shards, or forcing an unsafe promotion are administrative actions. They can weaken protection, reduce availability, or, in the case of forcing a stale copy, destroy data. Give the right to perform them only to trusted administrators and automation. Ordinary applications should have rights to read and write documents only.
Encrypt node-to-node traffic
Protects operations and recoveries as they cross the network.
Certificates for nodes
Only nodes with valid certificates may join and receive copies.
Restrict node ports
Only cluster members should reach the ports used for replication.
Limit administrative rights
Only trusted roles may change replicas, allocation, or force promotions.
Protect every copy’s disk
More copies mean more disks holding the data, all of which must be encrypted and controlled.
Log changes
Record who changed replica counts and allocation, and when.
More copies, more places to protect
Each replica is a full copy of the data on another machine’s disk. Security controls that apply to the primary, such as disk encryption, access restrictions on the machine, and secure disposal of retired hardware, must apply equally to every replica. A cluster is as secure as its least protected node.
Deletion and privacy
When you delete a document, the change is replicated to every copy. But because history is kept for recovery, the old version of the document may remain on disk for a while, in the retained history, until leases release it and a merge removes it. For most uses, this is invisible. For strict privacy requirements, such as erasing personal data on request, be aware that removal from disk is not instant, and design your deletion and retention processes with this window in mind. Snapshots also hold copies until they expire.
Snapshots as a separate security domain
Snapshots are stored outside the cluster, often in cloud storage. Protect that storage with its own access rules, encryption, and retention policy. A well-protected cluster with an open snapshot bucket is not a secure system.
Turn on authentication and encryption, even for clusters that seem internal. Many incidents begin with a cluster that was described as “only internal” and had no protection at all.
17Monitoring, Logging, and Metrics
Synchronization problems announce themselves early, if you are watching the right numbers.
| Metric or signal | What it tells you | Warning sign |
|---|---|---|
| Cluster health color | Whether all primaries and replicas are assigned | Yellow or red beyond a planned window |
| Unassigned and initializing shard counts | How many copies are missing or being rebuilt | Counts that do not shrink over time |
| Gap between the highest sequence number and each copy’s local checkpoint | How far each replica lags behind the primary | A gap that keeps growing |
| Global checkpoint progress | Whether the safe point moves forward on active shards | Stuck while writes continue |
| Failed count in write responses | Writes acknowledged with fewer copies than planned | Any nonzero value |
| Write rejections on replicas | Replicas that cannot keep up with incoming operations | A sustained rise |
| Indexing pressure by stage | Memory of in-flight work at coordinating, primary, and replica stages | Rejections at the replica stage |
| Recovery progress and duration | How fast copies catch up | Recoveries that take much longer than usual |
| Primary term changes | How often primaries are replaced | Frequent changes for the same shards |
| Translog size and uncommitted operations | How much is waiting to be committed | Rapid growth |
| Retention leases | Which copies are protected by history, and for how long | Leases close to expiry for copies that are away |
| Disk use and watermarks | Space for shards, translogs, and history | Nodes near the flood level |
| Network throughput between nodes | Replication and recovery traffic | Links near their capacity |
Reading the patterns
Green, small lag, no failures
Checkpoints advance together, writes report full success, recoveries are short.
One replica falls behind
Its local checkpoint trails, writes slow down, and it may be dropped. Look at that node’s disk, CPU, and network.
Replicas dropped and rebuilt again and again
Usually a sign of an unstable node, or a network that loses packets. Fix the cause before more rebuilds.
Rejections at the replica stage
Replicas cannot keep up with the primaries. Reduce load, add capacity, or lower the replica count for that index.
Yellow for a long time
The cluster is running with less protection. Find out why shards are not being rebuilt.
Primary terms rising quickly
Primaries keep being replaced. Suspect network trouble or master instability.
Logs that help
The master’s log records when copies are marked as failed, when nodes leave, and when primaries are promoted. Data nodes log the start and end of recoveries, slow operations, and the reasons that a replica was failed. When something odd happens, read the master log around that time first, then the logs of the nodes involved. Ship logs to a central place, so that they survive the loss of a machine, and keep them long enough to investigate incidents that appeared days ago.
A troubleshooting playbook
Ask for the health
Note the color and the counts of unassigned and initializing shards.
Ask why shards are unassigned
The allocation explanation names the rule that refused each placement, such as disk space, awareness, or a filter.
Check the recoveries
See which are running, at what stage, and how much data has moved.
Compare checkpoints
Look at the shard statistics of the affected shard to see each copy’s progress.
Look at the nodes involved
Disk, CPU, garbage collection, and network on the lagging or missing copy.
Read the logs
Find the moment the copy was failed and the reason recorded.
Fix the cause, then let the cluster repair
Free disk, fix the network, restart the node, or adjust limits. Avoid forcing unsafe actions.
Alert on health that stays yellow or red beyond a set time, on write responses that report failed copies, on replica write rejections, on recoveries that run far longer than normal, on rapidly rising primary terms, and on nodes approaching disk watermarks.
18Design Patterns and Anti-patterns
Good habits keep replicas healthy and recoveries quick. Bad habits are behind most replication incidents.
Patterns that work
One replica by default, two for the critical
Choose the number of replicas by the value of the data and the failures you must survive, not by habit.
Zone-aware placement
Spread copies across zones so that the loss of a zone never removes every copy.
Moderate shard sizes
Keep shards in the tens of gigabytes so that recovery and rebalancing stay quick.
Zero replicas for bulk loads, restored after
Load fast with a single copy, then add replicas, and verify that health returns to green.
Snapshots as the real backup
Replicas for hardware failure, snapshots for mistakes and disasters.
Idempotent writes
Use stable identifiers so that repeated writes after timeouts are harmless.
Sticky search preference
Give users a stable preference value so that repeated searches use the same copies and results do not bounce.
A careful librarian keeps a second copy of each valuable book in a different building, stores a backup of the catalog off-site, and makes sure that every loan is recorded the same way in both places. The habits are simple, and they are what make a library survive a flood.
Anti-patterns to avoid
What people do
They run important production indexes with zero replicas to save money or speed up writes.
Why it hurts
Any node failure makes part of the data unavailable, and a disk failure loses it. Restoring from a snapshot takes far longer than failing over to a replica.
Better approach
Keep at least one replica for data that matters. Use zero replicas only for temporary loads or data that is easy to rebuild.
What people do
They believe replicas are a backup and skip snapshots.
Why it hurts
Replication copies every change, including deletions and mistakes, to all copies. A wrong delete is faithfully replicated.
Better approach
Take regular snapshots to storage outside the cluster, and test restoring from them.
What people do
They place a primary and all its replicas in the same rack or zone, because no awareness was configured.
Why it hurts
A single rack or zone failure removes every copy at once, so the redundancy provides no protection against that failure.
Better approach
Configure allocation awareness, and make sure enough nodes exist in each zone.
What people do
They ask for a refresh on every write so that documents are searchable immediately.
Why it hurts
Each write triggers extra work on every copy, and the benefit of batching is lost. Throughput drops sharply.
Better approach
Read your own writes through lookups by identifier, and let search catch up on its normal schedule.
What people do
They relax translog durability on data that cannot be recreated to gain a little speed.
Why it hurts
A crash can lose the last seconds of acknowledged writes on a copy, and a simultaneous failure of several copies can lose them everywhere.
Better approach
Keep the safe default for important data. Relax it only for data that can be replayed from a source.
What people do
They raise the recovery bandwidth to the maximum and rebuild many replicas during peak traffic.
Why it hurts
Recoveries compete with live searches and writes for disk and network, and can cause rejections and timeouts, which may cause more copies to be dropped.
Better approach
Raise limits gradually, prefer quiet periods, and watch the effect on live traffic.
What people do
They ignore the count of failed copies in write responses, and only look at the overall success.
Why it hurts
Writes may be quietly accepted with reduced protection for a long time, and nobody notices until a second failure.
Better approach
Record and alert on writes where fewer copies succeeded than planned, and watch health closely.
What people do
They restart several nodes at once, including nodes that hold copies of the same shard.
Why it hurts
If every in-sync copy of a shard is down at the same time, the shard becomes unavailable, and recovery may be slow.
Better approach
Restart one node at a time, and wait for green health between restarts.
19Best Practices and Common Mistakes
A short list you could hand to a new teammate on their first day.
Best practices
Right number of replicas
One by default, two for critical data, zero only temporarily.
Spread across zones
Use awareness so no failure domain holds all copies.
Leave headroom
Keep free disk and processing room to absorb the shards of a failed node.
Moderate shards
Tens of gigabytes per shard keep recovery fast and balancing easy.
Snapshots, tested
Replicas do not replace snapshots, and untested snapshots are only hopes.
Design for unknown outcomes
Use stable identifiers and safe retries.
Do not depend on instant visibility
Use lookups by identifier, or accept a short refresh delay.
Alert on exposure
Yellow status, failed copies in responses, and long recoveries are early warnings.
Common mistakes
- Assuming a replica is always identical to the primary. Copies agree on history for acknowledged writes, but refreshes and in-flight operations mean small differences at any instant.
- Assuming acknowledged means searchable. Visibility depends on refresh, which is separate.
- Adding replicas to speed up writes. More replicas increase the write cost.
- Forgetting that replicas cost storage. Every replica doubles the data on disk, and history retention adds more.
- Planning maintenance longer than the lease. A node away longer than the retention lease must recover by copying files.
- Forcing a stale primary without understanding the loss. It permanently discards writes that the stale copy missed.
- Leaving load-mode settings in place. Zero replicas or relaxed durability after a bulk load leave the index exposed.
- Never testing a failover. The first real failure should not be the first time you see how the cluster reacts.
Myths versus facts
| Myth | Fact |
|---|---|
| Replicas are backups. | They copy every change, including mistakes. Only snapshots protect against errors. |
| Replicas make writes faster. | They make reads faster and writes slower and more costly. |
| A replica copies files from the primary on every write. | In the standard model each replica applies the operations itself and keeps its own translog. |
| An acknowledged write might be lost if one node fails. | Acknowledged writes are on all in-sync copies, so one failure cannot lose them. |
| Any surviving copy can become primary. | Only copies in the in-sync set may be promoted. |
| Yellow means data is lost. | Yellow means all primaries work and some replicas are missing. |
| Searches always return the same results from every copy. | Copies refresh independently, so results can differ briefly. |
| Recovery always copies the whole shard. | Often it replays only the missed operations, when history is retained. |
Think of every copy as a promise: a promise of durability, of read capacity, and of recovery. Each promise costs storage, work, and attention. Make as many as the data deserves, place them apart from each other, and check regularly that they can be kept.
20Real-World and Industry Examples
Where does synchronization quietly decide success or trouble?
Many well-known organizations have said publicly that Elasticsearch is part of their systems, including Wikipedia’s search, Netflix, Uber, and Stack Overflow. They rarely publish how they set up replication, so the scenarios below are typical patterns for such workloads, not descriptions of anyone’s private configuration.
Online marketplace: reads outnumber writes
A marketplace of the size of Amazon or eBay serves far more searches than product updates. Its product index has one or two replicas, spread over zones, so that searches spread across many copies and one machine failure goes unnoticed by shoppers. Updates use stable product identifiers, so retried writes are harmless.
Log platform: writes dominate
A streaming or ride-hailing company indexes a huge stream of logs. Here, replicas mostly cost, and rarely serve reads. The team keeps one replica on recent, hot indexes so that a failed node does not lose data, tunes the refresh interval to reduce work, and relies on snapshots for older data. Bulk reindexing uses zero replicas during the load, followed by restoring one.
Financial records: safety first
A company that stores records with business value keeps two replicas, spread over three zones, with the safe translog default and per-request acknowledgment of all in-sync copies. Snapshots run frequently and restores are practised. The extra cost is accepted as the price of safety.
Rolling upgrade at scale
An operator upgrades a cluster of hundreds of nodes over a weekend. Allocation is limited before each restart, one node is restarted at a time, and the cluster returns to green between steps. Because each node returns within the retention lease period, replicas catch up by replaying a few operations, and no bulk copying is needed.
A zone outage
A cloud provider loses one zone. The cluster promotes replicas in the surviving zones to primaries, resyncs the remaining copies, and keeps serving. Health turns yellow, then returns to green as new replicas are built once the zone is back or capacity is added. Users see a brief blip in write latency for the affected shards, and no data loss.
A slow replica that dragged everyone down
A node with a failing disk answered replication requests very slowly. Every write to shards with a copy on that node waited for it, and indexing throughput fell. Monitoring showed one replica’s local checkpoint trailing far behind. The team removed the node from service, the cluster dropped its copies from the in-sync set, throughput recovered, and replicas were rebuilt on healthy hardware.
In every example, the winning ideas are the same: the right number of copies for the value of the data, copies spread across failure zones, snapshots for mistakes, careful maintenance, and monitoring that spots a lagging or missing copy early.
21Frequently Asked Questions
Short answers to the questions that come up most often.
22Summary and Key Takeaways
If you skim only one part of this guide, make it this one.
Primary-replica synchronization is how Elasticsearch turns several machines into one reliable home for each shard. The primary numbers every write and passes it to its replicas, the cluster tracks which copies are fully up to date, and a strict set of rules governs failures, promotions, and recovery. It costs extra work and storage on every copy, and in return it lets the cluster survive failures without losing an acknowledged write.
Key Takeaways
- The write rule: the primary validates and numbers each write, forwards it in parallel to all in-sync replicas, and acknowledges only when they have confirmed or been removed from the in-sync set.
- The bookkeeping: sequence numbers fix the order, primary terms stop old primaries, and local and global checkpoints show exactly what each copy has processed and what is safe everywhere.
- The trust list: only in-sync copies may be promoted, so a stale copy can never quietly become the primary and lose acknowledged writes.
- Failure handling: a failed replica is dropped through the master, a failed primary is replaced by an in-sync replica followed by a resync, and unknown outcomes for in-flight writes must be handled by safe retries.
- Recovery: copies catch up by replaying missing operations when history is retained, and by copying files when it is not, so keep maintenance within the retention lease period.
- Visibility: acknowledgment means safe, not searchable. Each copy refreshes on its own, so use lookups by identifier or a stable search preference where it matters.
- Running it well: choose replica counts by data value, spread copies across zones, use snapshots as the real backup, watch lag and failed copies, and protect the traffic and machines that carry the replicas.