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. 🧮

  1. 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.
  2. 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!):

json
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.

  1. Use the _bulk API: Never send 1,000 separate HTTP requests. Send one HTTP request containing 1,000 documents.
  2. Increase the refresh_interval: By default, Elasticsearch refreshes the index every 1 second to make new data searchable. This is expensive. Change it to 30s or -1 (disabled) during heavy bulk loads.
  3. Disable Replicas Temporarily: Replicas mean Elasticsearch has to do the indexing work twice. Set replicas to 0 during a massive initial data load, then set it back to 1 when you are done.
json
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.

  1. Use keyword mapping for identifiers: A common mistake is mapping product_id or status_code as an integer. Numeric fields in Elasticsearch are optimized for range queries (e.g., price > 10). For exact matches, keyword is significantly faster.
  2. 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.
  3. 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.
json
POST /my-old-logs-2025-12/_forcemerge?max_num_segments=1

3. 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

  1. Node Query Cache (Filter Cache)
    This is the most important cache. It caches the results of queries used in a filter context. 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 filter instead of must for exact matches, ranges, and boolean checks.

    json
    GET /products/_search
    {
      "query": {
        "bool": {
          "must": [
            { "match": { "name": "laptop" } } 
          ],
          "filter": [
            { "term": { "in_stock": true } } 
          ]
        }
      }
    }
  2. Shard Request Cache
    This caches the final response of a search request (mainly used for size=0 aggregation 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.

  3. 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. Use doc_values on keyword fields 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:

json
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.

json
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:

  1. 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.
  2. Create an Index Template named logs_template that applies to all new indices matching the pattern logs-*.

    • Settings for High Ingestion Speed: To handle massive initial data loads, configure the template to set number_of_replicas to 0 and the refresh_interval to 60s for 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_id field. This is a mandatory requirement for all documents indexed.
    • Data Mapping: Define explicit mappings for the following fields:
      • timestamp: A date field.
      • tenant_id: A keyword field, crucial for filtering and routing.
      • log_level: A keyword field for efficient aggregations.
      • message: A text field for full-text search.
    • Integration: Connect this template to the logs_policy ILM policy and specify logs_write_alias as the rollover alias.

Expected result

Your solution should consist of two complete and valid Elasticsearch API calls.

  1. ILM Policy (PUT _ilm/policy/logs_policy):

    • The JSON body must define a policy with hot, warm, and delete phases.
    • The warm phase must trigger at min_age: "30d" and include a forcemerge action with max_num_segments: 1.
    • The delete phase must trigger at min_age: "90d" and include a delete action.
  2. Index Template (PUT _index_template/logs_template):

    • The index_patterns must be ["logs-*"].
    • The settings object 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 mappings object must contain:
      • A _routing field with "required": true.
      • A properties object with timestamp, tenant_id, log_level, and message fields mapped to their respective types (date, keyword, keyword, text).
json

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.