WORKINGCHAPTER 13

Logs at scale: indexing, labels and the Loki vs Elasticsearch model

Pay at write time or pay at read time: the inverted index, the label index, the column store, and what each one does to your bill

55 MINOBSERVABILITYUPDATED 2026-11-02
PREDICT

You send the same 10 GB per day of JSON application logs to a single-node OpenSearch with default settings and to Loki with default settings, and keep 30 days. Roughly how do the two on-disk sizes compare at the end?

There are two questions you ask of logs. The first is a needle: show me every line that mentions order 81723, or this trace id, or this error string. The second is a scope: show me the lines from payments in the last fifteen minutes at level error. Every log backend is a bet on which of those you ask more often, and on whether you would rather pay to answer it when the line is written or when the question is asked.

This chapter takes the three answers that exist in production today, an inverted index, a label index over compressed chunks, and a column store, and puts numbers on each. The lab runs the same logs into Loki and OpenSearch side by side and then breaks Loki the way most teams break it.

The inverted index: pay at write time

Elasticsearch and its fork OpenSearch are built on Lucene, and Lucene’s central structure is the inverted index. For every field mapped as text, the analyser splits the value into terms (lowercased, sometimes stemmed), and the index records, for each term, the sorted list of documents that contain it: the postings list. A query for declined looks up one term and gets the matching document ids directly. A query for declined AND acme-pay intersects two sorted lists. Neither touches a document that does not match.

That is why full-text search over a month of logs returns in milliseconds. It is also why ingest is expensive. Every document that arrives is parsed, every text field is tokenised, every term’s postings are appended, and every keyword and numeric field also gets doc values, a column-oriented copy used for sorting and aggregations. The original JSON is stored too, as _source, so you can see the document you found. New documents land in an in-memory buffer and become searchable on each refresh, every 1 s by default (index.refresh_interval); each refresh writes a small immutable segment, and background merges rewrite small segments into large ones, which costs disk I/O for the life of the index.

The storage consequence is the number in the Predict. Per copy, a log index is commonly in the region of the raw input size, sometimes more for many short fields, sometimes less with index.codec: best_compression and careful mappings. A production cluster then keeps a replica of every shard for availability, which doubles it. Elastic’s own disk-usage guide is a list of things you can turn off to claw this back: index fields you never filter on with "index": false, use match_only_text where you never need scoring, avoid the default dynamic mapping that indexes every string twice (as text and keyword), and force-merge read-only indices.

The other failure is the mapping explosion. Dynamic mapping adds a field to the index the first time it sees a new key. Structured logs that put user-supplied keys into field names (headers.x-custom-thing, params.<anything>) grow the mapping without bound until the cluster hits index.mapping.total_fields.limit, 1,000 fields by default, and rejects documents. Every field in the mapping also costs heap on every node that holds a shard.

What you get for the cost is the strongest query model of the three: arbitrary full-text search, fast aggregations on any mapped field, and no need to know in advance which field you will search. Security teams and audit use cases that genuinely do not know the question in advance are the users this model was built for.

The label index: pay at read time

Loki takes the opposite bet. It indexes almost nothing. Each log line arrives with a small set of labels, the same idea as Prometheus labels, and the unique combination of label values names a stream. Lines in a stream are appended, in time order, to an in-memory chunk. When a chunk reaches chunk_target_size (1,572,864 bytes compressed by default), or has had no new lines for chunk_idle_period (30 m), or has been open for max_chunk_age (2 h), the ingester compresses it (chunk_encoding, gzip by default) and writes it to object storage. The index records only which chunks exist for which label set over which time range.

A query has two parts. The stream selector, {service_name="payments", deployment_environment="lab"}, goes to the index and returns a list of chunks in the time range. The pipeline after it, |= "declined" | severity_text="ERROR", runs on every line of every one of those chunks. The query frontend splits the time range into pieces and queriers decompress and scan them in parallel. There is no term lookup. The work is proportional to the bytes the selector leaves behind, which is the single most important fact about Loki performance.

