RousselTMLEARNING

Observability

Elasticsearch best practices: mappings, shards, lifecycle and operations

Elasticsearch best practices: shard sizing, explicit mappings, templates, ILM, JVM memory, security, snapshots, efficient queries and diagnostic commands.

1. Sizing indices and shards #

The most impactful setting.

Sizing rules #

Recommended shard size
Too many small shards consume memory; too large, they slow down recovery.
  • Aim for 10 to 50 GB per shard. The old rule « fewer than 20 shards per GB of heap » was withdrawn by Elastic in 8.3: instead, watch the cluster.max_shards_per_node limit and the memory actually used by mappings and fields.
  • A single primary shard is enough for small indices; avoid over-sharding.
  • Use data streams with rollover rather than a single giant index.
# Toutes les commandes utilisent HTTPS et l'authentification (ca.crt : certificat de l'autorité du cluster)
export ES_PASSWORD='...'
curl --cacert ca.crt -u "elastic:$ES_PASSWORD" -s https://localhost:9200/_cluster/health?pretty
curl --cacert ca.crt -u "elastic:$ES_PASSWORD" -s 'https://localhost:9200/_cat/indices?v&s=store.size:desc&h=index,pri,rep,docs.count,store.size' | head
curl --cacert ca.crt -u "elastic:$ES_PASSWORD" -s 'https://localhost:9200/_cat/shards?v&s=store:desc' | head
curl --cacert ca.crt -u "elastic:$ES_PASSWORD" -s 'https://localhost:9200/_cat/allocation?v'
curl --cacert ca.crt -u "elastic:$ES_PASSWORD" -s 'https://localhost:9200/_cluster/allocation/explain?pretty'      # pourquoi un shard n'est pas alloué

2. Mappings, templates and ILM #

Controlling the schema and the lifecycle.

Template and explicit mapping #

curl --cacert ca.crt -u "elastic:$ES_PASSWORD" -X PUT https://localhost:9200/_index_template/logs-app -H 'Content-Type: application/json' -d '{
  "index_patterns": ["logs-app-*"],
  "data_stream": {},
  "priority": 200,
  "template": {
    "settings": { "number_of_shards": 1, "number_of_replicas": 1, "index.lifecycle.name": "logs-30j", "index.codec": "best_compression" },
    "mappings": {
      "dynamic": "strict",
      "properties": {
        "@timestamp": { "type": "date" }, "level": { "type": "keyword" }, "message": { "type": "text" },
        "user_id": { "type": "keyword" }, "duration_ms": { "type": "long" }
      }
    }
  }
}'
Common mistake: An unrestricted dynamic mapping creates thousands of fields (mapping explosion). Use dynamic: strict and suitable types (keyword for filters, text for full text).
Good to know: The template has a priority of 200: without it, it overlaps the built-in logs-*-* template (priority 100) and the data stream may receive the built-in mapping instead of yours. Check the applied template with POST _index_template/_simulate_index/logs-app-default.

Lifecycle (ILM) #

curl --cacert ca.crt -u "elastic:$ES_PASSWORD" -X PUT https://localhost:9200/_ilm/policy/logs-30j -H 'Content-Type: application/json' -d '{
  "policy": { "phases": {
    "hot":    { "actions": { "rollover": { "max_primary_shard_size": "50gb", "max_age": "1d" } } },
    "warm":   { "min_age": "7d",  "actions": { "forcemerge": { "max_num_segments": 1 } } },
    "delete": { "min_age": "30d", "actions": { "delete": {} } }
  } }
}'
curl --cacert ca.crt -u "elastic:$ES_PASSWORD" -s https://localhost:9200/_ilm/status
curl --cacert ca.crt -u "elastic:$ES_PASSWORD" -s 'https://localhost:9200/logs-app-*/_ilm/explain?pretty' | head -30

3. Memory, security and backups #

Production stability.

JVM and system #

# jvm.options.d/heap.options : 50 % de la RAM maximum, jamais plus de ~30 Go
-Xms16g
-Xmx16g

sudo sysctl -w vm.max_map_count=262144
sudo swapoff -a                       # ou bootstrap.memory_lock: true
curl --cacert ca.crt -u "elastic:$ES_PASSWORD" -s 'https://localhost:9200/_nodes/stats/jvm?filter_path=**.heap_used_percent&pretty'

