AlgoViz

Scaling search and indexing

hard 28 min

How a search cluster grows: the right number and size of shards, replicas for reads and safety, safe placement, storage tiers for old data, rebuilding without downtime, and rules for scaling up and down.

Video lesson · Chapter 1 of 6

Split and replicate for different reasons

0:00 / 4:01

Theory

Read or listen first. About 2 min.

What it is

Scaling search means growing in three directions that need different tools. More data and more writes need more primary shards. More reads need more replicas. More of either needs more nodes to put them on.

It also means shrinking with age. Old data is read rarely, so it moves to cheaper machines and storage. And it means changing: an index that has the wrong number of shards is rebuilt next to the live one and swapped in.

Why it exists

Most search clusters do not die of too much traffic. They die of thousands of tiny shards, a full disk, or an index that was planned for last year's data. All three can be calculated beforehand.

Indexing and searching compete for the same CPU, memory and disk. A big load in the afternoon makes every search slow. Separating them, in time or on different machines, is the largest single improvement in many systems.

A short history

  1. 2003

    Google's cluster paper describes index shards with many replicas on cheap machines: capacity grows by adding copies.

  2. 8 February 2010

    The first Elasticsearch release places and moves shards on its own when nodes come and go.

  3. 2010

    Google's Percolator paper shows indexing in small steps, so that fresh pages need not wait for a full rebuild.

Words to know

Primary shard
The copy that takes writes first. Their number is fixed for an index.
Replica
Another copy of a shard, for reads and for safety. Their number can change at any time.
Rollover
Start a new index when the current one is big or old enough.
Alias
A name that points to an index and can be moved in one step.
Tier
A group of machines for data of one age: hot, warm, cold, frozen.
Watermark
A disk level at which the cluster stops placing shards, or moves them away.
Oversharding
So many small shards that the overhead is larger than the work.

How it works

Step through the idea, or press Play.

Step 1 of 3

Size. Primaries from data, replicas from reads

Understand it

Start here

The map makers

A town has a large map that many visitors read. The town grows, the visitors multiply, and streets change. The map makers must never take the map away.

A map that is always open
The town

How a question is asked of all sheets is the topic Inside a distributed search system.

Directions

What exactly is too small?

ProblemSignTool
Too much dataLarge shards, full disksMore primaries, nodes, tiers
Too many writesIndexing queue growsMore primaries on more nodes
Too many readsCPU high, queue of searchesReplicas, on new nodes
A node failsMissing results, slow recoveryReplicas in other zones
Traffic variesIdle nights, full daysScale replicas by the clock
  • Sharding

    Split the data.

  • Replication

    Copy for reads and safety.

  • Autoscaling

    Follow the load.

  • Tiers

    Old data on cheap storage.

  • Balance

    Even shards, even queries.

  • Lifecycle

    Roll over, shrink, delete.

A bigger machine is also scaling, and often the first step. More memory for the file cache helps searches directly. See vertical scaling. It ends at one machine, and one machine can fail.

Shards

How many primaries, and how large

Documents are split by id, so each lives whole on one shard. Updates are easy and searches ask every shard. Why not by term is explained in indexing.

Sizing rules (Elasticsearch documentation, 8.19)

WhatRuleWhy
Shard size10 to 50 GB for many usesSearch speed and time to copy
Documents in a shardUnder 200 millionSearch slows; the hard limit is 2,147,483,519
Shards on a nodeAt most 1,000 (not frozen)A limit, not a goal
IndicesUnder 3,000 for each GB of heap on mastersEach has metadata
Measure with your own documents and queries. Many small shards are worse than a few large ones.

Primaries from size

P=⌈100,000,000×2 KB×1.530 GB⌉=⌈30030⌉=10P = \left\lceil \frac{100{,}000{,}000 \times 2\text{ KB} \times 1.5}{30\text{ GB}} \right\rceil = \left\lceil \frac{300}{30} \right\rceil = 10
100 million documents, 50% growth in a year, target 30 GB. Without growth it would be 200 / 30, so 7, and too few next year. The index can be smaller or larger than the raw text: load a sample and measure.

Why the number is hard to change

10→11 shards, modulo: 1011≈91% of documents move10 \to 11 \text{ shards, modulo: } \tfrac{10}{11} \approx 91\% \text{ of documents move}
So an index has a fixed number. Elasticsearch can split by whole factors, for example 5 to 10, from a read-only index into a new one. Otherwise build a new index. The general picture is in sharding.

Replicas

Copies for reads and safety

Every copy in another zone

Three zones with one node each. Zone A holds primary 0 and copy 2, zone B holds primary 1 and copy 0, zone C holds primary 2 and copy 1.
If zone B is lost, primary 1 is replaced by its copy in zone C, and all data is still there.

What replicas give

  • A spare when a node dies
  • More searches a second, if they are on extra nodes
  • Upgrades node by node without downtime
  • A copy near readers, when copied to another region

What they cost

  • Disk: each copy is the full shard
  • Indexing work again on each copy
  • Writes wait for the copies in sync
  • Asynchronous copies lag behind
  • Network for copying

In Elasticsearch the primary sends each write to the replicas that are in sync and waits for them. A replica in another region is fed asynchronously, so it is a little behind.

Copies from read load

copies=⌈1,800/s×0.020 s8 cores⌉=⌈4.5⌉=5\text{copies} = \left\lceil \frac{1{,}800/\text{s} \times 0.020\text{ s}}{8\text{ cores}} \right\rceil = \lceil 4.5 \rceil = 5
For each shard: every search uses 20 ms of CPU, and a copy may use 8 busy cores (half of a 16-core machine). Five copies, so one primary and four replicas. Assumed numbers, from the search system.

Placement

Where a shard may live

