AlgoViz

Inside a logging service

medium 30 min

A logging service carries the log lines of all programs to one place where people can search them.

Video lesson · Chapter 1 of 6

Carry structured events to the index

0:00 / 4:47

Theory

Read or listen first. About 2 min.

What it is

A log is a record of one event: what happened, when, and in which program. A distributed logging service collects the logs of many programs on many machines, stores them in one place, and makes them searchable.

It is a pipeline with six jobs: generate, collect, buffer, process, index and query. Each job can be done by a different program, and each can be slow or broken without stopping the others.

Why it exists

With one server you can open a file and read it. With two hundred servers, half of which existed only for an hour, nobody can do that. The machine that failed may already be gone, and its file with it.

One request often passes ten services. To understand why it failed you need the lines of all ten together, in order. That works only if they are in one place and carry the same id.

The search must also be fast while something is broken. At that moment everybody logs more than usual, so the logging service gets its hardest test exactly when people need it.

A short history

  1. 1980s

    Eric Allman writes syslog. RFC 3164 names Allman as the inventor.

  2. August 2001

    RFC 3164 describes the syslog protocol that machines had long been using.

  3. March 2009

    RFC 5424 replaces it and adds structured data to a message.

  4. February 2010

    The first version of Elasticsearch is released. With Logstash and Kibana it later becomes the ELK stack.

  5. December 2018

    Grafana Labs introduces Loki, which indexes only labels and not the text of the lines.

  6. November 2021

    The current W3C Trace Context recommendation is published: one header that carries the id of a request.

Words to know

Structured log
A record with named fields, usually JSON.
Agent
A small program on each machine that reads log lines and sends them on. Also called a shipper.
Buffer
A queue between senders and the store that absorbs bursts and outages.
Inverted index
A list that says for each word which lines contain it.
Shard
One part of an index, on one machine.
Trace id and span id
The id of a whole request, and the id of one step of it.
Ingestion delay
The time between an event and the moment you can find it.
Retention
How long a kind of log is kept.
Backpressure
A slow receiver making the sender wait or drop.

Understand it

Start here

Captains' logbooks in the harbour office

The harbour office
123

The captains never wait for the office. They write and sail on.

At the harbourIn the system
Captain writingA service
BookA log on one machine
PorterAgent
BasketQueue
ClerkProcessor
Card with wordsInverted index
Crate numberTrace id

The idea

Six properties people want

A good logging service is

  • Central

    All lines in one place, also those of machines that no longer exist.

  • Searchable

    Find one word among billions of lines.

  • Fresh

    A line can be found seconds after it was written.

  • Scalable

    More machines, more lines, the same speed.

  • Correlated

    One id joins the lines of one request.

  • Alerting

    A pattern of errors calls a person.

Say it in one sentence: every service writes what it does, agents carry the lines to one place, an index answers questions such as "all errors of the payment service in the last hour", and one id follows a request through ten services.

Logs are one of three kinds of data. Load balancer monitoring shows how metrics, logs and traces work together, and monitoring basics explains metrics.

Requirements

What to agree on first

RequirementA target to start fromWhy it matters
Writing100,000 lines a second on average, 300,000 at peakDecides the number of partitions and shards
FreshnessSearchable within 5 secondsDecides batch sizes
SearchUnder 1 second for recent dataDecides what stays on fast disks
LossAt least once for errors and audit linesDecides buffering on disk
Search available99.9%Decides replicas and zones
RecoveryA failed node is replaced by itselfDecides replication
Targets to discuss, not facts about a product. Peak is 3 times the average.

How much is it?

100,000×500 B=50 MB/s≈4.3 TB per day100{,}000 \times 500\,\text{B} = 50\,\text{MB/s} \approx 4.3\,\text{TB per day}
50 MB x 86,400 s = 4.32 TB. The size of 500 bytes is an assumption: measure yours. A year would be about 1.6 PB of raw text.

The whole

The pipeline

