AlgoViz

ELK Stack

medium 30 min

The ELK Stack is Elasticsearch, Logstash and Kibana: a place to collect, clean, store and search logs from many machines.

Video lesson · Chapter 1 of 5

Follow one train cancellation into search

0:00 / 4:35

The ELK Stack in 90 seconds

1:30Reel coming soon

Theory

Read or listen first. About 2 min.

What it is

ELK stands for three programs. Elasticsearch stores documents and searches them. Logstash receives events, changes them and sends them on. Kibana is the web interface for searching, charts and administration.

Today the company Elastic calls the set the Elastic Stack. It adds small programs that run on every machine and send data: Elastic Agent, and the older Beats such as Filebeat. Elastic says the agent has replaced Beats for most uses. Elastic Agent also contains an OpenTelemetry Collector.

Logstash is optional. Many teams send straight from the agent to Elasticsearch and let an ingest pipeline, which runs inside Elasticsearch, do the parsing.

Why it exists

With two servers you can log in and read the files. With two hundred you cannot, and a container takes its files with it when it goes away. The lines have to be copied somewhere else while they are fresh.

Once they are in one place, the questions get better: which service logged errors in the last hour, for which version, and what did one request leave behind on all machines? That needs fields and an index, not only text. The ideas behind this are in distributed logging and full-text search.

A short history

  1. February 2016

    Elastic announces the name Elastic Stack, since Beats had joined the three.

  2. October 2016

    Version 5.0 gives all products the same version number and release.

  3. 2021

    From version 7.11, Elasticsearch and Kibana leave the Apache 2.0 licence. The OpenSearch fork starts from 7.10.2.

  4. August 2024

    Elastic announces AGPLv3 as a further licence choice for the free source code. In September 2024 OpenSearch moves to the Linux Foundation.

  5. April 2025

    Version 9.0. New logs data streams use the space-saving logsdb mode by default.

Words to know

Shipper
A small program beside the application that reads logs and sends them: Elastic Agent or Filebeat.
Event
One log line or record while it travels.
Document
The stored event: JSON with fields such as @timestamp and log.level.
Data stream
One name for a series of hidden indices, for data that is only appended.
Rollover
Closing the current write index of a stream and opening a new one.
ILM
Index lifecycle management: rules that move and delete indices by age and size.
ECS
Elastic Common Schema: agreed field names, so that one search works on all sources.
KQL and ES|QL
Kibana's filter language, and a piped language that can also calculate.

How it works

Step through the idea, or press Play.

Step 1 of 3

Collect. A shipper reads the file and keeps its offset

Understand it

Start here

The feather sorting house

A park keeper finds feathers all over the ground. Visitors ask questions such as: how many red ones were found this week? Imagine how the keeper could answer without walking the park again.

Five feathers find a place
MONTUEWEDFeathers everywhere

Collect, label, file by day, look. And throw away whole drawers, not single feathers.

The whole

Parts and who does what

One path from line to chart

Inside our system, a server with an app and an agent sends events to Logstash, Logstash sends bulk requests to Elasticsearch, Elasticsearch returns answers to Kibana, and Kibana shows charts to engineers outside.
Logstash can be left out: then the agent writes to Elasticsearch, and an ingest pipeline parses.
  • Elastic Agent

    One program for logs, metrics and security data, managed centrally from Fleet in Kibana.

  • Beats

    Single-purpose shippers such as Filebeat. Still maintained; the agent is the usual choice for new work.

  • Logstash

    Inputs, filters, outputs. Useful when events come from or go to several systems.

  • Elasticsearch

    Stores JSON documents in shards and searches them almost in real time.

  • Kibana

    Discover, dashboards, alerts, and the screens that manage the cluster.

  • Ingest pipeline

    A list of processors inside Elasticsearch, run before a document is stored.

How Elasticsearch itself works, with segments, shards, replicas and refresh, is on its own page. This page is about the stack around it.

Collect

The shipper and its notebook

Filebeat starts one harvester for each file. It reads line by line and keeps the offset of each file in a registry on disk. If the output is down, it waits and later goes on from the same place.

YAML
filebeat.inputs:  - type: filestream    id: checkout-log          # must be unique and must not change    paths: ["/var/log/checkout/*.log"]    parsers:      - ndjson:          target: ""output.logstash:  hosts: ["logstash1:5044", "logstash2:5044"]  loadbalance: true  ssl.certificate_authorities: ["/etc/filebeat/ca.crt"]
filestream replaces the older log input. It recognises a file by a fingerprint of its content, so a file is read only when it is larger than 1,024 bytes.

Why the offset moves last

Each event arrives at least once. After a crash it may arrive twice.

Process

Logstash: inputs, filters, outputs

