Log Pipelines and Storage

From stdout to a store: what a log pipeline is

A log pipeline is the chain that moves log lines from where they are written to where they can be queried: produce → collect → (buffer) → parse/enrich → store → query. In the seven-step pipeline of the Telemetry pipeline part this is the "collect → process → store" middle. The component at the front is a log shipper (also called a log agent or forwarder): a process on every node that reads log files or sockets and forwards them. The OTel Collector part covers the OTel Collector as a general telemetry pipeline; this part is about the log-specific parts.

Shippers and agents

AgentLanguage / ownerWhat it is good forWatch out for
FluentdRuby + C; CNCF graduatedHuge plugin ecosystem (hundreds), tag-based routing, mature buffering to diskHeavier (tens of MB RSS and up); Ruby GC under load
Fluent BitC; Fluentd sub-project (CNCF)Small footprint (single-digit MB at idle), the usual Kubernetes DaemonSet choice; handles logs, metrics and tracesFewer plugins than Fluentd; Lua/filters get awkward for complex transforms
LogstashJVM (JRuby); ElasticRich grok/filter library; persistent queue on disk; central transform tierJVM heap and startup cost; rarely run per node anymore
Filebeat / Elastic AgentGo; ElasticLightweight tailer for the Elastic stack; Elastic Agent is the unified agent managed by FleetBest fit only when the destination is Elasticsearch/Logstash/Kafka
VectorRust; DatadogFast, one binary as agent or aggregator; transforms written in VRL (Vector Remap Language); end-to-end acknowledgementsVendor-owned project; smaller ecosystem than the Fluent family
PromtailGo; GrafanaLoki's original agentEnd of life Deprecated and in LTS from 2025-02-13; EOL 2026-03-02. Replacement: Alloy (alloy convert --source-format=promtail)
Grafana AlloyGo; Grafana (Apache 2.0)OpenTelemetry Collector distribution with Prometheus and Loki components; replaces Promtail and Grafana Agent (EOL 2025-11-01); see OTel CollectorOwn config language (River-style syntax), not the Collector's YAML
OTel Collector filelog receiverGo; OpenTelemetryTails files, parses with "operators" (including a container parser), emits OTLP logs; vendor-neutralContrib distribution only; log-specific tuning knobs are fewer than in Fluent Bit

There is no universally right agent. The decision is mostly about the destination (Elastic stack → Elastic Agent/Filebeat; Loki → Alloy; OTLP everywhere → Collector) and the resource budget per node, because the agent runs on every node and its memory is multiplied by node count.

Logs in Kubernetes