So Loki is cheap to write to (append and compress, no tokenising), cheap to store (compressed chunks in S3 at object-storage prices, and the Loki docs put a 1 MB compressed chunk at about 5 MB of raw logs, sometimes 10), and its query cost depends entirely on how narrow your labels let you be. A needle query with a tight selector over an hour is fast. A needle query across every service over thirty days scans thirty days of every service, and the only way to make it faster is to add queriers.

Grafana’s original announcement in 2018 was candid about this: the design target was cheap, simple storage, and the query model was grep over the chunks the labels select.

Label discipline and the streams explosion

Labels look free, and the obvious move is to make every useful field a label. That is the most common way to break Loki.

Each stream holds its own open chunk in ingester memory. Add a user_id label with 1,000 values and every stream becomes up to 1,000 streams. Each receives a thousandth of the lines, so chunks never fill: they flush on chunk_idle_period or max_chunk_age as tiny objects. The index, which records every chunk, grows by the same factor. Queries that select all users now open thousands of small chunks instead of a few large ones, which is slower than scanning the large ones would have been. You made storage worse, memory worse and queries worse, and the only query you made faster is one you could have written as a filter.

Loki defends itself with limits under limits_config, and you will meet them in the lab:

limit default what hitting it looks like
max_global_streams_per_user 5,000 pushes rejected: “maximum active stream limit exceeded when trying to create stream …”
max_label_names_per_series 15 lines with more labels rejected
per_stream_rate_limit / _burst 3 MB / 15 MB per second one hot stream throttled
ingestion_rate_mb / ingestion_burst_size_mb 4 / 6 MB per second per tenant 429s at the client
max_line_size 256 KB long lines dropped

Grafana’s guidance puts the healthy ceiling for a very large tenant, more than 10 TB a day, at about 100,000 active streams and under a million streams in 24 hours; a tenant ten times smaller should have about ten times fewer. The rules that follow from it:

  • Labels describe where a line came from, not what it says: service, environment, cluster, namespace, region. Values that are bounded and long-lived.
  • Never label with a value that identifies a request or a user: trace id, order id, user id, request path with ids in it.
  • Add a dynamic label only when you query by it all the time and the volume per value fills chunks faster than max_chunk_age. A level label on a low-volume app splits five ways and gains nothing that | level="error" would not give you.
  • logcli series --analyze-labels '{}' shows the cardinality of every label in a tenant. Run it before and after any label change.

The lab’s Loki ingests OTLP natively, and labs/observability/loki/loki.yaml decides which OTLP resource attributes become labels with limits_config.otlp_config.resource_attributes.attributes_config and action: index_label. It promotes three: service.name, deployment.environment and service.version, which become service_name, deployment_environment and service_version (Loki replaces dots with underscores). Three services, one environment, one version: three streams. That is the whole index.

Structured metadata: where high cardinality goes

Before Loki 3, a team that wanted to filter by trace id without a label had to put it in the log line and parse it at query time with | json, which costs CPU on every line scanned. Structured metadata fixes the ergonomics. It is a set of key-value pairs attached to each line, stored in the chunk next to the line, not in the index. It requires the TSDB index and schema v13, which the lab uses, and is capped per line by max_structured_metadata_entries_count (128) and max_structured_metadata_size (64 KB).

When logs arrive over OTLP, Loki puts every resource attribute that is not an index label, every log record attribute, and the record’s trace id, span id and severity into structured metadata. The demo app’s Python services send their extra={...} fields as log record attributes, so a payments line carries order_id, amount_cents, idempotency_key and charge_id as metadata with no parsing:

{service_name="payments"} | trace_id="4bf92f3577b34da6a3ce929d0e0e4736"
{service_name="gateway"} | ms > 500 | user="42"

