Want to get Elastic certified? Find out when the next Elasticsearch Engineer training is running!
Elasticsearch is packed with new features to help you build the best search solutions for your use case. Dive into our sample notebooks to learn more, start a free cloud trial, or try Elastic on your local machine now.
Elasticsearch enhances the power of Lucene by building a distributed system on top of it, which addresses the issues of scalability and fault tolerance. It also exposes a JSON-based REST API, making interoperability with other systems very straightforward.
Distributed systems like Elasticsearch can be very complex, with many factors that can affect their performance and stability. Shards are among the most fundamental concepts in Elasticsearch, and understanding how these work will enable you to effectively manage an Elasticsearch cluster.
This article explains what primary and replica shards are, their impact on an Elasticsearch cluster, and what tools exist to tune them to varying demands.
Understanding shards
Data in an Elasticsearch index can grow to massive proportions. In order to keep it manageable, every piece of data is kept in an index, and indices are an index split into a number of shards. Each Elasticsearch shard is an Apache Lucene index, with each individual Lucene index containing a subset of the documents in the Elasticsearch index. Splitting indices in this way keeps resource usage under control. An Apache Lucene index has a limit of 2,147,483,519 (2³¹ - 129) documents.
Sometimes, indices need to be moved across nodes for rebalancing purposes. Since this process can be both time- and resource-intensive, the indices should not grow too large, which helps keep the recovery time manageable. Furthermore, as indices are composed of Lucene segments that need to be constantly merged together, it’s important that the segments don’t get too big. For these reasons, Elasticsearch splits the index data into smaller more manageable chunks, called primary shards, that can be more easily distributed across a number of machines. Replica shards are simply an exact copy of a corresponding primary shard and we’ll go over their function later in this article.
Having the right number of shards is important for performance. It is thus wise to plan in advance. When queries are run across different shards in parallel, they execute faster than an index composed of a single shard, but only if each shard is located on a different node and there are sufficient nodes in the cluster. At the same time, however, shards consume memory and disk space, both in terms of indexed data and cluster metadata. Having too many shards (also known as oversharding) can slow down queries, indexing requests, and management operations, and so maintaining the right balance is critical.
The number of primary shards is defined at index creation time for that specific index instance. If you need a different number of primary shards later, you can use the resize APIs—split (more primary shards), shrink (fewer primary shards), or clone (the same number of primary shards with new settings for replicas). These operations copy Lucene segments and avoid a full re-indexing of all documents.When creating an index, you can set the number of primary and replica shards as settings of the index:
(If you don’t specify the number of shards or replicas, the default value of both is 1, as of Elasticsearch 7.0). The ideal number of shards should be determined based on the amount of data in an index. Generally, an optimal shard should hold 10-50GB of data, with fewer than 200 million documents per shard. For example, if you expect to accumulate around 300GB of application logs in a day, having around 10 shards in that index would be reasonable, provided you have a sufficient amount of nodes to host them.
During their lifetime, shards can go through a number of states, including:
- Initializing: An initial state before the shard can be used.
- Started: A state in which the shard is active and can receive requests.
- Relocating: A state that occurs when shards are in the process of being moved to a different node. This may be necessary under certain conditions, for example, when the node they are on is running out of disk space.
- Unassigned: The state of a shard that has failed to be assigned. A reason is provided when this happens, for example, if the node hosting the shard is no longer in the cluster (NODE_LEFT) or due to restoring into a closed index (EXISTING_INDEX_REstoreD).
To view all shards, their states, and other metadata, you can use the following request:
To view shards for a specific index, you can append the name of the index to the URL, for example, sensor:
This command produces an output, such as in the following example. By default, the columns shown include the name of the index, the name (i.e. number) of the shard, whether it is a primary shard or a replica, its state, the number of documents, the size on disk, as well as the IP address and the node ID of the node where the shard is located.
Understanding replicas
While each shard contains a single copy of the data, an index can contain multiple copies of the shard. There are thus two types of shards, the primary shard and a copy, or replica. Each replica of a primary shard is always located on a different node, which ensures high availability of your data in the event of a node failure. In addition to redundancy and their role in preventing data loss and downtime, replicas can also help boost search performance by allowing queries to be processed in parallel with the primary shard, and therefore faster.
There are some important differences in how primary and replica shards behave. While both are capable of processing queries, indexing requests (i.e. adding data to index) must first go through primary shards before they can be replicated to the replica shards. As noted above, if a primary shard becomes unavailable—for example, due to a node disconnection or hardware failure—a replica is promoted to take over its role.
While replicas can help in the case of a node failure,it's important not to have too many of them because they consume memory, disk space, and compute power when indexing. Another difference between the primary shards and replicas is that while the number of primary shards cannot be changed after the index has been created, the number of replicas can be altered dynamically at any time by updating the index settings.
Another factor to consider with replicas is the number of nodes available. Replicas are always placed on different nodes from the primary shard, since two copies of the same data on the same node would offer no protection if the node were to fail. As a result, for a system to support n replicas, there needs to be at least n + 1 nodes in the cluster. For instance, if there are two nodes in a cluster and an index is configured with six replicas, only one replica will be allocated. On the other hand, a system with seven nodes is perfectly capable of handling one primary shard and six replicas.
Optimizing shards and replicas
Even after an index with the right balance of primary and replica shards has been created, these need to be monitored, as the dynamics around an index change over time. For instance, when dealing with time series data, indices with recent data are generally more active than older ones. Without tuning these indices, they would all consume the same amount of resources, despite their very different requirements.
The rollover index API can be used to separate newer and older indices. It can be set to automatically create a new index once a certain threshold—an index’s size on the disk, number of documents, or age—is reached. This API is also useful for keeping shard sizes under control. Since the number of shards can’t be easily changed after index creation, shards will continue to accumulate data if no rollover conditions are met. For older indices that only require infrequent access, shrinking and force-merging an index are two different ways to reduce their memory and disk footprints. The former reduces the number of shards in an index, while the latter reduces the number of Lucene segments and frees up space used by documents that have been deleted.
Primary and replica shards as the foundation of Elasticsearch
Elasticsearch has built a strong reputation as a distributed storage, search, and analytics platform for huge volumes of data. When operating at such a scale, however, challenges will inevitably arise. This is why understanding how primary and replica shards work is so important and fundamental to Elasticsearch, as this can help to optimize the reliability and performance of the platform.
Knowing how they work and how to optimize them is critical for achieving a more robust and performant Elasticsearch cluster. If you are experiencing sluggish query responses or outages regularly , this knowledge may be the key to overcoming these obstacles.
Follow Elasticsearch’s official documentation to learn more about clusters, nodes and shards, how to size your shards, shard allocation and recovery.
This topic is also available as an introductory course on the Elastic Community YouTube Channel.
Last but not least: if you don’t want to worry about nodes, shards, or replicas, you can try out Elastic Cloud Serverless. This Elastic Cloud offering is fully managed by Elastic and automated to scale with your workload. A free trial can help you get familiar with other benefits of the serverless approach.