The Art of the Shard
Status of This Memo #
This memo provides information for the curious and the on-call. It does not specify an Internet standard of any kind. Distribution of this memo is unlimited, and comments are welcome by email (saksh.am [at] outlook [dot] in). I don’t trust comment boxes online.
Abstract #
One of our three Elasticsearch nodes reached 80% disk while the other two sat at 17% and 40%, because trace indices were being created as single 50 GB shards and never deleted. This memo explains Elasticsearch one idea at a time (index, shard, replica, data stream, templates, lifecycle, shard placement, and what is inside a shard), each idea using only the ones before it, with our cluster’s numbers throughout (a few rounded, see Caveats). It ends with everything we changed that day, and what data we gave up to do it.
Table of Contents #
- 1. Introduction
- 2. The Big Picture
- 3. Index
- 4. Shard
- 5. Replica
- 6. Why Many Indices Instead of One Big One
- 7. Data Stream
- 8. Index Template vs Component Template
- 9. ILM vs DSL: the Bug and the Fix
- 10. How Elasticsearch Picks a Node for a Shard
- 11. Inside a Shard: _source, Columns and best_compression
- 12. Everything We Changed
- 13. What We Lost and What We Kept
- 14. Caveats
- 15. Conclusion
- 16. References
1. Introduction #
RFC 0002 followed a log from the app that writes it to the store that keeps it. This one opens up that store. And like RFC 0003, it is not theory: it is what we changed on our Elasticsearch cluster in a single day, written up so the reasons make sense.
The short version: our daily cluster health check showed one node at 80% disk, close to the point where Elasticsearch stops placing shards on it. Traces were being managed by the wrong lifecycle, so every trace index was one big shard that was never deleted. One missing setting. No errors either: ES was doing exactly what it was told, and the disk just kept filling.
Read it top to bottom. Each section only uses words defined in the sections above it.
2. The Big Picture #
Elasticsearch (ES) is a database for JSON records that you search and aggregate, not update. Ours stores telemetry: every span, log line and metric sample is one JSON record, called a document.
The hard part is volume. About 40 million documents arrive per day, and 3 machines with fixed disks have to hold them, spread them evenly, and throw old ones away on time.
apps ──► EDOT collector (one per k8s node) ──► ES: 3 processes, es-0 / es-1 / es-2 ──► Kibana (UI)
each with its own ~150 GB disk
Each of the 3 ES processes is a node: one ES process with one disk.
3. Index #
You can’t put 40 million documents a day into one heap. You need named groups that you can configure, search and delete as a unit.
Think of a binder of paper records with a label on the spine. You can open it, search it, or throw the whole binder in the bin. (The comparison breaks in one place: a binder holds each page once, while an index stores each record in several shapes. Section 11 gets to that.)
An index is a named collection of documents, stored as a set of files on disk. It has settings (how it’s stored) and mappings (each field’s type: number, keyword, date). Most settings, like the shard count in the next section, are fixed once the index exists.
For example, this is one index:
.ds-traces-generic.otel-default-YYYY.MM.DD-000087
Without indices, “delete last week” or “search only traces” means scanning everything. With them, you pick the binder.
Quick note: if you go looking for an index like this on your cluster and can’t find it, it’s hidden. Names starting with .ds- belong to a data stream (Section 7), and those are hidden by default. Ask for them explicitly:
GET _cat/indices/.ds-traces-*?v&expand_wildcards=all
Or, in Kibana, go to Stack Management → Index Management and turn on “Include hidden indices”.
So an index is files on disk. But documents don’t arrive as files. They arrive one at a time, hundreds a second on average (40 million a day), and properly writing to disk for every single one would be painfully slow.
Back to the binder. You don’t punch holes and file every page the moment it lands on your desk. You drop it in a tray, jot a line in a notebook in case the tray gets knocked over, and every so often staple the tray into a thin booklet and put it on the shelf.
ES does roughly the same thing. Here is the trip one document takes, from the heap (the memory ES runs in) to the disk:
document arrives
├─► indexing buffer, in the JVM heap fast, not searchable yet, gone if ES dies
└─► translog, a file on disk append-only, fsync'd before ES says OK (by default),
│ replayed after a crash, so nothing acked is lost
│ refresh (every 1s by default)
▼
new segment in the OS page cache searchable now, but not fsync'd yet
│
│ flush (when the translog gets big, or after a while)
▼
segments fsync'd to disk durable, so the old translog can be dropped
│
│ merge (in the background, Section 6)
▼
small segments rewritten into bigger ones deleted documents finally go away
A segment is one of those thin booklets: a small, read-only set of index files. An index is really a pile of segments plus a translog (per shard, once Section 4 gets there).
Two things from this matter for the rest of the memo. A document is searchable about a second after it arrives, long before it is safely in its final files. And the heap is only working space. What fills the disk is segments and translog, and that is where the 80% on es-1 lived.
The intervals here are Elastic’s defaults, not numbers from our cluster.
4. Shard #
One index can be bigger than one disk, or busier than one CPU. The work has to be split across nodes.
Picture a thick binder split into 3 thinner volumes kept on different shelves, so 3 people can read or file pages at the same time.
A shard is one piece of an index: a complete, self-contained mini search engine (its own files) that lives on exactly one node. An index with number_of_shards: 3 has 3 shards, and each document goes to one of them, picked by hashing the document’s id. A search is sent to all 3 shards in parallel and the results are merged.
The shard count is fixed when the index is created. Changing it means building a new index.
BEFORE: traces index = 1 shard AFTER: traces index = 3 shards es-1 gets ALL of that day's 13 GB es-0, es-1, es-2 each get ~4.3 GB es-1 does ALL the trace indexing work indexing CPU split three ways
Hold on to that BEFORE line. Section 9 explains why those shards got so big and never went away.
5. Replica #
Our nodes run on spot machines, which the cloud provider can take back at any time (es-2 restarted that very day, because of course it did). A shard that exists on only one node is offline, or gone, when that node is.
Saksham, doesn’t ES just write to one of the other two? yk, Raft and all?
Well, reader, half right. ES does have a consensus algorithm, but it is not Raft, and it is not what decides where your documents go. That one is for electing a master node and agreeing on the state of the cluster.
Your documents follow a much dumber rule. Remember Section 4: each document goes to one shard, picked by hashing its id. Roughly hash(id) % number_of_shards. Say an index has three shards:
shard_0 shard_1 shard_2 new_data → hash(id) % 3 = 1 → shard_1 (but shard_1 is offline)
Then it should just go to shard_0 or shard_2, right?
You’d think so. But the document already has its shard, and no other shard can stand in for it. If that shard is offline, the write fails.
That is what replicas are for: they keep every shard there, and writable, when one node isn’t.
So you photocopy each volume and keep the copy on a different shelf. If one shelf collapses, every page still exists somewhere.
A replica is a full copy of a shard, always placed on a different node from the original (the primary). A write goes to the primary first, then is forwarded to the replica, and both index the document. number_of_replicas: 1 means one copy of every shard.
It is not free insurance, though. Both copies do the indexing work, so a replica costs disk and CPU, not just disk.
BEFORE (traces, 0 replicas): es-1 dies → five days of older traces unavailable;
if its disk is lost, gone for good
AFTER (traces, 1 replica): any one node dies → every shard still has a copy,
so nothing is missing
Our new traces index: 3 primaries + 3 replicas = 6 shards, 2 per node.
6. Why Many Indices Instead of One Big One #
Telemetry has to be thrown away after N days, and how you delete decides whether deleting is cheap.
Throwing away last Monday’s binder takes a second. Tearing last Monday’s pages out of one giant binder means going through every page.
Deleting single documents inside an index only marks them deleted. The disk space comes back later, when ES rewrites the files in a merge (combining small files into bigger ones and dropping deleted documents). That’s slow and CPU-heavy. Deleting a whole index just deletes its files: instant, and the space comes back immediately.
So time-based data is written into a new index every so often (for us, about daily), and old data is removed by deleting whole indices.
Is that the only reason?
There’s a second one, and we leaned on it: since settings are fixed per index, the next new index is where new settings take effect. Existing indices keep their old settings until they’re deleted.
7. Data Stream #
Apps shouldn’t have to know that today’s index is called …-000087. They need one stable name to write to.
Think of a filing cabinet drawer labelled “Traces”. Clerks always drop new pages in the front binder. When it’s full, a new binder goes in front. Readers search every binder in the drawer.
A data stream is a name (e.g. traces-generic.otel-default) that points to an ordered list of indices called backing indices (.ds-traces-generic.otel-default-…-000084, …-000086, …-000087):
- Writes always go to the newest one, the write index.
- Searches on the stream name go to all of them.
- Rollover means creating a new backing index and moving writes to it.
traces-generic.otel-default ──► [000079] [000084] [000086] [000087 ← writes go here]
oldest ──────────────────────► newest
You can trigger a rollover by hand. We did, for traces:
POST /traces-generic.otel-default/_rollover
8. Index Template vs Component Template #
Every rollover creates a new index, automatically, many times a week. Its settings have to come from somewhere: a recipe.
Picture a recipe card for “how to set up a new Traces binder”, put together from standard sections (the publisher’s) plus your own handwritten card on top. When two sections disagree, the later one wins.
- A component template is one reusable section of settings, mappings and lifecycle. Example:
traces@settings, written by Elastic. - An index template (e.g.
traces-otel@template) says “indices or data streams whose name matches this pattern get built from this ordered list of component templates”. Later entries override earlier ones. …@custom(e.g.traces-otel@custom) is a component template Elastic lists last on purpose and leaves empty for you. Your overrides go there, and stack upgrades don’t overwrite it.
traces-otel@template = traces@mappings + traces@settings + otel@… + … + traces-otel@custom
↑ Elastic: "use ILM policy ↑ ours, wins
traces@lifecycle"
Now the rule that explains half of that day: templates are only read when something is created.
- A new index reads its settings (shards, replicas, codec) when it’s created. Existing indices don’t pick up template changes. Some of their settings can still be changed by hand (replicas and
prefer_ilmcan, the shard count and codec can’t), so we patched the existing ones (PUT …/_settings) and rolled over so the next index got everything else. - A data stream copies its lifecycle (retention) when the stream itself is created. So the
5dwe put inmetrics-otel@customdidn’t reach the metrics streams that already existed, and we had to set it on them directly:
PUT /_data_stream/metrics-*.otel-*/_lifecycle
{
"data_retention": "5d"
}
| Thing | What it is | When changing it takes effect |
|---|---|---|
| component template | a reusable section of settings | when the next index or stream is built from it |
| index template | pattern + ordered list of sections | same |
| data stream | a name pointing to a list of backing indices | its lifecycle can be changed live |
| index | the actual files | shard count and codec fixed at creation; a few, like replicas, can be patched live |
9. ILM vs DSL: the Bug and the Fix #
Something has to roll indices over and delete old ones, on a schedule, forever, without anyone watching.
Imagine two clerks who can both be assigned to a drawer. Clerk ILM follows a written multi-step procedure card, step by step. Clerk DSL has one instruction: “keep N days”. If a binder has both clerks assigned, a flag on the binder says which one is in charge, and it defaults to ILM.
- ILM (index lifecycle management): a named policy of phases (hot → warm → cold → delete). Each index points to its policy by name, and ES steps each index through the phases. It’s powerful: it can change the codec, shrink or force-merge indices. It’s also easy to get subtly wrong.
- DSL (data stream lifecycle): just a retention (e.g.
5d) set on the data stream. ES then rolls over automatically (it pickedmax_age: 1dfor a 5d retention), merges, and deletes each backing index once it’s been 5 days since that index rolled over. index.lifecycle.prefer_ilm: an index setting. When an index has both,true(the default) means ILM runs it.
9.1 The bug
Elastic's traces@settings: "use ILM policy traces@lifecycle"
→ rollover at 50 GB / 30 d, NO delete step
our traces-otel@custom: "DSL, 5d" but no prefer_ilm: false
→ ILM won on every new traces index
→ 50 GB single-shard indices, never deleted
→ es-1 hit 80%
logs and metrics @custom already had prefer_ilm: false
→ that's why only traces broke
So the 5 days we asked for was just… ignored?
Not ignored. Overruled, quietly. Both lifecycles were attached, the default flag picked ILM, and Elastic’s ILM policy for traces has no delete step. Nothing was wrong as far as ES was concerned.
9.2 The fix
prefer_ilm: false in traces-otel@custom, and on the existing traces indices. DSL now runs traces like everything else. Simplified, the two requests look like this:
PUT /_component_template/traces-otel@custom
{
"template": {
"settings": {
"index.lifecycle.prefer_ilm": false,
"index.number_of_shards": 3,
"index.number_of_replicas": 1
},
"lifecycle": { "data_retention": "5d" }
}
}
PUT /traces-generic.otel-default/_settings
{
"index.lifecycle.prefer_ilm": false
}
The second one targets the data stream name, so it lands on every backing index at once. prefer_ilm is a dynamic setting, which is why it can be flipped on indices that already exist [ES-DSL-SETTINGS].
9.3 Why DSL instead of fixing the ILM policy
- It’s what we had already planned on.
- It needs one number instead of a phase policy.
- Rollover size is chosen automatically from the retention.
- Logs and metrics already use it, so there’s one model everywhere.
The cost is that ILM-only tricks aren’t available, like “switch the codec after 24h”.
10. How Elasticsearch Picks a Node for a Shard #
Shards have to be spread over nodes so no node runs out of disk. So why did es-1 fill up while the others didn’t?
Picture a warehouse manager who balances shelves by counting boxes, not weighing them.
So the balancer was broken?
Not broken. It did exactly what it is built to do. The balancer tries to give every node roughly the same number of shards (ours: about 200 each, within a handful of each other). Sizes matter much less. A 50 GB trace shard and a 1 MB metrics shard count about the same.
So why did both big shards land on es-1?
Because nothing was looking at their size. Counting boxes, es-1 looked as good a shelf as any. Bytes only start to matter once a node crosses a watermark.
Those disk watermarks are hard limits per node:
| Watermark | Disk used | What ES does |
|---|---|---|
| low | 85% | stops putting additional shards on that node |
| high | 90% | starts moving shards away from it |
| flood stage | 95% | makes every index with a shard there read-only, so writes fail |
BEFORE: shard counts equal, bytes 17% / 80% / 40% (two 50 GB trace shards on es-1)
AFTER: traces in 3 × ~4 GB shards per day, spread 2-2-2
→ bytes even out as old ones are deleted
11. Inside a Shard: _source, Columns and best_compression #
The same data has to be searchable by word, fast to aggregate, and returned exactly as it was sent. Those need different layouts on disk.
A library keeps each book, a card catalogue (to search by word), and ledgers where one page lists every book’s page count (to add things up). Each document is written in up to three shapes:
- inverted index: word → which documents contain it. Used to search.
- doc values: one column per field (all
durationvalues together). Used to aggregate, sort and chart. _source: the original JSON, stored as a blob. Used to show you the document.
The codec compresses the stored blobs (mainly _source):
defaultis LZ4: fast, lighter compression.best_compressionis stronger. On the 9.x we run, it’s zstd [ES-CODEC]. It costs a bit more CPU, and reading stored fields (like_source) back is slower.- Neither touches the columns.
Measured on our kubeletstats index: _source was 89% of it, columns 10%. That’s why best_compression on metrics is worth doing. Traces and logs already had it.
Why keep the blob at all, if the columns have the data?
Good question. Synthetic _source does exactly that: drops the blob and rebuilds the JSON from the columns when you read a document. It’s the bigger saving, but it needs an enterprise licence, and ours is basic.
stored (ours): columns + full JSON blob ← codec compresses this blob synthetic: columns only ← enterprise licence
Like other settings, the codec applies from the next index. Existing indices aren’t rewritten.
12. Everything We Changed #
Here’s the whole day in one table.
| # | Change | Before | After |
|---|---|---|---|
| 1 | prefer_ilm: false on existing traces indices | ILM, never deleted | DSL deleted the oldest traces index (50 GB) at once; es-1 80% → 59% |
| 2 | traces-otel@custom: DSL, 5d, 3 shards, 1 replica | each new index: 1 shard, 0 copies, ILM | each new index: 3 shards + 3 replicas, DSL 5d |
| 3 | traces rollover | settings would only apply in a few days | the new write index created with the new settings straight away |
| 4 | metrics-otel@custom: best_compression, 5d | LZ4, 10d (template) | zstd blob from the next index on |
| 5 | _lifecycle 5d on all the metrics streams | 10d | 5d; days 6–10 deleted |
| 6 | hostMetrics: false in the collector | duplicate node metrics | host metrics stream stopped |
Disk per node:
| es-0 | es-1 | es-2 | ||
|---|---|---|---|---|
| morning | 17% | 80% | 40% | es-1 close to the 85% low watermark |
| end of day | 16% | 48% | 40% |
What we saw straight away: the moment DSL deleted the oldest traces index (change 1), es-1 dropped from 80% to 59%. By the end of the day it was at 48%. es-0 and es-2 barely moved.
What we expect over the next couple of days: no big jump, just the shape changing. New trace indices are 3 shards spread 2-2-2 (Section 10), so new trace data lands evenly on all three nodes. The old single-shard trace indices, the reason es-1 is heavier, get deleted as they reach their five days, and es-1 comes down towards the other two as they go.
13. What We Lost and What We Kept #
| Gone (deliberately, can’t be undone) | Kept |
|---|---|
| the oldest three days of traces (deleted that day) | every span: nothing sampled or filtered, DB spans included |
| metrics older than 5 days (deleted that day) | logs: still 10 days |
| the next five days of traces, once they age out in a couple of days | existing data: nothing rewritten or reindexed |
| host metrics | every Kibana view except Infrastructure → Hosts |
| from now on: traces and metrics older than 5 days, logs older than 10 | traces now survive losing a node |
Still at risk for about five more days: the three old traces indices have no replica. Losing es-1 or es-2 before they age out would lose those traces.
We could have added a replica to them live, but that copies every one of those big shards onto another node, and disk was the very thing we were short of (es-1 especially). So we let them age out instead.
14. Caveats #
- Deleting indices is permanent. Switching to a shorter lifecycle deletes old data straight away, so write down what will go first (we did: Section 13) and make sure everyone is fine losing it.
- Names, dates and a few counts are changed or rounded so the cluster can’t be identified. The percentages, sizes and ratios are the real ones.
best_compressionis zstd on 9.x [ES-CODEC]. Older versions used DEFLATE, so if you’re on an older cluster, check what yours does before switching.- Numbers are from our cluster on one day. Your shard counts, sizes and defaults will differ.
15. Conclusion #
Phew! That’s a lot of words. The TL;DR: one missing flag let the wrong clerk run the traces drawer, and the disk filled up without a single error.
- Templates are read only when something is created. Changing one fixes the future, not the present: patch what exists, then roll over.
- If an index has both ILM and DSL, ILM wins unless you say
prefer_ilm: false. - The balancer counts shards, not bytes. A few huge shards can fill one node while the counts look perfectly even.
- Replicas cost disk and CPU, and they’re what turns losing a spot node into a non-event.
And it loops back to RFC 0001: ES was accepting writes and doing exactly what its config said, while one disk crept towards a watermark. Nothing said so. The only signal was a number you had to go and look at.
16. References #
[ES-DS] Elastic documentation, “Data streams”, elastic.co/docs.
[ES-DSL] Elastic documentation, “Data stream lifecycle”, elastic.co/docs.
[ES-ILM] Elastic documentation, “Index lifecycle management”, elastic.co/docs.
[ES-TEMPLATES] Elastic documentation, “Index templates”, elastic.co/docs.
[ES-DISK] Elastic documentation, “Cluster-level shard allocation and routing settings” (disk-based shard allocation), elastic.co/docs.
[ES-DSL-SETTINGS] Elastic documentation, “Data stream lifecycle settings” (index.lifecycle.prefer_ilm), elastic.co/docs.
[ES-MIGRATE] Elastic documentation, “Tutorial: Migrate ILM managed data stream to data stream lifecycle”, elastic.co/docs.
[ES-CODEC] Elastic documentation, “General index settings” (index.codec), elastic.co/docs.
[RFC0001] Saksham, “Observability, My Dear Watson”, blogs.saksh.fyi.
[RFC0002] Saksham, “Logs in Translation”, blogs.saksh.fyi.