From a line to an answer

A server holds a service and an agent. The agent sends lines to a queue. A processor reads the queue and writes to an index and to an archive. A search page reads the index.
Blue: reading. Pink: writing. Orange dashed: copies for the archive.

One line on its way

The processor remembers its position only after the index has the lines. So a crash repeats lines but loses none.

Who does which job

JobExamples
CollectFluentd, Fluent Bit, Filebeat, Vector
BufferKafka, Kinesis
ProcessLogstash, Vector, your own consumers
Store and indexElasticsearch, Loki, ClickHouse
Search and showKibana, Grafana
Elasticsearch, Logstash and Kibana together are the ELK stack. Elastic also counts Beats, the family Filebeat belongs to.

In the ELK stack, Logstash parses free text with patterns called grok, adds fields such as a country, and decides where a line goes. Elasticsearch stores and searches, split over shards. Kibana is the page for searching, charts and alert rules.

Write

Structured lines

Text
2024-01-15 10:23:45 ERROR Payment failed for user 123,order 456, amount 99.99 - timeout
Free text. Every question needs its own pattern.
JSON
{  "id": "01HM5Z-0001",  "timestamp": "2024-01-15T10:23:45.120Z",  "level": "ERROR",  "service": "payment",  "version": "1.4.2",  "host": "pay-7",  "environment": "production",  "trace_id": "4bf92f3577b34da6a3ce929d0e0e4736",  "span_id": "00f067aa0ba902b7",  "message": "payment failed",  "error": "timeout",  "user_id": "123",  "order_id": "456",  "amount": 99.99}
The same event with named fields.

Levels

LevelUse it forIn production
DEBUGDetails for one investigationOff, or for a short time
INFONormal steps that matterYes, sampled if many
WARNOdd but handledYes
ERROROne operation failedAlways
FATALThe process stopsAlways

Collect

Agents, push and pull

Push: the sender sends

  • Arrives quickly.
  • The sender decides what is sent.
  • Works through firewalls that allow only outgoing traffic.
  • The receiver can be flooded, so it needs backpressure.

Pull: the receiver asks

  • The receiver sets the pace.
  • Backpressure comes for free.
  • A little slower.
  • The receiver must know all senders.

Logs are nearly always pushed: Fluentd, Filebeat and direct Kafka producers all send. Pull is usual for metrics, as in Prometheus. In the middle there is pull too: consumers fetch from Kafka at their own speed. Push and pull compares both.

Four agents

AgentKnown forThink of
FluentdMany plugins. C and Ruby, over 60 MB of memory by its own comparisonRouting and changing on a central node
Fluent BitC, about 450 KB by the same comparisonOn every container host
FilebeatLight. Delivers at least onceFiles to Elastic
VectorWritten in Rust. Logs and metricsHigh volume

Why batch? A hundred lines of 500 bytes in one message need one round trip and one set of headers, and they compress well because they look alike. The price is delay: send after 100 lines or 1 second, whichever comes first.

Filebeat writes down how far it has read. After a restart it continues there and may send some lines twice. That is at least once. Give each line an id, and let the index use it as the document id: the second copy then overwrites the first.

Buffer

The queue in the middle

The queue separates those who write from those who store. If the index is slow for an hour, lines wait and nobody loses anything. If a second team wants the same lines, it reads them from the same queue. How such a log works inside is the subject of log-based queues.

How long can the index be away?

50 MB/s×3600 s=180 GB per hour50\,\text{MB/s} \times 3600\,\text{s} = 180\,\text{GB per hour}
With three copies 540 GB an hour. Keeping 24 hours needs about 13 TB. At the 3x peak it fills three times as fast.

And if the queue is away? The agent keeps lines on its own disk. A machine with 200 lines a second writes 100 KB a second, so 10 GB last 100,000 seconds, about 28 hours.

The buffer is full. What now?

Whatever is dropped is counted, so that people know the log has a hole.

Store

The inverted index