Ruby
input { beats { port => 5044 } }filter {  grok {    match => { "message" => "%{TIMESTAMP_ISO8601:ts} %{LOGLEVEL:[log][level]} %{NUMBER:took_ms:int} %{GREEDYDATA:text}" }    tag_on_failure => ["_grokparsefailure"]  }  date   { match => ["ts", "ISO8601"] remove_field => ["ts"] }  mutate { remove_field => ["[http][request][headers][authorization]"] }}output {  elasticsearch {    hosts => ["https://es1:9200", "https://es2:9200"]    api_key => "${ES_API_KEY}"    ssl_certificate_authorities => ["/etc/logstash/ca.crt"]    data_stream => "true"    data_stream_type => "logs"    data_stream_dataset => "checkout"    data_stream_namespace => "prod"  }}
Goes to the data stream logs-checkout-prod. The key comes from the environment or the keystore, never from the file.

Logstash numbers to know

SettingDefaultMeaning
pipeline.workersNumber of CPU coresThreads that run filters and outputs
pipeline.batch.size125Events one worker takes at a time
pipeline.batch.delay50 msHow long to wait to fill a batch
queue.typememorypersisted writes the queue to local disk
queue.max_bytes1,024 MBSize of the persisted queue, per pipeline
dead_letter_queue.enablefalseKeep events that Elasticsearch refuses with 400 or 404

Where should parsing happen?

PlaceGood forCost
In the application: JSON logsAlmost always the first choiceTeams must agree on field names
Shipper processorsSmall changes, dropping noise earlyWork on every host
Ingest pipelineParsing with no extra serversCPU of the Elasticsearch nodes
LogstashMany sources or targets, lookups, a disk queueAnother service to run and watch

Do you need Logstash?

Buffer

Bursts and slow targets

When Elasticsearch is slow, it refuses bulk requests, Logstash keeps trying, its queue fills, and it stops taking events. The shipper then waits at its offset. This back-pressure is healthy as long as the files live longer than the problem.

How long does a full-size persisted queue last?

t=1024×220 B2000 events/s×500 B=1.07 GB1 MB/s≈1074 s≈18 mint = \frac{1024 \times 2^{20}\ \text{B}}{2000\ \text{events/s} \times 500\ \text{B}} = \frac{1.07\ \text{GB}}{1\ \text{MB/s}} \approx 1074\ \text{s} \approx 18\ \text{min}
Assumed: 2,000 events a second of 500 bytes, and nothing drained meanwhile.

A log broker for hours instead of minutes

Shippers on servers write to a Kafka topic named logs. Logstash workers of one consumer group read from it and send bulk requests to Elasticsearch.
Kafka keeps the events on several machines, so a dead Logstash disk loses nothing, and other consumers can read the same topic.

A persisted queue is on one disk and is not replicated. For longer outages, or to feed several systems, put Kafka in between. See log-based queues.

Store

Data streams and rollover

The name has three parts: logs-checkout-prod is type, dataset and namespace. Writes go to the newest hidden index. A search looks at all of them. Names make access rules and retention easy: one pattern covers one team.

One stream, several indices

Removing an index frees its files at once. Deleting documents one by one only marks them.
JSON
PUT _ilm/policy/app-logs{  "policy": {    "phases": {      "hot":  { "actions": { "rollover": { "max_primary_shard_size": "50gb", "max_age": "1d" } } },      "warm": { "min_age": "2d",  "actions": { "forcemerge": { "max_num_segments": 1 } } },      "delete": { "min_age": "30d", "actions": { "delete": {} } }    }  }}
After a rollover, the ages of later phases count from the moment of the rollover.

Data tiers

One Elasticsearch cluster with a hot part on fast disks, a warm or cold part on cheaper disks, and a frozen part with a small cache. Data moves from hot to warm to frozen as it ages, and the frozen part reads from snapshots in object storage outside the cluster.
Old data becomes cheaper and slower. Cold and frozen data can live as searchable snapshots; check that your subscription includes them.

The five lifecycle phases

PhaseThe data isTypical action
HotWritten and searchedRollover
WarmSearched, hardly changedForce merge, cheaper disks
ColdSearched rarelyFully mounted snapshot, no replica needed
FrozenSearched very rarely, may be very slowPartly mounted snapshot
DeleteNo longer neededDelete the index

Fields

Mappings, and the trap of too many fields

Elasticsearch guesses a type for every new field. keyword fields are for exact values, filters and grouping. text fields are split into words for full-text search. A service that uses user ids as JSON keys creates a new field for each user: a mapping explosion. The limit is 1,000 fields in an index by default, and a document that would exceed it is refused.

Fields that stay few

  • user.id with the value 4711
  • Names from the Elastic Common Schema
  • One type for one field in all services
  • Unknown data in one flattened field

Fields that explode

  • users.4711.status as a field name
  • status as a number here and as text there
  • A whole request body as nested JSON
  • Raising the limit and going on