Read what that does and does not buy you. The metadata filter runs after the stream selector, on the lines the selector returned. It saves the parse, not the scan. A query that selects every stream for thirty days still scans thirty days. Structured metadata is where high-cardinality fields belong, but it does not turn Loki into an index of them.

The column store: a third way

The third design stores logs as rows in a columnar database, most often ClickHouse. Each field is a column stored contiguously on disk, sorted by an ORDER BY key such as (ServiceName, Timestamp). Similar values sit next to each other, so they compress well: ClickHouse’s own logging walkthrough measured 14 to 33 times compression on collected logs. A query that filters on two fields and counts reads two columns, skips granules whose min/max timestamp is outside the range, and never touches the message column. Full-text search is a scan of the body column, optionally accelerated by a skip index such as tokenbf_v1, a Bloom filter per granule that rules blocks out without being an inverted index.

Uber’s log platform is the public case study. In 2021 they described moving from ELK to ClickHouse with a schema that stores arbitrary fields in typed arrays: a single ClickHouse node ingested about 300,000 logs per second, roughly ten times a single Elasticsearch node, and hardware cost fell by more than half. Their other number is the telling one: of all the fields they had been indexing, about 5% were ever queried.

Honeycomb’s storage engine is the same idea taken further: a purpose-built distributed column store with no indexes at all, so nobody has to decide in advance which field will be fast. The cost of the columnar approach is operational: you run a database, you design its schema and sort key, and a log line with a new field needs a schema answer (a map column, typed arrays, or the JSON type).

What each one costs

Prices change; ratios do not. Take 1 TB of raw logs per day, kept 30 days, and the AWS us-east-1 list prices at the time of writing for storage only: S3 Standard about $0.023 per GB-month, gp3 block storage about $0.08 per GB-month.

Elasticsearch / OpenSearch Loki ClickHouse
bytes stored per raw byte ~1× per copy, ×2 with one replica ~0.1 to 0.2 (5 to 10× compression) ~0.03 to 0.07 (14 to 33×)
30 days on disk ~60 TB on SSD ~4 to 6 TB in S3 ~1 to 2 TB on SSD or S3
storage per month ~$4,800 ~$100 to $140 ~$80 to $160
ingest CPU high: tokenise, index, merge low: append and compress low to medium: columnar insert in batches
query you are good at any term in any field, instantly narrow label scope, then grep aggregations and filters over few columns
query you are bad at none for search; heavy aggregations over months need care needle across everything over long ranges full-text over huge bodies without a skip index

Storage is not the whole bill. Elasticsearch’s hot tier needs CPU and heap to index at the rate you ingest, which is usually the larger line. Loki moves cost into query time: a team that runs hundreds of wide queries a minute pays for queriers and for S3 GET requests. ClickHouse costs engineering time. But the storage row explains why so many teams that started on ELK have moved bulk application logs elsewhere.

Retention tiers

All three let you keep recent data fast and older data cheap, and the mechanism shapes your bill as much as the backend.

  • Elasticsearch has data tiers (hot, warm, cold, frozen) driven by index lifecycle management. Frozen indices live in object storage as searchable snapshots and are fetched on demand, which is slow but cheap. OpenSearch has Index State Management to the same end.
  • Loki has one tier, object storage, so a 30-day and a 365-day retention cost the same per GB. Retention is enforced by the compactor (compactor.retention_enabled: true) from limits_config.retention_period, and retention_stream sets per-selector overrides, for example 7 days for {level="debug"} and 90 for {namespace="payments"}. The lab keeps 48 h.
  • ClickHouse has table TTL clauses that delete or move parts to a cheaper volume after an interval.

A common shape: 7 to 14 days in the fast tier for incident debugging, 30 to 90 days cheap for investigations, a year or more in an archive only compliance reads. The first decision is how much the fast tier needs to hold, and the answer is almost always smaller than the default.

Choosing

