Log Aggregation and Query: Choosing Between Loki and ELK
When a service grows from one machine to dozens, grep stops working: failure information is scattered across hosts, and the first step of any investigation becomes "find which file on which machine". Centralised logging collects those scattered logs into one platform so that queries replace logins, and one search covers every instance.
The hard part of centralised logging is not collection but how long you keep it, how much you keep, and how you query it. A hundred gigabytes a day is easy to ingest and a project-sized decision to keep for three months. What decides the size of that bill is almost a single factor: the indexing strategy. Where the index is built and how much it contains shapes write cost, storage cost, and the shape of your query capability all at once.
Grafana Loki takes that trade to its limit: index a small set of labels, compress log content into blocks, and at query time locate streams by label and stream-scan the contents. The choice makes it an order of magnitude cheaper and makes fuzzy content search slower. This article explains the difference between the two paradigms, then label design, LogQL and its execution order, retention tiers and collection-side reduction, and finally a selection table and rollout order. For the collection and host-level side, see Server Log Monitoring.
1. Two Paradigms: Full-Text Indexing versus Label-Only Indexing
The most useful way to split logging platforms is to ask one question: what does it index? Elasticsearch indexes every word of every line; Loki indexes only the labels attached to a log stream. That difference drives every cost, performance characteristic, and usage pattern that follows.
1.1 Full-text indexing: writing every word into an inverted index
Systems in the Elasticsearch family parse and tokenise each log line at write time and maintain, for every term, an inverted index of which documents contain it. The payoff is immediate: any keyword, any field combination is an index lookup returning in seconds or less, essentially independent of total data volume.
The cost is just as direct, and it multiplies. First, the index occupies space — posting lists, term dictionaries, field metadata, plus temporary space kept for segment merges — and index size routinely exceeds raw data size. Second, writing pays tokenisation and indexing CPU, so the larger the log volume, the higher the share of cluster resources spent just receiving. Third, sharding and segment merging require continuous tuning: too many shards and query coordination overhead dominates, too few and individual shards grow large and recovery slows, and a poor merge policy amplifies disk writes. None of these is solved by one configuration pass; all of them need someone watching long term.
So the real cost of full-text indexing is not "expensive storage" but "expensive storage, expensive write compute, and expensive human operations, all at once". It earns that price where complex retrieval and ad-hoc aggregation are common; treating it as the default makes logging — something that should be cheap — expensive.
1.2 Label-only indexing: compress content and scan it sequentially
Loki does the opposite. The collector attaches a set of labels to each log line, lines sharing a label set form a stream, lines in a stream are appended in time order and packed into chunks, chunks are compressed and written to object storage, and the index records only which stream, which time range, and where the block lives — never which words appear inside.
A query therefore runs in two steps: use labels to select candidate streams and a time range, then fetch those chunks, decompress them, and scan line by line for content filters. Because chunks are read sequentially, compress well, and live on cheap object storage, the per-byte cost is far below a full index. And because you scan candidate streams rather than everything, a good label selection keeps the scanned volume small.
This design is extremely efficient for "known service, known environment, show me the error logs" — which is the overwhelming majority of real troubleshooting. What it handles poorly is the opposite: no idea which stream the line is in, and a plain keyword hunt through the body. Understanding that boundary is worth more than memorising any selection conclusion.
1.3 State the trade-off accurately
The accurate statement: Loki trades "the ability to search by content" for "storage and write cost", not "query speed" for "cost". For queries where labels eliminate more than ninety percent of the data, it is not slow at all; what is slow is a query where labels eliminate almost nothing and the body must be scanned in full.
That also explains why two teams running the same Loki reach opposite verdicts. Teams with sound label design troubleshoot in milliseconds to seconds; teams that put user IDs and request IDs into labels explode their stream count, end up with many tiny chunks and poor compression, and watch queries schedule across thousands of streams — slow and expensive.
The two paradigms are not mutually exclusive. The pragmatic arrangement is to run Loki as the primary log store for every environment and service, and route the small subset that genuinely needs complex retrieval — security audit, structured business events — into a full-index system. The deciding factor is not taste but what ninety percent of your queries look like.
2. Label Design: The Step That Decides Everything
In Loki, labels are not metadata attached to data; they are the data model. They decide how many streams exist, how large chunks grow, and how much a query must scan. Getting labels wrong does not cost you a little speed — it turns the system from usable into unusable.
2.1 Low cardinality: what deserves to be a label
One rule is enough: a label's value set must have a firm upper bound that is small enough to enumerate. Dimensions that qualify include service name, environment (prod/staging), region, log level, cluster, container name, and namespace — typically single digits to dozens of values, and a few hundred streams when combined.
"Log level as a label" is the one people push back on: five or six values looks perfectly low-cardinality, yet making it a label splits one stream into five, slows chunk fill, and worsens compression. The more common practice is to leave level out of the labels and filter on content at query time with something like | level="error" or |= "ERROR". Whether level deserves a label depends on whether "errors only" is a high-frequency query for you; if it is, and error lines are a small fraction, a label can genuinely reduce scanned bytes.
A second rule: labels should exist at the source, not be extracted from the body afterwards. Metadata the collector already has — container name, namespace, node, file path — is free. Pulling fields out of log text with a regex to use as labels adds collection cost and breaks whenever the log format changes.
2.2 Why request_id, user_id, and trace_id are a disaster
Making high-cardinality fields into labels is the single most common self-inflicted incident in home-grown logging. The mechanism is simple: a stream's identity is its label combination, so every new combination opens a new stream. As many distinct user IDs as you have, that is how many streams you may get.
The consequences cascade. First, each stream holds few lines, chunks never fill, and compression collapses — compression relies on adjacent lines in the same stream being highly similar, and shredding the data destroys that similarity. Second, an exploding stream count grows the index itself, which was supposed to stay tiny. Third, queries cannot select the target by label and must schedule across a huge number of small streams, where scheduling overhead dwarfs scanning overhead. Fourth, per-stream metadata overhead on the collector and the writer multiplies by the stream count, and memory gives out first.
The right home is unambiguous: request_id, trace_id, and user identifiers are fields inside the body. Emit them as part of structured JSON or logfmt, and filter on the parsed value. To follow one request across systems, use the trace data in distributed tracing, whose data model exists precisely for exact lookup by ID — not log labels.
3. The Three Stages of LogQL
LogQL looks like PromQL, but evaluating it is a pipeline: select streams, filter, parse, aggregate. Understanding that order matters more than memorising syntax, because the cost of each stage differs by an order of magnitude.
3.1 The stream selector: the starting point sets the cost
Every query starts with a stream selector such as {app="api", env="prod"}. It requires at least one non-empty matcher — you cannot write a pure-regex "select everything" like {env=~".*"}, which would make the engine scan every stream. This is a deliberate constraint: it forces you to say who you are looking at before you look.
The narrower the selector, the less work every later stage does. That is why label design deserves the argument: the selector is the only place that can use the index, and everything after it is brute-force scanning. A common mistake is putting a condition in the filter stage that belongs in the selector: {app="api"} |= "prod" scans every stream of app=api, while {app="api", env="prod"} scans a subset. The cost difference can exceed tenfold.
3.2 Filtering and parsing: |=, !=, |~, and | json
Filtering is line-level and comes in four forms: |= contains a substring, != excludes a substring, |~ matches a regex, and !~ excludes one. Their costs are ordered: substring matching is fastest because it runs over the decompressed byte stream directly, and regex is slowest because a pattern engine must run per line. Prefer substrings over regex — on high-volume systems this alone saves a great deal of query time.
Parsing happens after filtering: | json expands a JSON body into fields, | logfmt handles key=value. Parsing costs something, so order is critical: use cheap filters to cut candidates down first, then parse. Doing | json first and filtering on fields afterwards means parsing every candidate line — over a wide time range, that is the most common performance incident there is.
A useful shape is coarse-then-fine: cut the line count to the thousands with a substring filter, then parse, then apply exact conditions on parsed fields. If you control the log format, place key fields early in the line so a |= can match sooner.
3.3 Aggregation: turning logs into metrics
LogQL aggregation turns a range of logs into a time series using count_over_time, rate, or bytes_rate, combined with sum by (...) and topk. Its value is cross-validation: the metric side shows the shape of a rate or quantile, and the log side shows which lines produced it.
A typical form counts error-log rate per service:
sum by (app) (
rate({env="prod"} |= "level=error" [5m])
)
Queries like this can feed a Grafana panel (see Prometheus and Grafana Basics) or drive log-based alerting through Loki's ruler. One boundary matters: never compute with logs what a metric can answer. Every log aggregation evaluation scans raw logs, which is far more expensive than reading a precomputed metric. Log aggregation is right for "what do the errors look like and which field clusters them"; it is wrong for high-frequency, long-running "how many errors are there".
4. Query Cost and Execution Order
4.1 Time range, regex complexity, and returned lines
Three factors set the cost of a query: the time range, the number of streams and lines scanned, and the per-line processing complexity. They multiply rather than add. A query that looks reasonable can become a hundred times more expensive when its time range grows from one hour to seven days, because two orders of magnitude more chunks must be read.
A few habits are worth enforcing. Start with a short window while troubleshooting, confirm the shape, then widen. Use limits so a million lines never land in a browser. Keep "last 30 days" out of log panels — metrics panels read metrics, and only log panels read logs. None of this is architectural, yet it decides whether a platform gets used at all: a platform where every query takes three minutes is abandoned within a fortnight.
4.2 Get the order wrong and you scan everything
The cost gap between correct and incorrect order deserves its own emphasis. The engine executes in the order you wrote, and it will not reorder for you: parse-then-filter parses every candidate line; regex-then-substring runs a regex over every candidate line; a wide selector that pushes label-level conditions into content-level filtering hands the index's job to the scanner.
A self-check: read the query left to right and ask, after each step, how many lines remain. If the first step leaves all the data, the query is misdesigned; ideally the selector leaves a small fraction and every later step converges quickly. That reading habit beats memorising any optimisation trick.
4.3 Recorded queries and log alerting
Loki can precompute frequently used queries as recorded metrics and can also use the ruler to evaluate periodically and fire alerts. The division of labour matches Prometheus exactly: expensive computation happens once and is reused, and alerts only reference results and compare simply.
The split to aim for: log statistics spanning days or weeks and referenced by several panels become recorded rules; a handful of critical conditions such as "more than N errors of this kind in five minutes" are written directly in the ruler; everything else stays on-demand in the UI. Turning every frequently used UI query into a recorded rule converts Loki into a permanently saturated scanner, which is the opposite of its design intent. For how log alerts should be tiered and inhibited once they exist, see Designing Prometheus Alert Rules and Alerting Design Basics.
5. Retention and the Shape of the Bill
5.1 Hot, warm, and cold tiers
The value of a log line decays extremely fast. Almost all investigation happens minutes to days after an event; past a month, access frequency approaches zero. Retention policy should follow that fact in tiers: a few days hot (fast queries), tens of days warm (queryable, slower is acceptable), and anything older compressed and archived to object storage (thawed only in rare cases).
Loki sets retention per stream and deletes expired chunks automatically, without the index lifecycle and segment-merge management a full-index system needs. That is a real operational advantage: there is no "how should the index roll" question requiring long-term tuning; configure once and let it run.
The key to tiering is admitting that you may not need "queryable at any time within a year". Write that assumption down, then ask when anyone actually queried three-month-old logs — the answer usually removes half the storage budget.
5.2 The real cost is retention length
In a log bill, writing and querying are usually the small parts; retention length is the large one. The reason is arithmetic: daily volume multiplied by retention days is the standing volume, and standing volume sets the storage bill, while write and query costs track "how much happened today" and do not grow with retention.
So the most effective cost control is not a compression algorithm but the retention decision. The next most effective is how much you collect, which is the following chapter. Both require business judgement — which logs deserve ninety days and which deserve seven — and only people who know what the logs are for can make it.
A practical approach is to tier by service rather than applying one rule per environment: keep transaction-critical logs longer, and keep debug output, health checks, and static-asset access logs short or out of the platform entirely. If you already run the Grafana stack, cost attribution is covered in Grafana Cloud Cost Attribution.
6. Reducing Volume on the Collection Side
6.1 Dropping, sampling, and structured replacement
The cheapest log is the one never collected. Collection-side reduction comes in three kinds, ranked by value: dropping, sampling, and replacing long prose with structure.
Dropping is the most effective. Health-check access logs, 200s for static assets, and heartbeat debug output make up a large share of volume with almost no diagnostic value. Drop them at the collector, not after ingestion — by then the cost is already paid.
Sampling fits cases where volume is high but any single line might matter, such as verbose debug output. Proportional sampling breaks traces; semantic sampling such as "keep the first error per request" is more useful. Structured replacement means emitting JSON with separate fields instead of concatenating ten fields into a human sentence: lines get longer, but the need to scan everything in order to isolate a class of events largely disappears.
6.2 Stop using "log it, then count it" for metrics
A frequent anti-pattern: business code writes a log line and then counts occurrences by querying logs. It works functionally and costs enormously, because every count scans raw logs for something a counter should have recorded.
The criterion is simple: if a question only needs "how many times", use a counter metric; if it needs "which specific occurrences, with what context", use logs. Split along that line and many "our log volume is too large" problems evaporate, because they were metric requirements implemented as logs in the first place.
6.3 Three classic misuses
Treating logs as a reporting database is the most common. Building daily, dimensional, or cross-month business reports on the log platform means scanning history in full every time, with unpredictable cost and latency. Those needs belong in a warehouse or analytical store; logs only need to retain context for investigation.
Treating logs as an audit store is the second. Audit demands immutability, long retention, and controlled access, while log platforms compress retention periods, allow deletion, and do not guarantee write-once semantics. Compliance needs a dedicated audit store, separated from the start.
Infinite retention is the third and the most expensive. Its cost does not appear on day one; it appears in month eighteen as a bill nobody can explain and nobody dares to cut, because nobody knows who depends on it. The only way out is to tag each class of log with its purpose and retention period at collection time.
7. Selection Table and Rollout Order
7.1 A comparison table
| Dimension | Full-text indexing (ELK family) | Label-only indexing (Loki family) |
|---|---|---|
| What is indexed | Every term in the body | Label combinations and chunk locations |
| Storage medium | Index and documents on local or block storage | Compressed chunks on object storage |
| Content search | Index lookup, fast and weakly tied to volume | Sequential scan within candidate streams |
| Impact of label design | Affects query efficiency | Decides cost and usability |
| Operational focus | Sharding, segment merging, cluster tuning | Label governance, retention |
| Best-fit queries | Ad-hoc analysis on any field, complex aggregation | Specific logs for a known service and environment |
The selection question can be phrased briefly: if ninety percent of your investigation is "this service, this environment, what broke in the last hour", label indexing is sufficient; if ninety percent is "no idea which service, search by keyword across arbitrary fields", you need full-text indexing.
7.2 Rollout order and self-check
Step one is defining labels. List the metadata the collector already has for free, pick the dimensions with bounded value sets as labels, and leave everything else in the body. This step fixes eighty percent of your cost structure; every later optimisation works inside that frame.
Step two is defining retention. Classify logs by purpose, write a retention period for each class, and encode it in configuration. Never accept "keep everything for now, we will decide later" — that default is exactly where the month-eighteen bill comes from.
Step three is governing queries. Collect the team's frequent queries, check each one against the "how many lines remain" reading, push filters forward, and convert metric requirements into metrics. This step usually improves usability immediately, and it is the easiest way to get other people to adopt the platform.
Health can be judged by three signals: the most common investigation query returns in seconds; stream count grows with the number of services rather than the number of users; the storage bill grows linearly with retention rather than super-linearly. If all three hold, the two decisions that really mattered — labels and retention — are right. To connect log and metric observation points, see the layered view in What to Monitor. If a CDN sits in front of the site, edge logs are a separate data source; see CDN Log Analysis Scripts.
Source: Grafana Labs documentation (Loki overview, LogQL query reference, and retention). Compiled and interpreted by 16IDC.
Integration & Code Examples
Example 1: Narrowing a query step by step with LogQL
# 1) Narrow to one service in one environment by labels
{env="prod", app="checkout"}
# 2) Pipeline stages filter in order; earlier is cheaper
|= "timeout"
!= "healthcheck"
!= "probe"
# 3) Parse JSON and keep only the fields needed later
| json level="level", path="request.path", dur="duration_ms"
| level =~ "error|warn"
| dur > 800
# 4) Render something readable
| line_format "{{.level}} {{.path}} {{.dur}}ms"
The first query narrows to one stream by labels before filtering and parsing.
Example 2: Turning a scan query into a metric query
# Error lines per service per minute
sum by (service) (
rate({env="prod"} |= "error" [5m])
)
# Timeout share per route: aggregate first, then divide
sum by (path) (rate({env="prod"} |= "timeout" [5m]))
/
sum by (path) (rate({env="prod"} [5m]))
# Ten slowest routes in the last hour
topk(10,
max by (path) (
avg_over_time({env="prod"} | json | unwrap duration_ms [1h])
)
)
The second turns line-by-line reading into trend reading, so routine checks stop scanning the whole range.
Limitations
- They decide how many streams exist, how large chunks grow, and how much a query must scan.
- Getting labels wrong does not cost you a little speed — it turns the system from usable into unusable.
- One rule is enough: a label's value set must have a firm upper bound that is small enough to enumerate.
- Filtering is line-level and comes in four forms:
|=contains a substring,!=excludes a substring,|~matches a regex, and!~excludes one.
FAQ
Can Loki fully replace Elasticsearch for log search?
No, split the work by query shape. When about 90% of searches target one service in one environment, Loki is enough; ad-hoc field search over security audits and structured business events still belongs in a full-index system. Collecting the two log types separately costs less than indexing everything twice.
What drives monthly log costs most?
Retention days, not query volume. Write and query costs repeat daily, while stored volume is daily ingest multiplied by retention: 200 GB per day kept for 90 days is 18 TB resident. Tier retention per service, 7 days for debug logs and 90 days for core transaction logs, before tuning compression.
Why does a Loki query get slower?
At the stream selector first. Leaving the environment condition to content filtering means scanning every stream of that service before dropping lines, and parsing before filtering makes each line pay JSON cost. Validate the shape on a 1-hour window, then widen to 7 days, since cost scales with range.
What limits apply before deploying Loki?
Labels only. Cap yourself at 5-6 enumerable dimensions — service, environment, region, container, namespace — each with a value set small enough to list, so they combine into a few hundred streams. Request, user and trace IDs belong in the log body as JSON fields, or stream count grows with users until queries scan thousands of small streams.
Related Providers
- Grafana: When you would rather not run object storage and retention policies yourself, settle the label design on managed Loki in Grafana Cloud first.
- Elasticsearch: When a large share of queries are ad-hoc field searches that need an inverted index, keep the audit subset of logs here.
- Datadog: When logs must correlate with APM traces and metrics in one place, use it to check per-GB log cost on a single platform.
Community & Resources
-
Monitoring & Alerting: other coverage in this category.
Official docs and communities -
Loki documentation — Entry point for architecture, deployment and operations topics.
-
LogQL query reference — Complete syntax for selectors, pipeline expressions and metric queries.
-
Loki HTTP API — Push and query endpoints for custom collectors and scripts.
-
grafana/loki repository — Source code, release notes and issue tracking.
Learning resources and tools
- logcli usage — Command line client for batch retrieval and routine checks.
- Retention configuration — Per-tenant or per-stream retention to control storage cost.
- Grafana Loki questions — Practical questions on label design and query performance.
Original source: Grafana Loki Docs ↗