Security #

  • Enable TLS (transport and HTTP) and authentication; use API keys with limited scope.
  • Never expose port 9200 on the Internet; go through a reverse proxy.
  • One write role per ingestion pipeline, one read role per team.
curl --cacert ca.crt -u "elastic:$ES_PASSWORD" -X POST https://localhost:9200/_security/api_key -H 'Content-Type: application/json' -d '{
  "name": "ingestion-app",
  "role_descriptors": { "writer": { "indices": [{ "names": ["logs-app-*"], "privileges": ["create_doc", "auto_configure"] }] } },
  "expiration": "90d"
}'

Backups (snapshots) #

curl --cacert ca.crt -u "elastic:$ES_PASSWORD" -X PUT https://localhost:9200/_snapshot/depot -H 'Content-Type: application/json' -d '{ "type": "s3", "settings": { "bucket": "es-snapshots" } }'
curl --cacert ca.crt -u "elastic:$ES_PASSWORD" -X PUT https://localhost:9200/_slm/policy/quotidien -H 'Content-Type: application/json' -d '{
  "schedule": "0 30 1 * * ?", "name": "<snap-{now/d}>", "repository": "depot",
  "config": { "indices": ["logs-*"] }, "retention": { "expire_after": "30d", "min_count": 5 } }'
curl --cacert ca.crt -u "elastic:$ES_PASSWORD" -s https://localhost:9200/_snapshot/depot/_all?pretty | head -20
Good practice: Test restores regularly: a backup that has never been restored is not a backup.

4. Efficient queries and ingestion #

Bulk, filters and pagination.

Good habits #

# Ingestion : _bulk par lots de 5 à 15 Mo
curl --cacert ca.crt -u "elastic:$ES_PASSWORD" -s -H 'Content-Type: application/x-ndjson' -XPOST https://localhost:9200/_bulk --data-binary @lot.ndjson | jq '.errors'

# Filtres (cachés, sans score) plutôt que must pour les conditions exactes
curl --cacert ca.crt -u "elastic:$ES_PASSWORD" -s https://localhost:9200/logs-app-*/_search -H 'Content-Type: application/json' -d '{
  "size": 20, "_source": ["@timestamp","level","message"],
  "query": { "bool": { "filter": [ { "term": { "level": "error" } }, { "range": { "@timestamp": { "gte": "now-15m" } } } ] } },
  "sort": [{ "@timestamp": "desc" }]
}'
# Pagination profonde : search_after + PIT
curl --cacert ca.crt -u "elastic:$ES_PASSWORD" -s -XPOST 'https://localhost:9200/logs-app-*/_pit?keep_alive=1m'
AvoidPrefer
from: 100000search_after with PIT
Leading wildcard *textSuitable analyzer (n-gram) or dedicated field
Updating a document in a loopBulk reindexing, append-only model
One index per day without rolloverData streams and ILM

Reference diagram and quick check #

Visualize the principle and check it from the command line.

Reference diagram #

Elasticsearch ILM phases
Adjust durations to your business needs.
curl --cacert ca.crt -u "elastic:$ES_PASSWORD" -s 'https://localhost:9200/_cat/indices/logs-*?v&h=index,health,pri,store.size&s=index'

Related articles

Transforms and enrich: summarising and enriching data in Elasticsearch

Build entity-centric indices with pivot and latest transforms, and enrich documents at ingest time with enric…

OpenTelemetry and Elasticsearch: compatibility and architecture

Send OpenTelemetry to Elasticsearch: Collector and elasticsearch exporter, managed OTLP endpoint, APM Server,…

Ingesting OpenTelemetry logs into Elasticsearch

Collect and structure logs with the OpenTelemetry Collector (filelog receiver, operators, transform processor…

Keep learning

Support us

♥ SUPPORT US

Support RousselTM Learning

Courses, articles, labs and certificates stay free with no intrusive ads. A voluntary contribution, of any amount you choose, pays for hosting, lab environments and new content.

Contribute with PayPal Any amount · card or PayPal accountLearn more
QR code PayPal
Or scan this QR code with your phone

Thank you, every contribution counts!