Choose a node for a copy

The first two are rules, not points in a score. A good score must not put two copies on one node.

Disk watermarks (Elasticsearch defaults)

LevelUsedWhat happens
Low85%No more shards are placed here
High90%Shards are moved away
Flood95%Indices on it become read-only
On large disks the percentages are limited by an absolute amount of free space. Plan for about 70%, so that the loss of a node fits on the others.

Nodes from disk

300 GB×2 copies=600 GB⌈600500×0.7⌉=2300\text{ GB} \times 2 \text{ copies} = 600\text{ GB} \qquad \left\lceil \frac{600}{500 \times 0.7} \right\rceil = 2
Two nodes of 500 GB would hold it. Take three: if one of two dies, 600 GB cannot have two copies on one node, and masters need a majority of three to decide.

Time

Roll over and move down

Tiers for logs of 1 TB a day

TierAgeStorageCopiesSize
Hot0 to 7 daysSSD214 TB
Warm7 to 30 daysCheaper disks246 TB
Cold30 to 90 daysDense disks1, backed by a snapshot60 TB
Frozen90 to 365 daysObject storage1275 TB
Everything on hot machines would be 365 x 2 = 730 TB of SSD. With tiers it is 14 TB. Ages are examples: choose them from how often data is searched.
JSON
{  "policy": { "phases": {    "hot": { "actions": {      "rollover": { "max_primary_shard_size": "50gb", "max_age": "7d" },      "set_priority": { "priority": 100 } } },    "warm": { "min_age": "7d", "actions": {      "shrink": { "number_of_shards": 1 },      "forcemerge": { "max_num_segments": 1 },      "set_priority": { "priority": 50 } } },    "cold": { "min_age": "30d", "actions": {      "set_priority": { "priority": 0 } } },    "delete": { "min_age": "365d", "actions": { "delete": {} } }  } }}
After a rollover, ages count from the rollover. Shrink to one shard only if the result stays under the target size.

The life of one index

Deleting a whole index is instant. Deleting documents one by one leaves marks and work for merges.

Change

Rebuild while visitors read

Reindex behind an alias

Moving an alias is one atomic step. Keep feeding v1 until you are sure, so that you can move back.
  1. 1

    Make room

    Both indices exist at the same time, so you need the disk for both.

  2. 2

    Build with low priority

    No replicas and no refresh during the load, throttled, in quiet hours or on separate nodes.

  3. 3

    Catch up

    Apply the changes from the queue since the snapshot.

  4. 4

    Verify

    Counts for each day or category, and sample queries with both indices.

  5. 5

    Warm up

    Replicas on, then replay popular queries, so that the first users do not read from cold disks.

  6. 6

    Move the alias

    And watch. Delete v1 after a few days.

Indexing apart from searching

Changes flow from Kafka to an indexing group of machines, which writes finished segments to object storage. A search group of machines reads segments from the object storage and answers the clients.
When loads disturb searches, build segments on other machines and let search nodes copy them. Solr has replica types (TLOG, PULL) that copy segments instead of indexing again.

Speed

Cheaper work before more machines

MeasureDoesUse it when
Force mergeOne segment, faster readsThe index will not be written again
Index sortingDocuments stored in query orderSearches want the newest first
Filter cacheRemembers document setsThe same filters repeat
Column valuesValues by document for sorting and countingMany aggregations
RoutingOne shard instead of allEach query names a tenant
Bulk writesFewer round tripsAlways for loads
Force merging an index that is still written can create segments over 5 GB that normal merges leave alone, full of deleted documents. Elastic advises it only for read-only indices.

Autoscaling

Scale on the cause

SeenCheckDo
p99 over 200 ms, CPU highReads or merges?Add nodes and replicas, or move loads
p99 over 200 ms, CPU lowSlow disk, one hot shard, heavy queryFix that; more replicas do not help
CPU over 80%All nodes or one?Add nodes, or rebalance
Disk over 70%Growth a dayAdd nodes before 85%
CPU under 20%, p99 under 50 ms, for hoursMinimum copiesRemove one replica, never the last
Example limits. A new node first receives copies over the network, so scaling up makes things slower for a while. Scale before the peak.

How long a new copy takes

30 GB100 MB/s=300 s=5 minutes a shard\frac{30\text{ GB}}{100\text{ MB/s}} = 300\text{ s} = 5\text{ minutes a shard}
Ten shards one after another: 50 minutes. This is why shard size matters for recovery, and why autoscaling cannot answer a spike of ten minutes.

What to add?

Adding a replica without a node spreads the same CPU over more copies and costs memory.

Rules

Do and do not

Do

  • Keep shards between 10 and 50 GB
  • Use replicas for reads
  • Move old data to cheaper tiers
  • Watch and scale before the peak
  • Plan for a year of growth

Do not

  • Create many small shards
  • Put two copies on one node
  • Ignore disk watermarks
  • Add nodes and forget to rebalance
  • Run on defaults that you have not read

Summary

The whole topic in one minute.

Plan primaries from next year's size divided by a target of 10 to 50 GB, and replicas from read load and safety. Place no two copies of a shard on one node, keep disks under the low watermark, and leave room for the loss of one node.

Time-based data rolls over into new indices and moves through tiers. Anything that fixes the shape of an index, such as its shard count or analyzer, is changed by building a new one and moving an alias. Scale on the cause, not only on the symptom: a replica without a spare node helps nobody.

  • Primaries for data and writes, replicas for reads and safety, nodes for both.
  • Size shards from next year's data, 10 to 50 GB each.
  • More primaries make each search more expensive.
  • Never two copies on one node. Keep disks under 85%.
  • Roll over by size or age, move down the tiers, delete whole indices.
  • Rebuild beside the live index and move an alias.

Sources