Documents that do not fit can go into the failure store of a data stream instead of being refused. It must be switched on in the index template for data streams that do not have it by default. Elastic has contributed ECS to OpenTelemetry, so that the two sets of names grow together.

Search

Asking questions in Kibana

LanguageUse it forExample
KQLFiltering in Discover and dashboardslog.level : error and took_ms > 500
ES|QLFilter, calculate, group, step by stepFROM logs-* | STATS n = COUNT(*)
Query DSLJSON requests from programsA bool query with filter
SQL
FROM logs-checkout-prod| WHERE @timestamp > NOW() - 1 hour AND log.level == "error"| STATS errors = COUNT(*) BY service.version| SORT errors DESC| LIMIT 10
Which version logs the most errors? Always limit the time first: it decides how many indices are read.

From an alert to a cause

Logs explain. For the first alert, a metric is cheaper and faster.

Size

Numbers that decide

Storage before compression

2000 eventss×500 B=1 MBs;⇒;86.4 GBday×2 copies×30 days≈5.2 TB2000\ \tfrac{\text{events}}{\text{s}} \times 500\ \text{B} = 1\ \tfrac{\text{MB}}{\text{s}} ;\Rightarrow; 86.4\ \tfrac{\text{GB}}{\text{day}} \times 2\ \text{copies} \times 30\ \text{days} \approx 5.2\ \text{TB}
Peak is 3x: plan indexing for 6,000 events a second. The size on disk depends on fields and compression, so measure with your own lines.

Elastic's advice is to aim for shards between 10 and 50 GB with fewer than 200 million documents. If one day is 86.4 GB on disk and a primary shard may reach 50 GB, one primary rolls over after about 14 hours, and two primaries take a day each. A search uses one thread per shard, so thousands of tiny shards are slow.

In logsdb mode, Elastic measured up to 60 percent less log storage, for 10 to 20 percent less indexing speed. It is the default for new logs data streams since 9.0.

Operate

Keeping it healthy and safe

  1. 1

    Watch the delay

    Compare the time in the event with the time it was indexed. A growing gap is the first sign of trouble.

  2. 2

    Watch the disks

    At 85 percent a node gets no new shards, at 90 percent shards move away, and at 95 percent its indices become read-only. Logs then stop arriving.

  3. 3

    Watch refusals

    Parsing failures, dead letters, failure store and 429 answers each have a number. Alert on them.

  4. 4

    Protect access

    Since 8.0 a new Elasticsearch turns on passwords and TLS by itself. Kibana's own HTTPS has to be configured. Use roles per data stream.

  5. 5

    Remove secrets early

    Mask tokens and personal data in the application or the shipper. Deleting a value later is slow and never certain.

  6. 6

    Take snapshots

    Replicas protect against a lost machine, not against a wrong delete.

Licences

Names and licences, checked November 2026

ProductLicence of the sourceGood to know
Elasticsearch, KibanaYour choice of AGPLv3, SSPL 1 or Elastic License 2.0; parts in x-pack only Elastic LicenseReady-made packages come under the Elastic License 2.0
Logstash, BeatsApache 2.0 outside x-packPackages with -oss in the name are Apache 2.0
OpenSearch, OpenSearch DashboardsApache 2.0A fork from 7.10.2, at the Linux Foundation since 2024
The Elastic License 2.0 allows use and redistribution, but not offering the product to others as a managed service, and not working around licence keys. This is a summary, not legal advice.

Choose

When another tool fits better

NeedBetter choiceWhy
Alert on request rate or CPUPrometheusNumbers are far smaller than lines
Path of one request through servicesJaeger or another trace storeParent and child spans, not text
Cheap log storage, search mostly by labelGrafana LokiIndexes labels, not the content
Counting and grouping billions of rowsClickHouseColumns and SQL
No one to run a clusterElastic Cloud or another hosted service, such as DatadogYou pay instead of operating
An audit record that must never be lostA database or object storage with locksA log pipeline can drop or double events

Summary

The whole topic in one minute.

A shipper reads lines and remembers its place. Logstash or an ingest pipeline turns text into fields. Elasticsearch stores the documents in time-based indices. Kibana asks the questions.

Delivery is at least once, so give events a stable id where duplicates hurt. Put a durable buffer in front of indexing when bursts are larger than the cluster can take. Let lifecycle rules delete whole indices.

The bill is mostly stored bytes times copies times days. Fewer fields, fewer debug lines and shorter retention beat a bigger cluster.

  • Collect, process, store, look: shipper, Logstash or ingest pipeline, Elasticsearch, Kibana.
  • Delivery is at least once. The offset moves only after the acknowledgement.
  • Parse as early as possible, best by logging JSON with agreed names.
  • Data streams plus lifecycle rules: roll over by size, delete whole indices.
  • Cost is bytes times copies times days. Aim for shards of 10 to 50 GB.
  • At 95 percent disk the indices become read-only.
  • Elastic Stack is the current name, and the licences differ by product.

Sources