What Is Cluster State in Elasticsearch?
A complete, plain-English guide to the shared map that every Elasticsearch node carries: what is written in it, who is allowed to change it, how a change travels to every machine, and why its size and health decide how far your cluster can grow.
Imagine a treasure-hunt team of twenty people spread out across a big forest. Everyone carries the same map. The map shows where each teammate is standing, which paths are open, which bridges are closed, and who is guarding which clue. If one person had an old map and walked into a closed bridge, the whole team would suffer. So the team has one captain. Only the captain may draw on the master map. When something changes, the captain sends the update by radio, waits until most of the team confirms, and only then says, “This is now the official map.”
That shared map is what Elasticsearch calls the cluster state. It is not your data. It is the description of the cluster itself: which machines are members, which indexes exist, where every piece of every index lives, and which rules are switched on. Almost everything Elasticsearch does, from creating an index to recovering from a crashed machine, is really a change to this map. This guide starts from zero, opens the machinery step by step, and ends with the numbers, the warning signs, and the habits that keep the map small, fresh, and trusted in production.
1What Cluster State Actually Is
Three plain ideas, put together: a cluster, a state, and agreement. Once each is clear, the rest follows naturally.
Elasticsearch stores and searches documents, such as products, articles, or log lines. To handle a lot of data, it does not run on one machine. It runs on many machines called nodes, and a group of nodes that work together is called a cluster. Each index is cut into pieces called shards, and those shards are spread across the nodes, with extra copies called replicas kept for safety.
Now think about what the nodes need to know. Which nodes are in the cluster right now? Which indexes exist, and what fields do they have? Which node holds the main copy of shard 3 of the orders index? Which copy is the freshest? Is any part of the cluster temporarily locked? Every node must give the same answers to these questions, or requests would be sent to the wrong places and data could be lost.
The cluster state is the single, shared record that answers all of these questions. It is a data structure that describes the cluster as a whole. It has a version number, it is changed by exactly one node at a time, and a copy of the latest version is held in the memory of every node in the cluster.
Think of a school with several buildings. The office keeps one master register that says which classrooms exist, which teacher is in which room, and which rooms are closed for repairs. Every building has a printed copy of the register on its wall. Only the office may change the register, and when it does, it sends out the new pages to all buildings. The lessons themselves, meaning the students’ notebooks, are not in the register. The register only says where things are and how the school is arranged.
What it is not
A very common mistake is to think that the cluster state contains the documents. It does not. If you index a million documents, the cluster state does not grow by a million entries. The documents live inside shards, on the disks of the data nodes. The cluster state only records that the index exists, what its fields look like, and which nodes hold which shards. This is why the state can stay small even when the data is enormous, and also why it can become large for a different reason: too many indexes, too many shards, or too many fields.
Elasticsearch has many things with the word “state” or “status” in them. The cluster health color, the shard state, the node stats, and the snapshot status are all different views. Several of them are computed from the cluster state, but none of them is the cluster state itself. Chapter 11 shows how to look at each one.
The one-sentence version
If you remember one line from this chapter, make it this: the cluster state is the versioned, cluster-wide description of nodes, indexes, settings, and shard locations, written only by the elected master, agreed by a majority, and cached in memory on every node.
2Why It Exists: Many Machines, One Truth
Every design has a problem behind it. The problem here is agreement.
When only one machine is involved, everything is easy. It knows what it has. When many machines cooperate, three difficulties appear at once.
- Disagreement. If node A believes that shard 2 lives on node B, while node C believes it lives on node D, then a write may go to one place and a read to another. The user sees missing or old data.
- Simultaneous changes. If two administrators create an index with the same name at the same moment on two different nodes, someone must decide which one wins. Without a single decision maker, both might succeed and produce a broken cluster.
- Failure. Machines crash, networks break, and messages get lost. The cluster must keep a consistent picture even while parts of it disappear and come back.
The cluster state solves these problems together. It gives the cluster one shared picture. It routes all changes through one elected writer, the master, so there is never a fight over who decides. And it uses a voting rule so that, even during failures, the cluster never ends up with two different maps both claiming to be the real one.
Suppose a group of friends is planning a picnic through text messages. Everyone edits their own list of who brings what. Soon three people bring lemonade and nobody brings plates. The fix is to choose one organizer who keeps the official list and tells everybody about every change. The cluster state is that official list, and the master is the organizer.
A short history
Early days: a master and a shared picture
From the beginning, Elasticsearch elected a master node and let it publish a shared description of the cluster. This idea has stayed the same ever since.
The old discovery module
Nodes found each other, and elected masters, using a module known as Zen Discovery. It relied on an operator-set number, often called “minimum master nodes,” that had to be configured correctly to avoid the dreaded split brain, where two halves of a cluster each elect their own master.
Version 7: a new coordination layer
Around version 7.0, the election and publishing logic was rewritten using ideas from well-known agreement algorithms. The cluster now manages the voting group by itself, and the fragile manual number was removed.
Later releases: more visibility and guard rails
Newer versions added better statistics about how long state updates take, warnings for slow updates, and limits on the number of shards per node, all aimed at the problem of states that grow too large.
Today: safe by default, heavy if abused
Modern clusters form and elect safely with little setup. The remaining challenge for operators is keeping the state small and its updates fast.
The exact release for each step is worth double-checking in the release notes of your version. The direction of travel is clear: agreement became safer and more automatic, while the operator’s main job moved from “avoid split brain” to “avoid an oversized state.”
Why not keep the map in a separate database?
Some systems store their cluster description in an outside service. Elasticsearch chose to keep it inside the cluster itself. This makes installation simple, because there is nothing else to run, and it keeps the map close to the machines that need it. The price is that Elasticsearch has to solve the agreement problem on its own, which is why this part of the system is so carefully built.
3Core Concepts You Need First
A dozen words explain nearly everything about cluster state. Learn them here, and later chapters will read like common sense.
Node
One running Elasticsearch process. Every node has a role, or several roles, such as master-eligible, data, or coordinating.
Master node
The one node, elected from the master-eligible group, that is currently allowed to change the cluster state.
Master-eligible node
A node that may vote in elections and may become master. It also saves the cluster metadata to its disk.
Index and shard
An index is a named collection of documents. It is cut into shards, and each shard can live on a different node.
Primary and replica
The primary shard takes writes first. A replica is a copy, kept on another node for safety and extra reading power.
Metadata
The long-lived facts: index settings, field mappings, aliases, templates, and cluster settings.
Routing table
The seating chart of the cluster: for every shard copy, which node holds it and what condition it is in.
Blocks
Restrictions recorded in the state, such as “no writes allowed on this index” or “no master is available yet.”
Quorum
A majority of the voting nodes. A change needs a quorum to be accepted, which prevents two rival maps.
Term
A counter that goes up with each election. It lets nodes ignore messages from an old master.
Publish, commit, apply
The three steps of an update: send the new state, make it official after a quorum accepts, and switch to it on every node.
Diff
A small description of what changed between two versions of the state, sent instead of the whole thing when possible.
Roles: who does what
A node can carry several roles. A small development cluster may have one node doing everything. A large production cluster usually separates them. Master-eligible nodes handle elections and cluster-wide decisions. Data nodes hold shards and do the searching and indexing. Coordinating nodes receive requests, split them up, and gather the results. Every one of these nodes, regardless of role, holds the cluster state in memory, because they all need the map to do their jobs.
In a restaurant, the head waiter decides table assignments, the cooks prepare the food, and the greeters take orders at the door. All of them need the same seating chart on the wall. Only the head waiter is allowed to change who sits where.
Metadata versus routing
The state has two big halves that are worth learning to separate. The metadata half is about what exists and how it is defined. It changes when someone creates an index, adds a field, or updates a setting. The routing half is about where things physically are. It changes when a shard moves, a replica is added, or a node leaves. The metadata half is usually the larger one. The routing half is the one that changes most often during failures.
Versions and immutability
Every published cluster state has a version number that only goes up. A state is treated as read-only once it is created. To change anything, the master builds a brand-new state, with the change applied and a higher version, and publishes that. This makes it easy to reason about: at any moment, a node has one complete and consistent picture, and never a half-changed one.
Quorum in one story
Imagine three judges who must decide a case by majority. Two of them agreeing is enough to have a decision, and the third cannot contradict it. If a storm cuts off one judge, the other two can still decide. If the storm cuts off two judges, the remaining one cannot decide alone, because she cannot know whether the other two reached a different decision. Elasticsearch works in the same way: with three master-eligible nodes, any two form a quorum, and a single isolated node stops making cluster-wide decisions instead of guessing.
Having two master-eligible nodes gives no more safety than having one, because losing either of them breaks the majority. Elasticsearch handles even numbers by quietly leaving one node out of the vote. For real resilience, use three, and keep the number odd.
Quick glossary
| Word | Plain meaning |
|---|---|
| Split brain | A failure where two parts of a cluster each believe they are in charge and make different decisions. |
| Election | The vote among master-eligible nodes that chooses the master. |
| Voting configuration | The list of master-eligible nodes whose votes count toward a majority. |
| Mapping | The blueprint that says which fields an index has and what type each field is. |
| Template | A stored recipe that is applied automatically to new indexes with matching names. |
| Allocation | The decision about which node should hold which shard copy. |
| Recovery | Bringing a shard copy up to date on a node, after a restart, a move, or a failure. |
| Heap | The working memory of the Java program that Elasticsearch runs in. |
4Architecture and Components
Who holds the state, who writes it, and how does a change reach every machine?
Every node in the cluster holds a full copy of the latest committed cluster state in memory. That is what lets any node, even a coordinating node with no data, route a request correctly. Only one node, the elected master, is allowed to create new versions. The master-eligible nodes also save the metadata part of the state to their disks, and they are the ones who vote on changes.
flowchart TB
Admin["Admin or application: create index, change settings"] --> Coord["Any node receives the API request"]
Coord --> M["Elected master node: the only writer of cluster state"]
subgraph Masters["Master-eligible nodes: vote and save the state on disk"]
M
ME1["Master-eligible node 2"]
ME2["Master-eligible node 3"]
end
subgraph Others["All other nodes: hold a full in-memory copy"]
D1["Data node A"]
D2["Data node B"]
C1["Coordinating node"]
end
M -->|publishes new state| ME1
M -->|publishes new state| ME2
M -->|publishes new state| D1
M -->|publishes new state| D2
M -->|publishes new state| C1
Read the picture from top to bottom. A request that needs a cluster-wide change, such as creating an index, can arrive at any node. That node forwards the request to the elected master. The master builds the next version of the state and sends it to every node in the cluster, including the other master-eligible nodes, the data nodes, and the coordinating nodes. Nothing in this picture requires the master to be a big machine. Its job is careful bookkeeping, not heavy data work.
The main components
Master service
A queue and a single worker inside the master. It takes change requests one group at a time and turns each group into a new state.
Coordination layer
Runs elections, tracks the voting group, and performs the two-step publish and commit for each new state.
Cluster applier
On every node, it receives a committed state and applies it: creating or deleting local shards, updating local settings, notifying components.
Allocation service
Inside the master, it decides where shard copies should live and produces the routing table changes that follow.
Persisted state
The on-disk copy of cluster metadata kept by master-eligible nodes, and index metadata kept by data nodes for their own shards.
Fault detection
Regular health checks: the master checks that followers are alive, and followers check that the master is still there.
State APIs
Endpoints that show the state or views of it: health, pending tasks, allocation explanation, and the full state dump.
Blocks and limits
Settings and recorded restrictions that protect the cluster, such as limits on shard counts and write blocks on full disks.
Walking one change through the machine
A request arrives at any node
For example, someone asks to create an index, change a setting, or add an alias.
It is forwarded to the master
The receiving node finds the current master in its own copy of the state and sends the task there.
The task waits in the master’s queue
Tasks have priorities. Urgent ones, such as reacting to a lost node, run before routine ones.
The master computes the next state
It takes the current state, applies the change, and creates a new state with a higher version number.
The state is published and committed
The master sends it to all nodes, waits for a majority of voting nodes to accept it, and then announces that it is official.
Every node applies it
Nodes update their in-memory copy and act on it, for instance by starting to create the new shards assigned to them.
The caller gets an answer
The master reports success, usually once enough nodes have applied the change within a time limit.
Because every change goes through a single writer and must reach every node, the speed of this path is a hard limit on how often the cluster can change. Ordinary reads and writes of documents do not use this path at all, which is why the cluster can handle huge traffic even though the state changes slowly.
5What Lives Inside the Cluster State
Now we open the folder and look at the pages. Knowing what is inside tells you what can make it large or slow.
flowchart LR
CS["Cluster State"] --> N["Nodes: who is in the cluster and their roles"]
CS --> MD["Metadata"]
CS --> RT["Routing table: where every shard copy lives"]
CS --> BL["Blocks: read-only or no-master restrictions"]
CS --> ID["Identity: cluster id, version, elected master"]
MD --> S["Persistent settings"]
MD --> IX["Index settings, mappings, aliases"]
MD --> TP["Templates and data streams"]
MD --> OT["Pipelines, lifecycle policies, repositories, stored scripts"]
Identity and membership
At the top sits the identity of the state itself: a unique cluster identifier, the current version number, a unique identifier for this exact version, and the name of the elected master. Next comes the list of nodes: for each member, its identifier, its name, its address, its roles, and its attributes, such as a zone label. When a node joins or leaves, this list changes.
Metadata: the long-lived facts
Persistent cluster settings
Cluster-wide switches that were changed through the settings API and must survive restarts.
Index definitions
For every index: its settings, its mappings, its aliases, how many shards and replicas it has, and which shard copies are known to be up to date.
Templates
Stored recipes that apply mappings and settings to new indexes, in both the newer composable form and the older form.
Data streams
Definitions of append-only streams and the backing indexes that make them up.
Ingest pipelines
Stored steps that transform documents on their way into the cluster.
Lifecycle policies
Stored rules that move indexes through hot, warm, cold, and delete stages.
Snapshot repositories
Definitions of where snapshots are stored. Secrets for these places are kept elsewhere, not in the state.
Stored scripts
Reusable scripts kept by name so that requests can refer to them.
The routing table
The routing table is the part that answers “where is everything?” For each index, it lists every shard, and for each shard, every copy: whether it is the primary or a replica, which node holds it, and which condition it is in. The main conditions are unassigned (no node yet), initializing (being set up on a node), started (ready for use), and relocating (moving to another node). Chapter 8 explores how this table drives cluster health and how the master fills it.
Think of a theatre’s seating plan. The metadata is the description of the show: title, length, and rules. The routing table is the seat chart: seat by seat, who is sitting where, and which seats are still empty. When a guest moves, only the seat chart changes.
Blocks
Blocks are restrictions recorded in the state. A block at the cluster level might say that there is no master yet, so no cluster-wide changes are possible. A block at the index level might say that the index is read-only, for instance because a disk ran very low on space. Because blocks live in the state, they are seen by every node at the same moment.
Custom sections
Features such as index lifecycle management, snapshots, and data streams add their own sections to the state. These are called custom sections. They are the reason the state grows when you use many features at once, and one of the reasons the exact content differs between versions.
What is not inside
| Thing | Where it really lives |
|---|---|
| The documents you index | In shards, on the disks of data nodes |
| Search results and caches | In memory on individual nodes, not shared |
| Security users, roles, and API keys | In protected internal indexes, not in the cluster state |
| Passwords and secrets for repositories | In each node’s secure keystore |
| Live statistics such as CPU or heap | Collected on demand from nodes, not in the state |
| The list of documents in a shard | Inside the shard’s own files |
Why the contents matter
Every item above is copied to every node and re-sent whenever it changes. A thousand templates, ten thousand indexes, and hundreds of thousands of fields all sit in this one structure. That is why the discipline of keeping the state lean, discussed in Chapter 13, is one of the most important habits in running a large cluster.
The precise layout of the cluster state is an internal detail. It can change between versions, so tools and scripts should not depend on its exact shape. Use it to look and learn, not as a permanent interface for programs.
6Internal Working: The Master Queue and the Two-Step Publish
This is the heart of the subject. Here is exactly how one change becomes the new truth on every machine.
flowchart TD
T["Task arrives in the master queue: for example create index"] --> B["Master batches tasks of the same kind"]
B --> N["Master computes the next cluster state: version plus one"]
N --> P["Publish phase: send the state or a diff to every node"]
P --> Q{"Did a majority of voting nodes accept and save it?"}
Q -- No --> F["Update fails: the master may step down"]
Q -- Yes --> C["Commit phase: tell nodes the state is official"]
C --> A["Every node applies the new state"]
A --> K["Master acknowledges the request to the caller"]
Step one: the queue
Every request that changes the cluster becomes a small task placed in a queue on the master. Creating an index, deleting one, updating a mapping, changing a setting, reporting that a shard has started, and reacting to a lost node are all tasks of this kind. Each task has a priority. Reactions to failures and shard-started reports are urgent, because delays would leave the cluster in a weakened condition. Routine administrative changes have normal priority, and background housekeeping has low priority.
Think of an emergency dispatcher with a single phone line. Calls about fires are answered before calls about a noisy neighbor. If a hundred noisy-neighbor calls arrive at once, they wait, but a fire call jumps the line.
Step two: batching and computing
A single worker thread on the master takes tasks from the queue. To save effort, it groups tasks of the same kind and processes the whole group at once, producing one new state instead of many. For example, a hundred reports of the form “shard started” can be turned into a single new state that marks all hundred shards as started. This batching is a large part of why a master can survive bursts of activity.
The worker never edits the current state. It builds a new, separate state with the changes applied and a version number one higher. Because states are never edited in place, every node can keep using the old picture until the new one is officially accepted.
Step three: publishing
The master sends the new state to every node in the cluster. To save network traffic, it usually sends only a diff, meaning a description of what changed since the previous version. A node that has the previous version can apply the diff. A node that does not, perhaps because it just joined or missed an update, cannot, and the master falls back to sending the complete state. States are also compressed before they travel.
When a textbook publishes a new edition, it can send readers a sheet of corrections for the old edition. Readers who have the old edition fix their pages. A reader who lost the old book needs a whole new copy.
Step four: the vote
When a node receives a new state, it does not use it right away. First it checks that it comes from the master it currently follows, in the current term. Master-eligible nodes also write the new state to their disks. Only then do they answer “accepted.” The master counts the answers. When a majority of the voting nodes have accepted, the state is safe: even if the master crashes at that exact moment, a majority holds the new state, and any future master will find it.
Step five: the commit and apply
Once a majority has accepted, the master sends a commit message. It says, in effect, “this state is now official.” Each node then applies the state: it swaps its in-memory copy for the new one and lets the rest of the node react. A data node might create a shard, delete an index it no longer needs, or start a recovery. Component after component is notified in a fixed order.
Step six: the answer
The master answers the original request. Many administrative operations wait until enough nodes have applied the change, within a time limit, before saying “acknowledged.” If the time limit passes first, the operation may report that it was not acknowledged, even though the change did happen. That is why an unacknowledged answer does not always mean failure, and why you should look at the state, not only at the response.
| Time limit | What it controls | Typical default |
|---|---|---|
| Master timeout on a request | How long a request waits for the master to pick it up | 30 seconds |
| Acknowledgment timeout on a request | How long the caller waits for nodes to apply the change | 30 seconds |
| Publish timeout | How long the master waits for a new state to spread | 30 seconds |
| Follower lag timeout | How long a node may stay behind before it is removed | 90 seconds |
The values above are documented defaults for recent versions and can be changed, so check the documentation of the version you run.
One update at a time
The master publishes one new state at a time. It does not start the next update until the current one has been handled. This is what keeps versions in a simple, strict order, and it is also the reason that a very slow update, or a very slow node, can delay everything behind it. The queue of waiting tasks then grows, which is one of the clearest warning signs you can watch for.
Indexing and searching documents do not create cluster state updates. They only read the state to find the right shards. That is why a cluster can be slow to create an index and yet still search at full speed.
7Cluster Coordination: Elections, Quorum, and Split Brain
A shared map is only as trustworthy as the process that chooses its writer. Here is how the cluster chooses and how it stays sure.
Forming a cluster
When a brand-new cluster starts for the first time, the master-eligible nodes must agree on who is in the first voting group. A setting that lists the initial master-eligible nodes is used once, only on the very first start, to bootstrap the cluster. After that, the cluster remembers its voting group on disk and adjusts it automatically as master-eligible nodes come and go. The setting must be removed after the first start, because leaving it in place could allow an accidental new cluster to form if a node is ever restarted in an unexpected way.
Electing a master
Master-eligible nodes watch for a master. If a node cannot find one, or the current master fails its checks, the node starts a pre-vote. This is a polite question to the others: “would you vote for me if I stood for election?” Only if enough nodes say yes does the node actually start an election, which raises the term number. This trick prevents a node with a flaky network connection from repeatedly disrupting a healthy cluster with pointless elections. In an election, each node votes for at most one candidate per term. A candidate that receives votes from a majority of the voting group becomes the master.
Before a club member calls a formal election, she quietly asks around: “If I ran, would you back me?” If nobody would, she does not bother everyone with a full vote. A club that always holds a vote whenever one member has a bad phone signal would never get anything done.
The voting configuration and quorum
The voting configuration is the set of master-eligible nodes whose votes count. A quorum is more than half of that set. With three voters, a quorum is two. With five voters, a quorum is three. Both elections and cluster state updates require a quorum. The cluster keeps the voting configuration as an odd number where possible, by leaving out one node from an even-sized group, because an even group tolerates no more failures than the next smaller odd group.
| Master-eligible nodes | Votes needed | Failures survived | Comment |
|---|---|---|---|
| 1 | 1 | 0 | Fine for development, no resilience |
| 2 | Effectively 1 voter counts | 0 | No better than one, so avoid |
| 3 | 2 | 1 | The usual production minimum |
| 4 | Effectively 3 voters count | 1 | Same as three, wastes a node |
| 5 | 3 | 2 | For larger or more critical clusters |
Why split brain cannot happen now
Suppose a network problem cuts a cluster of three master-eligible nodes into a group of two and a group of one. The group of two still holds a majority, so it can elect a master, accept updates, and continue. The lone node cannot reach a majority, so it cannot elect itself, and it cannot commit any state. It steps aside and waits. When the network heals, it rejoins and catches up. At no point are there two masters both making valid decisions, because two groups cannot both hold a majority of the same voting set.
flowchart LR
subgraph Left["Majority side: 2 of 3 voters"]
A["Master-eligible node 1"]
B["Master-eligible node 2"]
end
subgraph Right["Minority side: 1 of 3 voters"]
C["Master-eligible node 3"]
end
A --- B
Left -. "network partition" .- Right
B --> W["Continues: elects or keeps a master and commits updates"]
C --> X["Stops: cannot reach a majority, so no cluster changes"]
Fault detection: how nodes know something is wrong
Two kinds of regular checks keep the cluster honest. The master pings each follower to make sure it is alive and still following it. Each follower pings the master to make sure it is still there. These pings are frequent, about once per second by default, and a node is declared lost only after several failed attempts in a row, so that a single dropped message does not cause a false alarm. When the master decides that a node is gone, it removes it from the state, which triggers the reactions described in Chapter 8.
Imagine team members calling out “still here!” every second. If one person misses three calls in a row, the captain assumes something has happened and updates the team list. If it was only a bad connection, the person can rejoin, but the map has to be updated again.
The lag detector
A node that is alive but very slow can hold everything up, because it may not apply new states in time. A lag detector watches for nodes that stay behind for too long, by default ninety seconds after a state has been committed. Such nodes are removed from the cluster, and they may rejoin once they are ready. This protects the cluster from a single struggling machine.
Dedicated master nodes
In a large cluster, master-eligible nodes should be dedicated to that job. A master that is also a busy data node can be slowed by heavy searches or long garbage collection pauses, and a slow master means slow cluster changes and, in the worst case, needless elections. Dedicated masters can be modest machines, because their work is bookkeeping, but they need reliable memory, disk, and network. A special kind of node can be given only a vote and never become master, which is useful as a low-cost tie-breaker in a third location.
When retiring master-eligible nodes, remove them slowly, a few at a time, and let the cluster adjust its voting group between steps. Taking away half or more of the voters at once can leave the cluster unable to form a majority and unable to recover without special tools.
8The Routing Table, Shard Allocation, and Cluster Health
The part of the state that changes most in real life is the seating chart of shards. Learn how it is decided and how it turns into the health colors you see.
How a shard copy moves through conditions
Unassigned
The shard copy exists on paper, in the routing table, but no node holds it. This is where every new shard copy starts.
Initializing
The master has chosen a node. That node is creating the shard, or copying its data from another copy, but it is not ready yet.
Started
The shard is ready. It can serve reads, and if it is a primary, accept writes.
Relocating
The shard is being moved from one node to another, for balancing, disk space, or maintenance. The old copy keeps serving until the new one is ready.
Health colors come from the routing table
flowchart TD
A["Read the routing table"] --> B{"Is every primary shard assigned and started?"}
B -- No --> R["RED: some data is unavailable"]
B -- Yes --> C{"Is every replica shard assigned and started?"}
C -- No --> Y["YELLOW: data available but not fully protected"]
C -- Yes --> G["GREEN: all copies are ready"]
Think of a school trip with one bus and one spare bus for every route. Green means every bus and every spare is ready. Yellow means every route has a working bus but some spares are missing. Red means some route has no working bus at all, and the children on that route cannot travel.
How the master decides where shards go
Whenever the routing table changes in a way that leaves unassigned shards, or when balance is poor, the master’s allocation service runs. It considers each unassigned shard copy and asks a panel of rule checkers, called deciders, whether a given node is allowed to hold it. The deciders look at many things.
Same-shard rule
Two copies of the same shard must never live on the same node, because one crash would then kill both.
Disk watermarks
Nodes with too little free disk are avoided, and at very low levels new shards are refused and writes may be blocked.
Awareness
Copies can be spread across zones or racks, so that losing one zone does not lose every copy.
Filters and tiers
Rules that keep certain indexes on certain nodes, such as fast hot nodes or cheaper warm nodes.
Throttling
Limits on how many recoveries a node performs at once, so that moving data does not swamp the cluster.
Shard count limits
A cap on how many shards one node may hold, to protect memory and the state itself.
Trusting the right copy: in-sync tracking
Suppose a primary shard fails. The cluster must promote a replica. But which replica is safe? One that missed recent writes would silently lose data. To prevent this, the metadata records, for every shard, the set of copies that are known to be fully up to date. This is called the in-sync set. Only a member of the in-sync set may be promoted to primary. A stale copy that comes back after a long absence must first catch up, and it is never trusted blindly. This small piece of bookkeeping inside the state is what protects data during failures.
Two students copy the same class notes. One misses a week of lessons because she was ill. When the teacher needs a master copy for the class, she picks the student who attended every lesson, and asks the other to catch up first. The list of students with complete notes is the in-sync set.
When a node leaves
If the master decides that a node is gone, it removes the node from the state, and shard copies that lived there become unassigned. For lost primaries, an in-sync replica is promoted. For lost replicas, the master could immediately start rebuilding them elsewhere. But a node that has merely restarted is likely to come back within minutes, and rebuilding many gigabytes of data would be wasted effort. Therefore, by default, the master waits about one minute before starting to rebuild, a delay controlled by a setting on each index. If the node returns within that time, its existing data is reused, and recovery is quick.
Rebalancing
Over time, shards may end up unevenly spread. The master occasionally moves shards to even out both the number of shards per node and the disk use, always with limits on how many moves happen at once. Balancing is polite work that gives way to more urgent tasks, and it can be paused by a setting during delicate operations such as rolling upgrades.
When a shard stays unassigned, the allocation explanation endpoint tells you which decider said no, and for which node. It is one of the most useful diagnostic tools, because it turns a mystery into a specific reason.
9Data Flow and Lifecycle: How the State Changes Over Time
Follow the state through a few ordinary events, and its behavior becomes easy to predict.
Event one: an index is born
flowchart LR
S1["Create index request reaches the master"] --> S2["State v1: index metadata added, shards unassigned"]
S2 --> S3["Allocation: master picks nodes for each shard copy"]
S3 --> S4["State v2: shards marked initializing"]
S4 --> S5["Data nodes create shards and report started"]
S5 --> S6["State v3: shards marked started"]
S6 --> S7["Cluster health turns green"]
The picture shows an important truth: even a simple action like creating an index produces a chain of state versions. First the master adds the index’s definition and its shard entries, all unassigned. Then allocation chooses nodes and produces another version with the shards initializing. Data nodes then do the physical work of creating the shards and report back. Each of those reports becomes a task, and the master batches them into a further version that marks the shards as started. Only then does the health turn green.
Event two: a new field appears
When a document arrives with a field the index has never seen, and dynamic mapping is on, Elasticsearch must add that field to the mapping. The mapping lives in the cluster state, so the data node that saw the new field sends a mapping update request to the master. The master builds a new state with the extended mapping and publishes it. Indexing of that document waits until the update is accepted. If a stream of documents keeps introducing new field names, the master is asked again and again, and each request costs a full round of publish and commit.
Imagine a shared spreadsheet where every new column must be approved by the class president and announced to the whole class before anyone may type in it. A student who invents a new column for every single entry would keep the president busy all day and slow everyone down.
Event three: a node joins or leaves
A new node contacts the master, passes some safety checks, such as having the same cluster identifier and a compatible version, and is added to the node list in a new state. Shards may then be assigned to it. When a node leaves, whether by choice or by failure, the master removes it from the list and the consequences of Chapter 8 follow: promotion of replicas, delayed rebuilding, and rebalancing.
Event four: rollover and lifecycle actions
Lifecycle policies and data stream rollovers create and delete indexes on a schedule. Each of these actions is a state change: a new index appears, an alias or data stream definition is updated, an old index is deleted. A busy system with many data streams may therefore perform a steady stream of small updates all day. That is normal, and it is one reason the master should never be starved of resources.
Event five: an index is deleted
Deleting an index removes its metadata and its routing entries from the state. Data nodes that hold its shards see the new state and delete the files from their disks. The cluster also records a small tombstone entry, a note that the index was deleted, so that leftover copies on a node that was absent during the deletion are not mistaken for a live index when that node returns.
Event six: settings change
Changing an index setting, adding an alias, or updating a cluster setting is one state update each. Because the change is atomic, every node switches to the new behavior at the moment it applies the new state, which is why nodes can agree about rules such as which disk thresholds are in force.
Summary of what triggers updates
| Action | Changes the state? |
|---|---|
| Indexing a document into an existing field | No |
| Searching | No |
| Indexing a document with a new field | Yes, a mapping update |
| Creating or deleting an index | Yes, several updates |
| Changing a setting, alias, or template | Yes |
| A node joining or leaving | Yes |
| A shard moving or starting | Yes |
| Taking or finishing a snapshot | Yes, snapshot progress is recorded |
10Persistence and Recovery: Surviving Restarts and Disasters
A map kept only in memory would vanish at the first power cut. Here is how the cluster remembers itself.
What is saved to disk, and where
The state is saved on disk, but not by every node in the same way. Master-eligible nodes save the cluster-wide metadata, including the metadata of every index. Data nodes save the metadata of the indexes for which they hold shards, so that they know what their own files mean. Nodes that are neither master-eligible nor data nodes save nothing about it. The routing table is not saved, because it can be rebuilt from what nodes report when they start.
The town hall keeps the full copy of the town register in a fireproof safe. Each shop keeps a small card about its own building. The seating chart of who is sitting where today is not filed anywhere. It is simply rebuilt each morning from what people report.
A full cluster restart
When every node stops and starts again, the cluster must rebuild its state from disk. The master-eligible nodes elect a master. Until this has happened and the saved metadata has been recovered, a cluster-wide block is in place, and requests fail with a message that the state has not yet been recovered. Then nodes report the shards they hold, the master rebuilds the routing table, and shards are started.
A few gateway settings let you tell the cluster how many data nodes to wait for before it starts assigning shards. If the master begins assigning shards as soon as the first two data nodes show up, and the rest arrive minutes later, it will waste effort copying data that would have been found in place. Waiting for most of the expected nodes, for a limited time, avoids this.
Losing the master
If the master fails, and a majority of voters remain, a new master is elected within seconds. It loads the last committed state it knows, which is guaranteed to be the newest because a majority had accepted it. During those seconds, changes to the cluster are not possible, but reading and writing documents on existing shards keeps working, because that traffic does not need the master.
Losing most of the masters
If more than half of the master-eligible nodes are lost for good, the cluster cannot form a majority. It cannot elect a master, and it cannot change its state. The right response is to bring the lost nodes back, if at all possible. Only if they can never return, there is a last-resort command-line tool that ships with Elasticsearch which can reset the voting group so that the surviving nodes can form a new cluster. It is dangerous, because it may lose recent changes to the state, and it must be used only with the documentation open and with backups in hand.
Unsafe recovery tools exist for the worst days. They can bring a cluster back, but they can also discard cluster metadata, and indexes may become unknown to the cluster even though their files still exist. The best protection is prevention: three or more dedicated master-eligible nodes, spread over different failure zones, and regular snapshots.
Dangling indexes
Sometimes a data node holds files for an index that the cluster state does not list. This can happen if the node was away while the index was deleted, or after certain disasters. Such an index is called dangling. Elasticsearch does not add it back on its own, because that could bring back deleted data. An operator may inspect the dangling indexes and choose to import or delete each one, and must explicitly accept the risk of data loss when importing.
Imagine a book found on a library shelf that is not listed in the catalog. The librarian does not automatically add it, because it might have been withdrawn on purpose. Someone has to look at it and decide whether to add it to the catalog or to remove it.
Snapshots and the global state
A snapshot can optionally include the global cluster state: persistent settings, templates, lifecycle policies, and similar metadata, in addition to the indexes’ own data. Restoring this global state into a new cluster can rebuild a working environment, but it should be done thoughtfully, since it can overwrite settings and templates that already exist. Think of snapshots as the real insurance policy for the state, because a single cluster’s disks are not enough to protect against every disaster.
A disaster recovery checklist
Know how many masters you can lose
Write down the size of your voting group and how many failures it tolerates.
Take regular snapshots
Include the global state if you want to rebuild templates, policies, and settings, and test restores in a safe environment.
Keep configuration in code
Store templates, policies, and pipelines in source control, so they can be re-applied without a snapshot.
Practice the drill
Once a year, rehearse the loss of a master node and, in a test cluster, the loss of a majority.
11Reading the Cluster State: The Windows You Can Look Through
You cannot manage what you cannot see. Elasticsearch gives you several windows onto the state, each showing a different slice.
| Window | What it shows | When to use it |
|---|---|---|
| Cluster health | The color, counts of nodes, shards, unassigned shards, and pending tasks, and how long the oldest task has waited | First look at any problem, and in dashboards and alerts |
| Cluster state dump | The full state, or chosen sections of it, such as nodes, metadata, routing table, blocks | Debugging and learning, in filtered form |
| Pending tasks | The queue of changes waiting on the master, with priorities and waiting time | When changes feel slow or stuck |
| Allocation explanation | The reasons a shard is unassigned or has not moved | When health is yellow or red |
| Compact listings | Tabular views of nodes, shards, the master, and pending tasks | Quick checks from a terminal |
| Node statistics for discovery | How many states were published as diffs or as full states, and how long updates took, in newer versions | Tracking the cost of state updates over time |
| Cluster settings | Persistent settings currently stored in the state, and optionally the defaults | Auditing what has been changed |
The state dump
The full state dump is the most direct window. You can ask for the whole state or only for parts of it, such as the metadata or the routing table, and you can limit it to certain indexes. On a large cluster, the full dump can be enormous, tens or hundreds of megabytes, and requesting it repeatedly puts load on the node that serves it. Always ask for the smallest slice that answers your question.
Elasticsearch’s own documentation describes the state dump as a debugging aid. Its format is internal and can change between versions. Do not build production monitoring or automation on parsing it. For programs, use the health, statistics, and management endpoints, which are designed to stay stable.
A power company lets you see your electricity use on an app. It does not hand you the raw log of the whole power grid. The full log would be huge and confusing, and the format might change next month. The state dump is that raw log: useful to an engineer, but not a good foundation for an app.
How to read a dump
Start with the identity
Note the cluster identifier, the version, and the elected master. If nodes report different masters or very different versions, you have a coordination problem.
Check the node list
Are all the expected nodes present, with the roles you intended?
Look at the blocks
Any cluster-wide or index-level block explains why certain requests are refused.
Read the routing table for the index in question
See which shard copies are unassigned or initializing, and on which nodes the others sit.
Only then open the metadata
Mappings and settings are long. Read them last, and only for the index you care about.
Comparing what nodes believe
Because every node holds its own copy of the state, you can, in a troubleshooting session, ask several nodes for their version of the state and compare the version numbers and the master. In a healthy cluster, they match, apart from tiny delays right after an update. A node that is stuck on an old version is a strong lead: it is probably slow, overloaded, or partly disconnected.
Health with patience
The health endpoint can also wait. You can ask it to hold the answer until the cluster reaches a certain color, or until a number of shards are moving, or until there are no more tasks waiting, for up to a time limit. Scripts that perform maintenance use this to pause safely between steps, instead of guessing how long to sleep.
12Cluster Settings: Rules Stored in the State
Some of the rules that shape the cluster are kept inside the state itself. This makes them easy to change, and easy to forget.
Where settings can live
Elasticsearch settings come from several places. Some are written in configuration files on each node and can only be changed by restarting that node; these are called static settings. Others can be changed while the cluster runs; these are dynamic settings, and they are stored in the cluster state so that all nodes see them at the same moment. Dynamic cluster settings can be marked persistent, meaning they survive a full restart, or transient, meaning they were meant to disappear after one.
| Source | Survives full restart? | Changed by | Priority |
|---|---|---|---|
| Transient cluster setting | No, by design | Settings API | Highest |
| Persistent cluster setting | Yes, stored in the metadata | Settings API | Next |
| Node configuration file | Yes, it is a file | Editing the file and restarting | Next |
| Built-in default | Not applicable | Only by a new version | Lowest |
Recent versions discourage transient settings, because their behavior during restarts and failures has surprised many operators, and recommend persistent settings or configuration files instead. Check the documentation for your version.
Think of house rules. Some are printed on the family fridge and stay the same for years (persistent). Some are written on a sticky note for today only (transient). A rule painted on the wall when the house was built (a static file) needs a builder to change. When two rules conflict, the sticky note wins for today.
Examples of settings that shape the state
Allocation and rebalance switches
Turn shard allocation and balancing on, off, or limited to primaries. Used in maintenance and easily forgotten afterward.
Disk watermarks
Thresholds at which nodes stop receiving new shards, start shedding them, and finally make indexes read-only.
Shard limits per node
A cap on the number of shards each node may hold, protecting the state and memory.
Destructive action protection
A setting that requires exact index names for deletion, so a wildcard cannot wipe out everything by accident.
Recovery limits
How many recoveries may run at once, and how much bandwidth they may use.
Timeouts
Publish and lag timeouts and other coordination settings, which are advanced and rarely need changing.
Changing and removing a setting
A dynamic setting can be updated with the settings API. To remove a setting and return to its default, you set it to nothing, which makes the cluster forget it. Each change is one state update, applied atomically on every node. Because these changes are stored in the state, they are also part of what a snapshot with global state would carry, so a restored cluster may inherit them, sometimes to the surprise of the person who restores it.
Keep settings in a record
A cluster with many hand-changed persistent settings becomes a puzzle: nobody remembers why a rule was added. A better habit is to keep a written list or a configuration file in source control, listing every non-default setting, the reason, the person who set it, and the date. Review this list every quarter and remove what is no longer needed. Maintenance switches, such as disabling allocation during an upgrade, should have an entry in the runbook that also says how to switch them back.
A common incident: allocation was switched off for a rolling restart, the restart finished, and nobody switched it back. Weeks later a node fails, and its shards never move because the cluster is still forbidden from assigning them. Put “restore allocation” in the checklist, and alert if unassigned shards persist while allocation is limited.
13Performance and Scalability: When the Map Gets Too Big
The cluster state is small when a cluster is small. At large scale, it becomes the thing that limits how far the cluster can grow.
Documents scale beautifully: add nodes, spread shards, and capacity grows. The cluster state does not scale in the same way. Every node must hold all of it, and every update must reach every node. So its cost grows with the number of nodes, and with the size of the state, at the same time. The cluster state is therefore the part of Elasticsearch where “too many small things” causes the most trouble.
What makes a state large
Too many indexes
Each index carries its own settings, mappings, and aliases. Tens of thousands of tiny indexes bloat the state.
Too many shards
Each shard copy adds a routing entry, and every shard adds memory and coordination work on the node that holds it.
Too many fields
Mappings grow with every field. A mapping explosion, where documents keep inventing new field names, is a classic cause.
Identical mappings
Thousands of indexes that share the same mapping still carry a copy of it each, in the state.
Many templates, pipelines, and policies
Large collections of stored definitions add up, especially when they are generated automatically.
Frequent updates
Even a modest state becomes a burden when updates are constant, because every update is sent to every node.
A numbers walkthrough
Let us use invented numbers to feel the cost. Suppose the cluster state is 50 megabytes and the cluster has 100 nodes. If every update sent the whole state, one update would move 5 gigabytes across the network, and a hundred updates per minute would need hundreds of gigabytes of traffic per minute just for bookkeeping. Diffs make this survivable, because a typical update changes only a few kilobytes, so the cost is small. But a node that misses an update, or joins the cluster, needs a full copy, and a burst of restarts can cause many full transfers at once.
Now consider the memory cost. Every node keeps the whole state in its heap, and sometimes several versions at once, while it applies a new version. A 50-megabyte state might take several times that in memory once it is expanded into objects. On a small node with a modest heap, that is a noticeable share of the memory, taken before a single search runs.
Imagine a school where every teacher must carry the complete list of all students in every class, and every change in the list must be announced to all teachers. In a small school that is trivial. In a school of ten thousand students with new enrolments every minute, the teachers spend their time reading announcements instead of teaching.
The master as a bottleneck
All state changes pass through one thread on one machine. Whatever the size of the cluster, the master can only process so many updates per second, and each one takes longer when the state is larger, because building and serializing the new state costs time in proportion to its size. When updates arrive faster than the master can finish them, the queue of pending tasks grows, and the effects become visible: index creation takes longer, shards take longer to start, and recovery after failures slows down.
Guard rails Elasticsearch gives you
- Shard limits per node. A default cap on the number of shards each data node may hold protects nodes and the state from unbounded growth. Do not raise it without good evidence.
- Field limits per index. A cap on the number of fields in an index stops runaway mappings. Raising it is a warning sign, not a solution.
- Slow-task warnings. The master writes a warning to its log when a state update takes unusually long, which points to the cause.
- Diffs and compression. Built-in efficiency features that keep ordinary updates small.
How to keep the state lean
Use fewer, bigger indexes
Aim for shards in the tens of gigabytes for search-oriented data, and avoid one index per customer or per day when the volume is small. Use rollover and lifecycle policies to keep indexes at a healthy size.
Merge tiny shards
Shrink or reindex collections of tiny indexes into a smaller number of larger ones.
Control the mapping
Define mappings up front. Turn off dynamic mapping for unknown fields, or use a special field type built for arbitrary key and value maps.
Delete what is not needed
Remove unused indexes, old templates, dead pipelines, and stale policies.
Give the masters enough resources
Dedicated master-eligible nodes with adequate memory, fast disks, and stable networks make each update faster.
Measure regularly
Track state size, update time, and pending tasks, so that growth is noticed early.
The many-clusters alternative
When a single cluster truly needs to hold an enormous number of indexes, splitting the workload across several smaller clusters is often wiser than growing one giant state. Cross-cluster search can still query them together when needed. Each cluster then has its own smaller state, its own master, and its own limits, and a problem in one does not spread to the others.
If creating an index takes seconds instead of milliseconds, or if pending tasks regularly wait for many seconds, the cluster state is telling you that the cluster has too many small things in it. Fix the shape of the cluster, not the timeout.
14Advantages, Disadvantages, and Trade-offs
Every design choice carries a price. Here is the honest balance sheet of having a single, shared cluster state.
Advantages
- One shared truth: every node routes requests the same way.
- Simple to reason about: one writer, strict versions, no rival maps.
- Safe under failure: majority voting prevents split brain.
- Fast reads of the map: every node has it in memory, with no lookups over the network.
- No external service needed to run the cluster.
- Atomic changes: settings and definitions switch on everywhere at once.
- Rich diagnostics: health, allocation reasons, and pending tasks all come from it.
Disadvantages
- Every node stores all of it, so large states cost memory everywhere.
- Every change must reach every node, so updates cost more as the cluster grows.
- A single writer thread limits how many changes per second are possible.
- A slow node or slow master can delay every change.
- Mapping mistakes, such as field explosions, hurt the whole cluster, not just one index.
- Loss of a majority of masters freezes the cluster’s ability to change.
- The internal format is not a stable interface for tools.
| Trade-off | Leaning toward convenience | Leaning toward stability |
|---|---|---|
| Index design | One index per tenant or per day: simple to reason about, many small indexes | Shared, larger indexes: fewer state entries, more careful design |
| Dynamic mapping | On: any document works, risk of field explosion | Strict or off: predictable state, needs defined mappings |
| Master roles | Combined with data: fewer machines, master competes for resources | Dedicated masters: more machines, steadier updates |
| Number of master-eligible nodes | Three: minimum resilience, lowest cost | Five: survives two failures, more coordination |
| Cluster size | One giant cluster: one place to manage | Several smaller clusters: smaller states, more places to manage |
| Recovery delay | Short: replicas rebuilt sooner, wasted work if the node returns | Longer: avoids needless copying, longer time with less protection |
A town with one official register is easy to run and hard to argue about. But as the town grows to a million people, the register becomes too thick to carry and too slow to update. Some towns then split into districts, each with its own register. The trade-off is between the simplicity of one book and the scale of many.
How strict should you be?
| Situation | Recommended stance |
|---|---|
| Small development cluster | Relaxed: one node is fine, do not over-engineer |
| Small production cluster | Three master-eligible nodes, which may also hold data, and sensible index sizes |
| Large production cluster | Dedicated masters in three zones, strict mappings, shard limits, monitoring of state size |
| Multi-tenant platform with many customers | Very strict: shared indexes, limits on fields and shards per tenant, possibly several clusters |
| Data that cannot be recreated | Conservative: snapshots with tested restores, five masters, zone awareness |
15High Availability and Reliability
A cluster is only as reliable as its ability to keep the state healthy through failures. Here is how it behaves, and how to prepare it.
What happens in each failure
| Failure | What the cluster does | What users notice |
|---|---|---|
| A data node crashes | Master removes it, promotes in-sync replicas, waits briefly before rebuilding copies | A short yellow period, no data loss if replicas exist |
| The master node crashes | The remaining voters elect a new master and continue from the last committed state | Cluster changes pause for seconds, searching and indexing continue |
| Network splits the voters into majority and minority | Majority side continues, minority side stops changing state | Nodes on the minority side may lose their master and reject changes |
| Majority of master-eligible nodes is lost | No master can be elected, no state changes are possible | Cluster changes fail, existing shards may still serve requests for a while |
| A node becomes very slow | Lag detector removes it after a timeout | Possible slowdown of updates until then |
| The state becomes huge | Updates slow down, queue grows, memory rises | Slow index creation, slow recovery, possibly out-of-memory errors |
| All nodes restart | State reloaded from disk, block until recovered, shards reassigned | A period of unavailability, then recovery |
Think of a ship with several officers who can take the wheel. If the captain falls ill, the officers choose a new captain within moments, and the ship keeps sailing. If most of the officers are lost at once, nobody has the authority to change course, and the ship can only drift until help arrives.
Designing for resilience
- Three or more dedicated master-eligible nodes. An odd number, on reliable machines, separate from the busy data nodes.
- Spread across failure zones. Put master-eligible nodes in three different zones, if possible, so that losing one zone never costs a majority. A small voting-only node in a third location can serve as a tie-breaker.
- Zone awareness for shards. Tell the allocation rules about zones, so copies of a shard live in different zones.
- Replicas everywhere important. At least one replica for indexes you cannot afford to lose, so that a failed node causes no data loss.
- Reliable networking. Low latency and stable links between master-eligible nodes, because the vote depends on them.
- Snapshots. Regular, tested snapshots as the last line of defense.
Rolling restarts and upgrades
To restart nodes one at a time without disruption, the usual approach is to limit shard allocation to primaries before you begin, so that the cluster does not waste effort rebuilding replicas for a node that will be back in minutes. You then restart each node, wait for it to rejoin, and restore normal allocation, waiting for health to return to green before touching the next node. Master-eligible nodes should be restarted with care: never more than one at a time, and only when the cluster is healthy.
Check that the cluster is green
Do not start a rolling restart while shards are unassigned.
Limit allocation
Restrict shard allocation so that stopping a node does not trigger heavy recovery.
Restart one node
Wait for it to rejoin the cluster and show up in the node list.
Restore allocation and wait for green
Let replicas re-attach, then move to the next node.
Confirm at the end
Check that no maintenance setting remains changed.
Slow is the enemy of reliable
Most instability in the state layer does not come from a clean crash. It comes from slowness: a master paused by long garbage collection, a network that drops packets, a disk that stalls while saving the state. Slow masters can lose their followers’ confidence, provoke elections, and cause the cluster to flap between masters. Keep heap sizes sane, watch garbage collection on masters, use fast disks, and avoid running heavy workloads on the same machines as masters.
A cluster stretched across distant data centers with high latency can suffer from slow state updates and frequent election trouble. If you need resilience across regions, consider separate clusters connected by cross-cluster features, instead of a single cluster with distant masters.
16Security Considerations
The cluster state is the control panel of the cluster. Whoever can change it can change almost everything. That deserves careful protection.
Who may look, and who may change
Elasticsearch security separates the right to look at cluster information from the right to change it. Read-only monitoring privileges allow someone to view health and statistics, and often the state dump. Management privileges allow changes: to settings, templates, lifecycle policies, snapshots, and the shape of indexes. Give people and programs only the level they need. A dashboard needs to read. It does not need to change. A deployment tool might need to manage templates, but not the whole cluster.
In a building, everyone can read the fire-exit map on the wall. Only the facilities team may repaint it or move the exits. If a visitor could edit the map, the next fire would go badly.
What the state reveals
The state contains the names of indexes and aliases, the structure of mappings, the addresses of nodes, the layout of shards, and more. This is metadata, not documents, but it can still be sensitive. In a system where index names contain customer names, for instance, the state reveals who the customers are. Limit who can read the full state, and be careful before pasting a state dump into a support ticket or a public forum. Remove names and addresses first.
Keep strangers out of the cluster
A node that joins the cluster receives the whole state. If an attacker could start a node that joins your cluster, they would learn its layout and could receive shard copies, and therefore data. Prevent this by enabling encryption and mutual authentication between nodes, so that only nodes with valid certificates can join, and by restricting network access to the ports that nodes use to talk to each other.
Encrypt node-to-node traffic
Encrypted and authenticated communication between nodes protects the state as it is published.
Restrict who can reach nodes
Only cluster members and trusted clients should be able to open connections to node ports.
Least-privilege roles
Separate roles for reading, for managing templates and policies, and for cluster-wide changes.
Protect destructive actions
Keep the setting that requires exact names for deletions switched on.
Audit changes
Where your subscription allows, log who changed settings, templates, and policies, and when.
Protect the disks
The saved state and the recovery tools live on the master machines. Restrict who can log in to them.
Dangerous power tools
The command-line tools that can rewrite the voting group or reset metadata are extremely powerful, and they work directly on the files of a stopped node. Anyone with shell access to a master-eligible machine could, in principle, misuse them. Restrict shell access, log administrative sessions, and treat the machines that hold the state as sensitive systems.
Bootstrapping safely
The setting used to form a new cluster for the first time should only be present during that first start. Remove it afterward, so that a mistaken restart on a new machine cannot silently create a second cluster with the same name. A good habit is to give each cluster a unique name, which also prevents nodes from accidentally joining the wrong one.
Changes as a control point
Because settings, templates, and policies are all changes to the state, they make a natural place to apply review and approval. Keep these definitions in source control, apply them through a pipeline, and grant direct human access only for emergencies. That way, every important change has a record, a reviewer, and a way back.
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
The cluster state rarely fails suddenly. It usually gives warnings first. These are the signals worth watching.
| Metric or signal | What it tells you | Warning sign |
|---|---|---|
| Cluster health color | Whether primaries and replicas are all assigned | Yellow or red for longer than a planned window |
| Number of unassigned and initializing shards | How much recovery work is pending | Unassigned shards that do not decrease |
| Number of pending tasks | Changes waiting for the master | Tasks queued for many seconds |
| Longest task waiting time | How long the oldest change has waited | Any sustained rise |
| Cluster state update time | How long a state update takes, in newer versions | Steady growth over weeks |
| Full states versus diffs published | How often nodes needed a complete copy | Many full states or incompatible diffs |
| Size of the state | How heavy the state is on every node | Doubling over a few months |
| Number of indexes, shards, and fields | The main drivers of state size | Growth outpacing the data |
| Master changes and elections | Stability of coordination | Frequent elections, master flapping |
| Node count versus expected | Membership stability | Nodes joining and leaving repeatedly |
| Heap and garbage collection on masters | Resource health of the writer | Long pauses, heap near its limit |
| Blocks on indexes or the cluster | Restrictions currently in force | Read-only blocks after disk warnings |
Reading the patterns
Green, empty queue, stable master
Updates are fast, tasks do not wait, no unexpected elections. Nothing to change.
Short bursts of pending tasks
Normal after a restart or a rollover. Watch that the queue clears quickly.
Long-waiting tasks, slow index creation
The master cannot keep up. Suspect a large state, too many updates, or a starved master machine.
Frequent master changes
Look for network trouble, long pauses on the master, or too few resources on master-eligible nodes.
State size climbing steadily
Something keeps adding indexes, shards, or fields. Find the source before it becomes an incident.
Yellow or red with no movement
Ask the cluster why the shard is unassigned. A decider is saying no, such as disk space or a filter.
Logs that help
The master’s log tells the story of the cluster. It records elections, nodes joining and leaving, and warnings when a state update or a task takes too long. Warnings about lagging nodes name the node that fell behind, and how far. Read the master’s log first when the cluster behaves oddly, and keep logs long enough to investigate problems that appeared days ago. Ship them to a central place, so that they survive the loss of a machine.
A troubleshooting playbook
Ask for the health
Note the color, the numbers of unassigned shards, and the number and waiting time of pending tasks.
Identify the master
Confirm that all nodes agree on who the master is. If they do not, look at network and coordination logs.
Look at the pending tasks
See which kinds of tasks are waiting, and whether one type dominates, such as mapping updates or shard-started reports.
Ask why shards are unassigned
Use the allocation explanation, and read the reason, which will name the decider that refused.
Check the resources of the master
Heap, garbage collection, disk, and network. A stressed master explains most slow-update problems.
Measure the state
Compare the number of indexes, shards, and fields with your history. Look for sudden jumps.
Fix the cause, not the symptom
If a runaway process creates indexes or fields, stop it first. Then clean up.
Alert on health that stays yellow or red beyond a set time, on pending tasks waiting longer than a few seconds, on repeated master elections, on the state growing faster than expected, on the number of shards per node approaching its limit, and on maintenance settings that remain changed after the maintenance window ends.
18Design Patterns and Anti-patterns
Good habits keep the state small and calm. Bad habits are behind most cluster-wide slowdowns.
Patterns that work
Rollover by size, not by calendar
Create a new index when the current one reaches a healthy size, instead of one per hour or per day regardless of volume. This keeps indexes and shards large enough to be worth their state entry.
Templates for everything
Every new index starts with a defined mapping and settings. No guessing, no surprises, and no field explosions.
Dedicated, odd-numbered masters across zones
Three or five master-eligible nodes, on their own machines, spread over different failure zones.
Lifecycle policies to delete old data
Automatic removal of aging indexes stops the state from growing forever.
Configuration as code
Settings, templates, pipelines, and policies live in source control and are applied by a pipeline, so that the state can be rebuilt and reviewed.
Guard rails on tenants
In multi-tenant platforms, limit the number of fields, indexes, and shards each tenant can create.
Regular state hygiene reviews
A quarterly look at the number of indexes, shards, fields, templates, and policies, and a cleanup of what is unused.
A librarian who files books in sensible sections, removes worn-out ones, and limits how many new sections may be created keeps the catalog short and easy to search. A library where anyone can invent a new section for every single book ends up with a catalog thicker than the books.
Anti-patterns to avoid
What people do
They create one small index for each customer, each day, or each device, resulting in tens of thousands of tiny indexes and shards.
Why it hurts
Each index and shard adds to the state, to every node’s memory, and to the work of every update. The master slows down and recovery takes longer.
Better approach
Use shared, larger indexes with a field or alias to separate tenants, and roll over by size. If separation is needed, consider several clusters instead.
What people do
They leave dynamic mapping fully open and index documents whose field names come from user data, such as identifiers used as keys.
Why it hurts
Mappings explode, each new field triggers a state update, and the state grows until every node is affected.
Better approach
Define mappings, keep dynamic behavior strict where possible, and store arbitrary key and value data in a field type built for it.
What people do
They run master-eligible roles on the same machines as heavy data and search workloads, with no dedicated masters.
Why it hurts
A heavy query or a long garbage collection pause on one machine can stall cluster changes, provoke elections, and cause the master to flap.
Better approach
Use dedicated master-eligible nodes, three or five of them, with steady resources and stable networking.
What people do
They run two master-eligible nodes, believing that two is safer than one.
Why it hurts
Two nodes offer no more resilience than one, and the loss of either node stops cluster changes.
Better approach
Use three, or use one on purpose for a non-critical environment.
What people do
They poll the full state dump every few seconds from a monitoring script and parse it for information.
Why it hurts
Each call makes a node serialize a large structure, which costs CPU and memory. The format can also change in a new version and break the script.
Better approach
Use health, statistics, and compact listing endpoints, which are lightweight and stable. Request only small slices of the state when you must.
What people do
They leave maintenance switches, such as limited shard allocation, in place after the work is done.
Why it hurts
The next failure cannot be repaired automatically, because the cluster is still forbidden from moving shards.
Better approach
Write the restore step into the runbook, and alert on unassigned shards combined with restricted allocation.
What people do
They decommission several master-eligible nodes at the same moment to save money.
Why it hurts
If too many voters vanish before the voting group can adjust, the cluster loses its majority and cannot change its state.
Better approach
Retire masters gradually, one or two at a time, and let the cluster update its voting group between steps.
19Best Practices and Common Mistakes
A short list you could hand to a new teammate on their first day.
Best practices
Three dedicated, odd, spread out
Master-eligible nodes on their own machines, in different zones.
Keep the state lean
Fewer, larger indexes, controlled mappings, regular cleanup.
Define, do not guess
Use templates with explicit mappings and limits on fields.
Track the trio
Pending tasks, state size, and master stability tell you most of what you need.
Configuration as code
Apply settings and definitions through a reviewed pipeline.
Replicas and snapshots
Replicas for availability, snapshots for disasters, tested restores for confidence.
Restore what you changed
Every temporary switch gets a matching restore step and an alert.
Least privilege
Separate reading from changing, and restrict who can reach nodes.
Common mistakes
- Thinking the state contains the data. It contains the map, not the documents. Deleting or corrupting it is a metadata problem with serious consequences, but a small state can sit on top of a huge dataset.
- Ignoring shard counts. Adding shards “for safety” or “for future growth” makes the state larger and every node slower.
- Raising limits to silence warnings. Increasing the field limit or the shard limit hides the symptom and keeps the cause.
- Treating an unacknowledged response as failure. The change may have happened. Look at the state.
- Restarting masters casually. Restart them one at a time, and only when the cluster is healthy.
- Skipping tests of recovery. A snapshot that has never been restored is only a hope.
- Forgetting to remove the bootstrap setting. It should not stay in the configuration after the cluster has formed.
- Assuming transient settings are safe. They can vanish at restarts and cause confusing behavior.
Myths versus facts
| Myth | Fact |
|---|---|
| The cluster state contains all my documents. | It contains only descriptions and locations. Documents live in shards. |
| Every node can change the state. | Only the elected master can, and only with a majority’s agreement. |
| Indexing documents updates the state. | Only when a new field appears, which needs a mapping update. |
| Two master-eligible nodes are safer than one. | They are no safer, since losing either stops changes. |
| Yellow health means data loss. | Yellow means all primaries are available but some replicas are not. |
| If the master dies, searches fail. | Searching and indexing on existing shards continue while a new master is elected. |
| More shards always means more speed. | Beyond a point, more shards make the state heavier and the cluster slower. |
| The state dump is a stable interface. | It is an internal format that can change in any version. |
Treat every index, shard, field, and template as something that every node in the cluster must carry for as long as it exists. Add them because they earn their place, and remove them when they stop earning it.
20Real-World and Industry Examples
Where does the cluster state 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 the details of how they manage cluster state, so the scenarios below are typical patterns for such workloads, not descriptions of anyone’s private configuration.
Online marketplace: a steady, calm state
A marketplace of the size of Amazon or eBay keeps a handful of large indexes for products, orders, and reviews. The state is small and changes rarely, mostly at deployments that update mappings and templates. The team keeps these changes in source control and applies them through a pipeline, so that the map is always reproducible and every change has a reviewer.
Log platform: rollover instead of a flood of tiny indexes
A streaming or ride-hailing service produces a huge amount of logs. Instead of creating an index per hour per service, the team uses data streams with rollover by size, and lifecycle policies that delete old data. The number of indexes and shards stays modest, and the master handles a steady, gentle flow of updates rather than a storm.
Multi-tenant software: tenants must not enlarge the map without limit
A support platform serves thousands of customers. An early design that created several indexes per customer led to a bloated state and slow index creation. The team moved to shared indexes with tenant filters, capped the number of fields per tenant, and split the largest customers to a separate cluster.
Security analytics: heavy ingest and a protected master
A security team ingests very large event volumes from many sources. Masters are dedicated and spread over three zones, so that heavy searches and indexing on data nodes never slow the coordination of the cluster. Monitoring watches pending tasks and master elections closely.
Rolling upgrade at scale
A company upgrades a cluster of hundreds of nodes without downtime. The runbook limits shard allocation, restarts one node at a time, waits for rejoin, restores allocation, and waits for green before continuing. The final step checks that no maintenance settings are left changed. The upgrade takes hours, and users notice nothing.
Recovering from a mapping explosion
A pipeline began to store user-supplied keys as field names. Within days, mappings grew until index creation took minutes and heap use on every node climbed. The team stopped the pipeline, moved the free-form data into a field type designed for it, reindexed the affected data, and added a limit on fields per index as a permanent guard.
In every example, the winning ideas are the same: a small, purposeful state, dedicated and well-placed masters, defined mappings, changes made through review, and constant attention to the pending task queue.
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.
The cluster state is the shared map of an Elasticsearch cluster. It says who is in the cluster, what indexes exist, how they are defined, and where every shard lives. It is written by one elected master, agreed by a majority, and carried in the memory of every node. It is small and quiet when the cluster is well shaped, and it is the first thing to strain when a cluster has too many tiny indexes, shards, or fields.
Key Takeaways
- What it is: a versioned description of nodes, metadata, routing, and blocks. It is the map, not the data.
- Who writes it: only the elected master, through a single queue, building a new immutable version for each change.
- How changes spread: publish a diff or full state, wait for a majority to accept and save it, commit, and apply on every node.
- How safety is kept: majority voting prevents split brain, in-sync tracking protects data, and three dedicated master-eligible nodes across zones give real resilience.
- How health is decided: the routing table drives the green, yellow, and red colors, and the allocation explanation reveals why a shard is stuck.
- What limits growth: every node stores all of it and every change reaches every node, so keep indexes fewer and larger, mappings controlled, and unused definitions removed.
- How to run it well: watch pending tasks, state size, and master stability, keep configuration in code, restore maintenance switches, take tested snapshots, and protect who may read and change the state.