Loki fits when most questions start with a service or a namespace, when logs are linked from traces and metrics by trace id, and when the budget is the constraint. Elasticsearch or OpenSearch fits when the questions are not known in advance and must be answered fast over long ranges, which describes security analytics more than application debugging. ClickHouse fits when you want analytics over structured fields at scale and have people to run a database. Plenty of organisations run two: cheap bulk logs in Loki or ClickHouse, a filtered security-relevant stream in a SIEM built on an inverted index.

LAB Same logs, two backends, then a label that breaks Loki ~90 MIN
YOU NEEDDocker Desktop or Docker Engine with Compose v2the ATLAS repo cloned, working in labs/observabilityabout 6 GB of RAM free (the stack plus a 1 GB OpenSearch heap)curl and jqon Linux: vm.max_map_count set to 262144 (sudo sysctl -w vm.max_map_count=262144)

You will add a single-node OpenSearch to the demo stack, send the same OTLP logs to it and to Loki, compare disk and query time, then give Loki a user_id label and watch the stream count.

1. Start the stack with JSON logs and OTel on, at 50 RPS.

cd labs/observability
cat > .env <<'EOF'
OTEL_SDK_DISABLED=false
LOG_FORMAT=json
OTEL_SEMCONV_STABILITY_OPT_IN=http/dup
LOADGEN_RPS=50
EOF
docker compose --profile telemetry up -d --build
curl -s 'localhost:3100/loki/api/v1/label/service_name/values' | jq -c .data
After a minute the label query returns ["gateway","orders","payments"]. Those values come from the OTLP resource attribute service.name, which loki/loki.yaml promotes to a label.

2. Add OpenSearch. Create compose.opensearch.yaml next to compose.yaml:

services:
  opensearch:
    image: opensearchproject/opensearch:3.3.2
    profiles: ["telemetry"]
    environment:
      - discovery.type=single-node
      - bootstrap.memory_lock=true
      - OPENSEARCH_JAVA_OPTS=-Xms1g -Xmx1g
      - DISABLE_SECURITY_PLUGIN=true
      - DISABLE_INSTALL_DEMO_CONFIG=true
    ulimits:
      memlock: { soft: -1, hard: -1 }
      nofile: { soft: 65536, hard: 65536 }
    ports: ["9200:9200"]
    volumes: ["osdata:/usr/share/opensearch/data"]
volumes:
  osdata:

The security plugin is off because this is a lab on localhost; never expose a node configured like this. Then add an exporter to otel/collector.yaml under exporters:

  opensearch:
    http:
      endpoint: http://opensearch:9200
    logs_index: atlas-logs

and add it to the logs pipeline so both backends get every record:

    logs:
      receivers: [otlp]
      processors: [batch]
      exporters: [otlphttp/loki, opensearch]
alias dc='docker compose -f compose.yaml -f compose.opensearch.yaml --profile telemetry'
dc up -d
dc restart otel-collector
sleep 30; curl -s 'localhost:9200/_cat/indices/atlas-logs?v&h=index,docs.count,store.size'
One index, atlas-logs, with a document count that climbs by roughly 300 per second: each checkout writes about six log records across the three services. If the collector logs connection refused for OpenSearch, the node is still starting; the exporter retries. The OpenSearch exporter in the lab’s Collector release is marked unmaintained upstream, which is fine for a comparison and a reason to think twice before building on it.

3. Look at one document. Before you write queries, see how the exporter mapped the OTLP record:

curl -s 'localhost:9200/atlas-logs/_search?size=1&q=charge' | jq '.hits.hits[0]._source'
curl -s 'localhost:9200/atlas-logs/_mapping' | jq '[paths(type == "object" and has("type"))] | length'
The document has body, severity, traceId, spanId, an attributes object with the Python extra fields (order_id, amount_cents, idempotency_key) and a resource object with service.name. The second command counts mapped fields, a few dozen. Every one of them has an index and doc values on disk. If your field names differ, use the ones you see in the queries below.