Containers should write logs to stdout/stderr, not to files inside the container. The container runtime (containerd or CRI-O) captures both streams and writes them to the node's disk; the kubelet rotates them. The standard pattern is one DaemonSet (one agent pod per node) that mounts the host's /var/log read-only and tails every container's file.

  • Where: /var/log/pods/<namespace>_<pod>_<uid>/<container>/<restart-count>.log. The friendlier /var/log/containers/*.log are symlinks into it. Pod name, namespace and container name are recoverable from the path.
  • CRI log format: each line is <RFC3339Nano time> <stream> <P|F> <message>. stream is stdout or stderr; the tag is F (full line) or P (partial: the runtime split a very long line, around 16 KiB for containerd, and the agent must glue the pieces back). The older Docker json-file driver wrote JSON objects ({"log":…,"stream":…,"time":…}) instead.
  • Enrichment: the agent calls the Kubernetes API (or reads the path) to attach namespace, pod, container, node and selected pod labels. In OTel terms these become resource attributes k8s.namespace.name, k8s.pod.name, k8s.container.name (see OpenTelemetry). This is also what makes logs joinable with metrics, which carry the same labels.
  • Positions / checkpoints: the agent stores the file offset (Fluent Bit DB file, Filebeat registry, Alloy positions) so a restart resumes instead of re-reading or skipping. This gives at-least-once delivery: after a crash between send and checkpoint, lines are duplicated, not lost.
Pipeline: an application container writes to stdout; the container runtime writes a CRI-format file under /var/log/pods; a DaemonSet agent on the same node tails it, reassembles partial lines, handles multiline, enriches with Kubernetes metadata and keeps a position checkpoint. The agent sends either through an optional Kafka buffer or directly to the store (Loki, Elasticsearch or ClickHouse), which is queried from Grafana or Kibana. Below: an example CRI line and three failure notes about checkpoints, backpressure and kubelet rotation.
The Kubernetes log pipeline, container stdout to a queryable store. Read it as: the application only ever writes stdout; everything else (rotation, tailing, enrichment, buffering) is infrastructure you operate. Each stage can lose or duplicate lines, and the amber boxes are where it happens.

Multiline handling

A Java stack trace printed by a logger becomes 40 CRI lines, each its own record, unless the agent re-joins them. Multiline handling means telling the agent how to recognise the first line of a record (typically a regex on a leading timestamp) and gluing everything until the next first line. Two rules: (1) reassemble CRI P partial lines before multiline logic; (2) the better fix is upstream: log one JSON object per line and let the stack trace live inside a "stack" string field.

fluent-bit.conf (DaemonSet)

[INPUT]
    Name              tail
    Path              /var/log/containers/*.log
    Tag               kube.*
    multiline.parser  cri            # joins P/F partial lines (use "docker, cri" if mixed)
    DB                /var/lib/fluent-bit/pos.db   # offset checkpoint
    storage.type      filesystem     # buffer chunks on disk, survive restart
    Mem_Buf_Limit     50MB           # pause tailing when memory buffer is full
    Skip_Long_Lines   Off

[FILTER]
    Name                kubernetes
    Match               kube.*
    Merge_Log           On           # parse the JSON message into fields
    Labels              On

[OUTPUT]
    Name   loki
    Match  kube.*
    Host   loki-gateway
    Labels namespace=$kubernetes['namespace_name'], app=$kubernetes['labels']['app.kubernetes.io/name']

Buffering, backpressure and Kafka

Backpressure is the signal a slow consumer sends upstream ("stop, I'm full"). A log pipeline has to decide what a full stage does: block the producer, buffer, or drop. Applications writing to stdout cannot be blocked sanely, so the buffer is the agent's disk/memory and, before that, the rotated log file itself.

A log buffer such as Apache Kafka sits between agents and the store. What it buys: (1) it absorbs bursts and store outages (hours of retention, not agent RAM); (2) consumers can replay after a bad parse or a store migration; (3) multiple consumers (security SIEM, long-term archive, Loki) read the same stream; (4) the heavy parse/transform runs in a separate scalable tier. What it costs: another distributed system to size and operate, extra end-to-end latency, and more places to duplicate. The usual guidance: add Kafka when you have multiple consumers, strict loss tolerance, or ingest bursts the store cannot absorb; skip it for a single-store, moderate-volume cluster. (Kafka's own design is in the Kafka study guide in this repo.)

Elasticsearch / OpenSearch: index everything

Elasticsearch is a distributed search engine built on Apache Lucene. A log line becomes a document (a JSON object). Each field is analysed into terms and stored in an inverted index: a map term → sorted list of document ids (the postings list). A search for error AND timeout looks up two terms and intersects two sorted lists, which is why full-text search stays fast over billions of documents. Alongside it Lucene keeps doc values (columnar per-field data for sorting and aggregations) and stored fields (the original _source JSON to return).

Left, Elasticsearch: three log lines are tokenized into an inverted index mapping each term to document ids; the query error AND timeout reads two posting lists, intersects them to document 1 and fetches that document. Right, Loki: log lines are not indexed; a small label index maps label sets to streams, and each stream maps to compressed chunks in object storage; the query selects streams by label, then reads and greps every line in those chunks.
What each design indexes, and what one query touches. Read it as: amber rows are what the query touches. Elasticsearch answers from postings without reading log text; Loki narrows by label and then reads text. Same question, opposite place to pay.

Shards, replicas, and index lifecycle

  • An index is split into primary shards; each shard is a self-contained Lucene index. The primary count is fixed at creation (changing it means split/shrink/reindex). Each primary has replica shards on other nodes for availability and read throughput, which multiplies storage by (1 + replicas).
  • Logs are time-series, so use a data stream backed by hidden time-ordered indices. Rollover starts a new backing index when the current one reaches a size/age limit (common guidance: aim for shards of tens of GB, not thousands of 10 MB shards: each shard costs heap and cluster-state memory).
  • Index lifecycle management (ILM) moves backing indices through tiers: hot (indexing and frequent search, fast SSD), warm (read-only, cheaper nodes), cold (rarely searched; may use searchable snapshots), frozen (data lives in object storage as searchable snapshots, cached locally on demand), then delete. Retention is a cost lever: most debugging queries touch the last hours.

Mappings and mapping explosion

A mapping is the schema: field name → type (text analysed for search, keyword exact/aggregatable, date, …). With dynamic mapping, any new JSON key silently creates a new field. Mapping explosion is when logs carry unbounded key names (user ids or request ids used as keys, free-form maps): thousands of fields bloat the cluster state held in every node's memory and slow every mapping update. Elasticsearch caps this with index.mapping.total_fields.limit (default 1000); when hit, indexing of those documents fails. Defences: dynamic: strict or false, the flattened type for arbitrary key/value blobs, drop or rename keys in the agent, and keep high-cardinality values as values not keys.

Grafana Loki: index labels, not content

Loki is a log store pitched as "like Prometheus, but for logs". It borrows Prometheus's data model: a stream is the set of log lines sharing one unique label set (e.g. {namespace="shop", app="api", level="error"}). Only the labels are indexed. The line contents are compressed into chunks and written to object storage (S3, GCS, Azure Blob). A query first picks streams from the index by label matchers, then fetches those streams' chunks for the time range and scans them.

Components and the write/read path

DistributorStateless entry point. Validates, enforces rate/size limits, hashes the label set and forwards each stream to replication-factor (default 3) ingesters on a consistent-hash ring.
IngesterKeeps a per-stream in-memory chunk, protected by a WAL. Flushes a chunk when it reaches target size, max age, or goes idle; uploads chunk and index to object storage. Also serves recent data for queries.
Query frontendSplits a long query into time shards, queues and caches results, retries. Sits in front of queriers.
QuerierExecutes the sub-queries: asks ingesters for recent data and object storage for older; the LogQL engine does the filtering and parsing.
Index gatewayServes index lookups to queriers so each querier does not download index files itself.
CompactorMerges small index files into one per day and applies retention/deletes.

The index is stored with the TSDB index format (the Prometheus-style index, recommended since Loki 2.8 and the only supported choice for new schemas; boltdb-shipper is deprecated). Ingesters write TSDB index files per period and the "shipper" uploads them to object storage. Loki 3 introduced structured metadata: key/value pairs attached to a line (e.g. trace_id) that are stored with the chunk, are not indexed and do not create streams, and are filterable without parsing. It needs the TSDB index and schema v13. This is the right home for high-cardinality ids.

LogQL in four layers

# 1. Stream selector: the ONLY thing that uses the index (must have at least one non-empty matcher)
{namespace="shop", app="api"}

# 2. Line filters: grep the chunk text (fast, no parsing)
{app="api"} |= "timeout" != "healthz"        # contains / does not contain
{app="api"} |~ "status=(5\\d\\d)"           # regex

# 3. Parsers and label filters: extract fields at query time
{app="api"} | json | level="error" | duration > 500ms
{app="api"} | logfmt | status >= 500

# 4. Metric queries: turn logs into time series
sum by (app) (rate({namespace="shop"} |= "error" [5m]))
quantile_over_time(0.99, {app="api"} | json | unwrap duration_ms [5m]) by (route)
sum(count_over_time({app="api"} | json | status >= 500 [1m]))

Order matters for cost: put the cheapest filter first (|= before | json) so lines are discarded before the expensive parse. unwrap converts an extracted label into a numeric sample for functions like quantile_over_time. Metric queries over logs compute at query time, which is why a dashboard panel doing this every 30 seconds is expensive; a ruler can record them into Prometheus-compatible series instead (see Cost and vendors, log-to-metric).

ClickHouse as a log store

ClickHouse is an open-source column-oriented analytical database. Its main table engine, MergeTree, writes immutable sorted parts and merges them in the background (an LSM-like idea). For logs, a table is declared with a PARTITION BY toDate(Timestamp) and an ORDER BY (ServiceName, SeverityText, toUnixTimestamp(Timestamp)) sort key; a sparse primary index lets a query skip whole granules of rows. Because each column is stored and compressed separately, repetitive columns (service name, severity, status) compress extremely well, and per-column codecs (ZSTD, Delta for timestamps) and LowCardinality(String) shrink them further; text search uses skip indexes (bloom filter, tokenbf) and, newer, an inverted text index. Columnar layout makes aggregations over logs ("p99 duration by route over 7 days", "top 10 error messages") far faster than grep or Lucene aggregations. Published compression for log data is commonly in the range of ten-fold or more, but it depends heavily on schema and sort key: measure on your data.

  • Who uses it: Uber (log analytics migrated from Elasticsearch, per their engineering blog) and Cloudflare (analytics and logging pipelines) are well-known public examples; ClickHouse itself runs an internal observability platform on it ("LogHouse").
  • Products on top: SigNoz (open-source APM storing logs, metrics, traces in ClickHouse, OTel-native); HyperDX (acquired by ClickHouse, announced 2025-03-13); ClickStack (ClickHouse's open-source observability stack = ClickHouse + a preconfigured OTel Collector/schema + HyperDX UI).
  • Trade-offs: you design and own the schema (the OTel exporter ships a default); single-row lookups and tiny frequent inserts are not its strength (batch inserts, or use async inserts); full-text relevance ranking is not the goal; you operate the cluster unless using the cloud service.

Comparison

Elasticsearch / OpenSearchLokiClickHouse
What is indexedEvery term of every analysed field (inverted index) + doc valuesLabel sets only; content is compressed chunksSparse primary index on the sort key + optional skip indexes; data stored by column
Ingest costHigh: tokenizing, segment merges, replicas; CPU- and disk-heavyLow: append and compress; cost grows with stream count, not bytesLow to medium: sorted insert + background merges; batching required
Storage footprintLargest; index ≈ raw order of magnitude, times replicasSmallest: compressed text in object storage + small indexSmall: strong columnar compression; local disk or object-store-backed
Query styleFull-text search, relevance, filters, aggregations; Query DSL / KQL / ES|QLSelect streams by label, then grep/parse (LogQL)SQL: filters, GROUP BY, joins, percentile on parsed columns
Weak atCost at volume; cluster tuning (shards, heap, mappings)Needle-in-haystack across many streams; ad-hoc analytics; high-cardinality labelsSchema design is on you; point lookups; text relevance
Best forFree-text investigation, security search, when you need both search and analytics on moderate volumeCheap, Kubernetes-native logs correlated with metrics via shared labels; "I know the service, show me the lines"Very high volume with analytical questions on logs; unified logs+traces+metrics in one SQL engine

The Invariants

  • Guarantees: Elasticsearch search cost depends on matching documents, not total log volume; Loki cost per query depends on bytes in the selected streams and time range; both ship logs at-least-once when the agent checkpoints after acknowledgement; a Loki stream's identity is exactly its label set.
  • Does not guarantee: No loss during a store outage unless a durable buffer (disk queue or Kafka) outlasts the node's log rotation; no ordering across streams or nodes; no cheap needle-in-haystack search in Loki; no bounded mapping size in Elasticsearch unless you cap it; no free lunch: the signal you do not index at write time you pay for at read time.