LineText
1Payment failed for user
2Order failed validation
3Payment succeeded
WordLines
failed1, 2
succeeded3
payment1, 3
order2
The question "failed" reads one entry. "payment and failed" cuts two lists: only line 1.

A new line is not searchable at once. By default Elasticsearch makes new lines visible every second, for indices that were searched in the last 30 seconds. That is why it calls itself near real time.

An index costs processor time and space for every field. Loki takes another way: it indexes only a few labels per stream, such as service and environment, and reads through the compressed text at query time. Writing is cheap, and a search without a narrow label is slow.

Index all or index labels

Full index (Elasticsearch)Labels only (Loki)
Write costHighLow
Find a rare word anywhereFastScans everything
Find it in one service, one hourFastFast enough
DangerToo many fieldsToo many label values

Split by time: one index per day or per size. A question about the last hour then touches one index, and deleting a day means dropping an index instead of deleting lines one by one. The mechanics of search are in full-text search.

Age

Hot, warm, cold, gone

TierAge, for exampleWhereQuestions
Hot0 to 2 daysFast SSDMost
Warm2 to 30 daysCheaper disks, segments mergedSome
ColdOver 30 daysObject storage such as S3Rare, slower
Elasticsearch knows hot, warm, cold and frozen tiers. The frozen one reads snapshots in object storage.

An example policy

KindHotWarmColdDelete after
Security and audit7 days90 days7 yearsWhat the law says
Application errors3 days30 days90 days1 year
Debug1 day7 days14 days30 days
Access2 days14 days30 days90 days
Each number is the age at which a line leaves the tier. Durations are decisions of your business and of the law where you work, not of the tool.

The life of an index

Ask

Questions people ask

QuestionFilter
All errorslevel:ERROR
Errors of paymentlevel:ERROR AND service:payment
One requesttrace_id:"abc-123"
Last hour@timestamp:[now-1h TO now]
Slow onesresponse_ms:>1000
JSON
{  "size": 0,  "query": { "term": { "level": "ERROR" } },  "aggs": {    "by_service": { "terms": { "field": "service" } },    "over_time": {      "date_histogram": {        "field": "@timestamp",        "fixed_interval": "1h"      }    }  }}
Errors per service and per hour in Elasticsearch. service must be a keyword field.

Always start with a time range and a service. A search for a word over everything touches every shard and slows the search of the person beside you.

Counting by reading logs is expensive. If a number is needed every minute, make a metric of it when the line is processed.

Join

One request, many logs

The same trace id everywhere

The times count from the start of the request. Each service writes its own span id and the same trace id.

The id is made once, at the entrance, and travels in the traceparent header. A service that finds no id may start a trace, but a logger that invents a new id for every line joins nothing at all.

Clocks of machines differ by some milliseconds. So the order of lines from two machines is not certain. Use the parent of each span to know which step called which.

Fail

What breaks, and what to do

FailureWhat people seeAnswer
A release logs 20 times moreQueue grows, search is lateLimit per service, sample, alert on volume
The index rejects linesHolesPut them in a separate queue, alert
One field has two typesRejected linesA shared schema, checked in tests
A user field makes thousands of fieldsIndex slowPut free data into one field
The logging service is downNobody sees itAlert from outside it

Summary

The whole topic in one minute.

A logging service is a pipeline: programs write structured lines, agents collect and batch them, a queue absorbs bursts, processors clean and enrich, an index makes them searchable, and old lines move to cheaper storage until they are deleted.

Three choices decide whether it works: every line carries a trace id, writing a line never blocks the program, and there is a plan for what to drop first. Volume decides the cost, so keep what people use.

  • Generate, collect, buffer, process, index, query.
  • Structured lines, a trace id in each, nothing secret.
  • Writing a line never blocks the program.
  • At least once plus an id per line.
  • Split by time, move to cheaper tiers, delete on purpose.
  • Volume is the cost: sample, limit, count what you drop.

Sources