4. Let it run for an hour, then compare disk. Leave loadgen at 50 RPS (if you open a new terminal, define the dc alias again). Loki holds recent chunks in memory until they fill or idle, so flush it first for an honest comparison:

curl -s -X POST localhost:3100/flush
sleep 10
docker run --rm -v atlas-observability_lokidata:/loki alpine:3.20 du -sh /loki/chunks
curl -s 'localhost:9200/atlas-logs/_refresh' >/dev/null
curl -s 'localhost:9200/_cat/indices/atlas-logs?v&h=docs.count,store.size'
About a million records in each. On a laptop, expect Loki’s chunk directory (read from its volume by a throwaway Alpine container) in the tens of megabytes and the OpenSearch index in the hundreds of megabytes: a ratio of roughly 5 to 15 times. Your exact numbers depend on line length. Now run curl -s -X POST 'localhost:9200/atlas-logs/_forcemerge?max_num_segments=1', wait for it to return, and look again: the index shrinks because merging discards per-segment overhead, which is why read-only indices are force-merged in production.

5. Time three queries on each. Pick a trace id from a recent payments line first:

TID=$(curl -sG localhost:3100/loki/api/v1/query_range --data-urlencode 'query={service_name="payments"}' \
  --data-urlencode since=5m --data-urlencode limit=1 | jq -r '.data.result[0].stream.trace_id')
echo $TID

Then the needle (one trace across all services), the scoped filter (payments errors) and the rare word (declined anywhere), over the last hour. Loki reports its execution time in data.stats.summary.execTime (seconds); OpenSearch reports took (milliseconds):

lq() { curl -sG localhost:3100/loki/api/v1/query_range --data-urlencode "query=$1" \
  --data-urlencode since=1h --data-urlencode limit=1000 \
  | jq -c '{lines: ([.data.result[].values[]] | length), execTime: .data.stats.summary.execTime, bytes: .data.stats.summary.totalBytesProcessed}'; }
lq "{service_name=~\".+\"} | trace_id=\"$TID\""
lq '{service_name="payments"} | severity_text="ERROR"'
lq '{service_name=~".+"} |= "declined"'

oq() { curl -s 'localhost:9200/atlas-logs/_search' -H 'Content-Type: application/json' -d "$1" \
  | jq -c '{hits: .hits.total.value, took_ms: .took}'; }
oq "{\"size\":1000,\"query\":{\"term\":{\"traceId\":\"$TID\"}}}"
oq '{"size":1000,"query":{"bool":{"filter":[{"term":{"resource.service.name":"payments"}},{"match":{"severity.text":"ERROR"}}]}}}'
oq '{"size":1000,"query":{"match":{"body":"declined"}}}'
OpenSearch answers all three in single-digit to low tens of milliseconds, because each is a postings lookup. Loki’s needle query scans every stream for an hour and reports bytes in the hundreds of megabytes and an execTime of a second or more on a laptop; the payments-only query scans a third as much and is faster. The two error queries return nothing unless you set FAULT_ERROR_RATE: try FAULT_ERROR_RATE=0.05 dc up -d payments, wait a minute, and run them again. The pattern to take away: Loki’s cost tracks bytes, which you control with the selector, and OpenSearch’s tracks almost nothing at query time because you paid at step 4.

6. Make user_id a Loki label. The gateway logs the user as the record attribute user. Promote it in the Collector: add these processors to otel/collector.yaml

  transform/userid:
    error_mode: ignore
    log_statements:
      - set(log.attributes["user_id"], log.attributes["user"]) where log.attributes["user"] != nil
  groupbyattrs/userid:
    keys: [user_id]

set the logs pipeline’s processors to [transform/userid, groupbyattrs/userid, batch], and in loki/loki.yaml add - user_id to the attributes list under index_label. groupbyattrs moves the attribute onto the resource, which is the only place Loki will take an index label from. Then:

dc restart loki otel-collector
for i in 1 2 3 4 5 6; do
  curl -s localhost:3100/metrics | grep -E '^loki_ingester_(memory_streams|memory_chunks)\{?' 
  docker stats --no-stream --format '{{.Name}} {{.MemUsage}}' | grep loki; sleep 30
done
loki_ingester_memory_streams climbs from a handful to about 1,000 within a few minutes, one stream per user who has checked out, and loki_ingester_memory_chunks follows it. Loki’s resident memory rises with it. Run curl -sG localhost:3100/loki/api/v1/series --data-urlencode 'match[]={service_name="gateway"}' | jq '.data | length' to count streams directly. Nothing is faster: a query by user was already possible as | user="42" on three streams.
Set max_global_streams_per_user: 500 under limits_config in loki/loki.yaml and restart Loki. Within a minute the Collector’s log (docker compose logs otel-collector | grep -i 429) shows rejected pushes, and the body names the cause: “maximum active stream limit exceeded when trying to create stream”. Lines for users past the 500th are being dropped while everything else keeps working, which is the worst kind of failure: silent and partial. Remove user_id from the index labels and both processors, restart, and the stream count falls back to three after the old streams idle out. Then remove opensearch from the pipeline, restart the Collector, and run dc stop opensearch to free the memory. Finally delete the LOADGEN_RPS=50 line from .env and run docker compose --profile telemetry up -d loadgen; the other three lines stay for the rest of the module.
DECIDE

Your company ships 2 TB of application logs a day from 150 services. Engineers query them during incidents, almost always starting from a service name or a trace id linked from Grafana. The security team also needs ad-hoc full-text search over 90 days of authentication and admin-action logs, about 30 GB a day of the total. Today everything sits in a self-managed Elasticsearch cluster that costs more than the rest of the observability stack combined. What do you propose?

READING
  1. DOC
    Loki label best practices

    The official rules for static versus dynamic labels, why streams split chunks, and the stream ceilings quoted above. Read all of it before you add a label; it is short.

  2. POST
    Loki: Prometheus-inspired, open source logging for cloud natives Goutham Veeramachaneni, 2018

    The original design rationale: index labels, store compressed chunks cheaply, grep at query time. The architecture has moved on since alpha; the bet has not.

  3. DOC
    Inverted Index (Elasticsearch: The Definitive Guide)

    A clear two-page explanation of terms, postings lists and analysis. The guide covers 2.x and is unmaintained, but this chapter of it is still exactly how Lucene works.

  4. DOC
    Tune for disk usage

    The list of knobs that make an inverted-index log cluster smaller, from mappings to codecs to force merge. Useful both for tuning and as an inventory of what the defaults cost you.

  5. POST
    Fast and Reliable Schema-Agnostic Log Analytics Platform Chao Wang and Xiaobing Li (Uber), 2021

    Uber's move from ELK to ClickHouse with real numbers: ingest per node, hardware cost, and the 5% of indexed fields that were ever queried. Skim the schema section; read the motivation and results.

  6. POST
    Building an Observability Solution with ClickHouse, Part 1: Logs Dale McDiarmid, 2023

    Measured compression ratios for real collected logs and the reasoning behind ORDER BY keys for log tables. Skip the agent configuration sections unless you are building it.

  7. POST
    Why Observability Requires a Distributed Column Store Alex Vondrak (Honeycomb), 2024

    The argument for no indexes at all: scan columns in time-bounded segments so no field has to be chosen as fast in advance. It sets up the wide-events chapter in module O3.

All companies and people in these examples are fictional. Any resemblance to a real business or person is unintended.

RECALL CARDS Tap to flip. They join your review deck when you mark the lesson complete.
NEXT: Frontend and mobile: RUM, Core Web Vitals, session replay →