Performance Tuning and Best Practices
7 min read
1. Sharding Strategy: How Many Shards Do I Need? 🍕
Definition: A shard is a standalone Apache Lucene index that holds a subset of your Elasticsearch index's data. An Elasticsearch index is simply a logical grouping of one or more physical shards.
The Problem: Storing all your data on a single machine does not scale. As your data grows to terabytes, a single node will run out of disk space and memory. Conversely, if you divide your data into too many tiny shards (oversharding), the cluster spends all its CPU and memory just managing the shards rather than answering your queries.
The Solution: A calculated sharding strategy based on data volume limits. This ensures Elasticsearch distributes data evenly without choking the cluster.
Industry Standards for Sharding
In the industry, we do not guess shard counts. We do math. 🧮
- Aim for 10GB to 50GB per shard: This is the sweet spot. A shard smaller than 10GB is usually a waste of cluster overhead. A shard larger than 50GB takes too long to move across the network if a node fails and needs to recover.
- Maximum of 20 shards per GB of Heap Memory: Every shard consumes memory just by existing. If your node has a 30GB heap, it should not hold more than 600 shards.
How to Calculate Your Needs
If you have an index that will hold roughly 200GB of data, and you target 40GB per shard:200GB / 40GB = 5 Primary Shards
Here is how you set the shard count when creating an index (Note: you cannot change primary shard count after the index is created!):
PUT /my-production-index
{
"settings": {
"number_of_shards": 5,
"number_of_replicas": 1
}
}Fact: People often set number_of_shards to 1 until the index organically hits 30-50GB, then they use the Rollover API to create a new one. This is the backbone of Index Lifecycle Management (ILM).
2. Optimizing for Search vs. Optimizing for Indexing Speed 🏎️
Definition:
- Indexing is the process of writing, updating, or deleting JSON documents in Elasticsearch.
- Searching is the process of querying that data to find matches or run aggregations.
The Problem: The database settings that make writing data blazing fast are the exact opposite of the settings that make reading data lightning fast. If Elasticsearch is constantly preparing newly written data for searches, it burns CPU. If it stops to organize data perfectly for searches, your write speeds plummet.
The Solution: You must decide if your workload is Write-Heavy (like logging) or Read-Heavy (like an e-commerce catalog) and tune accordingly.
🛠️ Optimizing for Indexing Speed (Write-Heavy)
If you are dumping millions of logs or migrating a massive database, you want maximum write speed.
- Use the
_bulkAPI: Never send 1,000 separate HTTP requests. Send one HTTP request containing 1,000 documents. - Increase the
refresh_interval: By default, Elasticsearch refreshes the index every1 secondto make new data searchable. This is expensive. Change it to30sor-1(disabled) during heavy bulk loads. - Disable Replicas Temporarily: Replicas mean Elasticsearch has to do the indexing work twice. Set replicas to
0during a massive initial data load, then set it back to1when you are done.
PUT /my-log-index/_settings
{
"index" : {
"refresh_interval" : "30s",
"number_of_replicas": 0
}
}🔍 Optimizing for Search Speed (Read-Heavy)
If you are building a product search for impatient online shoppers, read speed is your priority.
- Use
keywordmapping for identifiers: A common mistake is mappingproduct_idorstatus_codeas aninteger. Numeric fields in Elasticsearch are optimized for range queries (e.g., price > 10). For exact matches,keywordis significantly faster. - De-normalize your data: Relational database joins are slow. Elasticsearch joins (nested or parent-child documents) are heavily penalized in performance. Flatten your data into single documents.
- Force Merge read-only indices: If you have old log data from last month that is never updated, force merge it into a single segment. It makes searching that index vastly faster.
POST /my-old-logs-2025-12/_forcemerge?max_num_segments=13. Understanding Elasticsearch Caching Mechanisms 🧠
Definition: Caching is the process of temporarily storing frequently accessed data in fast memory (RAM) so the system does not have to recompute results or fetch them from a slower disk.
The Problem: Calculating complex aggregations or scanning millions of documents to check if status = "active" takes CPU cycles. If 1,000 users run the exact same search, computing it 1,000 times will melt your server.
The Solution: Elasticsearch uses built-in caching mechanisms to instantly return results for queries it has seen before.
Imagine you are running a pizza shop (the server). You have customers (requests) coming in constantly. If you, the chef, forget where you put the cheese every time a new customer walks in, you are going to have a bad time. You need a way to remember things—ingredients, recipes, and the cash register—while handling hundreds of orders at once. Caching is your prep-station memory.
The Frequently Used Caches
Node Query Cache (Filter Cache)
This is the most important cache. It caches the results of queries used in afiltercontext. If you filter by{"term": {"status": "published"}}, Elasticsearch remembers exactly which documents match this. It does not calculate relevance scores, making it extremely fast.Industry Rule: Always use
filterinstead ofmustfor exact matches, ranges, and boolean checks.jsonGET /products/_search { "query": { "bool": { "must": [ { "match": { "name": "laptop" } } ], "filter": [ { "term": { "in_stock": true } } ] } } }Shard Request Cache
This caches the final response of a search request (mainly used forsize=0aggregation queries). If you have a Kibana dashboard showing website traffic for the last 7 days, and the data hasn't changed, Elasticsearch serves the entire graph's data from memory instantly.Fielddata vs. Doc Values
Historically, sorting on text fields used "Fielddata", which loaded the entire field into RAM (causing catastrophic Out-Of-Memory crashes). Industry standard today: completely avoid Fielddata. Usedoc_valuesonkeywordfields to sort and aggregate efficiently on disk without blowing up your memory.
4. Using Routing to Optimize Query Performance 🗺️
Definition: Routing is the mathematical process Elasticsearch uses to determine exactly which shard a document should be stored in.
The Problem: By default, Elasticsearch hashes the document's _id to distribute data evenly.
shard_num = hash(_id) % num_primary_shards
Because the data is distributed randomly, when you run a query, Elasticsearch doesn't know which shard holds your data. It is forced to broadcast the search to every single shard in the index, wait for all of them to reply, and merge the results. This is called the Scatter-Gather phase. In a massive cluster, Scatter-Gather creates severe network overhead.
The Solution: Custom Routing. You can tell Elasticsearch to use a specific field (like a user_id or tenant_id) to route the document.
How Custom Routing Works
If you are building a SaaS application (Multi-tenant architecture), every document belongs to a specific company (tenant_id). You can route all documents for "Company A" to the exact same shard.
Indexing with Routing:
POST /saas-data/_doc/1?routing=company_A
{
"tenant_id": "company_A",
"document_type": "invoice",
"amount": 500
}Now, all data for company_A lives on exactly one shard.
Searching with Routing:
When "Company A" logs in and searches for their invoices, you pass the routing key in the search request.
GET /saas-data/_search?routing=company_A
{
"query": {
"match": {
"document_type": "invoice"
}
}
}Instead of interrogating 50 shards and wasting massive compute resources, Elasticsearch bypasses the scatter-gather phase. It goes directly to the 1 shard holding Company A's data, grabs the results, and returns them instantly.
Warning: Only use custom routing if you have many distinct routing values (like thousands of users). If you route by a boolean field (e.g., is_active), you will cram 99% of your data into one massive shard and leave the rest empty. This creates a "hotspot," and it will bring your cluster to a screeching halt. 🥵
📚 References for Extra Reading
Challenge
Challenge: Optimize a Multi-Tenant Logging Index
You are the lead DevOps engineer for a new multi-tenant SaaS platform. Your task is to configure an Elasticsearch index template and lifecycle policy for application logs. The configuration must be optimized for both high-volume data ingestion and fast, tenant-isolated querying.
Requirements:
Create an Index Lifecycle Management (ILM) Policy named
logs_policy.- Hot Phase: This is the default phase for new indices.
- Warm Phase: Indices should move to the warm phase after 30 days. In this phase, the index should be force-merged down to a single segment to improve query performance.
- Delete Phase: Indices must be permanently deleted 90 days after creation.
Create an Index Template named
logs_templatethat applies to all new indices matching the patternlogs-*.- Settings for High Ingestion Speed: To handle massive initial data loads, configure the template to set
number_of_replicasto0and therefresh_intervalto60sfor any new index created. - Sharding Strategy: Set the number of primary shards to
5. - Query Optimization via Routing: Implement custom routing. All documents must be routed based on their
tenant_idfield. This is a mandatory requirement for all documents indexed. - Data Mapping: Define explicit mappings for the following fields:
timestamp: Adatefield.tenant_id: Akeywordfield, crucial for filtering and routing.log_level: Akeywordfield for efficient aggregations.message: Atextfield for full-text search.
- Integration: Connect this template to the
logs_policyILM policy and specifylogs_write_aliasas the rollover alias.
- Settings for High Ingestion Speed: To handle massive initial data loads, configure the template to set
Expected result
Your solution should consist of two complete and valid Elasticsearch API calls.
ILM Policy (
PUT _ilm/policy/logs_policy):- The JSON body must define a policy with
hot,warm, anddeletephases. - The
warmphase must trigger atmin_age: "30d"and include aforcemergeaction withmax_num_segments: 1. - The
deletephase must trigger atmin_age: "90d"and include adeleteaction.
- The JSON body must define a policy with
Index Template (
PUT _index_template/logs_template):- The
index_patternsmust be["logs-*"]. - The
settingsobject must contain:"index.lifecycle.name": "logs_policy""index.lifecycle.rollover_alias": "logs_write_alias""number_of_shards": 5"number_of_replicas": 0"refresh_interval": "60s"
- The
mappingsobject must contain:- A
_routingfield with"required": true. - A
propertiesobject withtimestamp,tenant_id,log_level, andmessagefields mapped to their respective types (date,keyword,keyword,text).
- A
- The