Published
How to Validate Loki Label Cardinality Before Migrating Kubernetes Logs
A practical Loki migration test for Kubernetes logs: measure indexed stream cardinality, preserve structured metadata, validate queries, and plan rollback.
A Kubernetes log migration can look healthy while quietly multiplying Loki streams. The collector reports successful exports, the application logs appear in Grafana, and the new backend seems responsive during a small pilot. Then deployment churn adds thousands of short-lived label combinations, ingesters spend resources holding active streams, and queries become expensive to operate. The problem is not necessarily log volume. It is the shape of the label index. Before moving production logs from Datadog or another system, establish which attributes must identify streams and which must remain queryable without becoming index labels.
This procedure is a migration acceptance test, not a generic recommendation to strip every label. It defines a controlled Kubernetes scope, an indexed-label policy, measurements for active streams and query behavior, and rollback conditions. It separates vendor-documented Loki behavior from operational thresholds selected by the engineering team. The objective is a reversible decision supported by evidence, not a claim of automatic cost savings.
Define the migration boundary and the query contract
Begin with a bounded pilot: one Kubernetes cluster, two or three representative namespaces, and an explicit sampling window that includes normal traffic, deployment churn and any scheduled batch jobs. Record the Loki version and deployment mode, collector implementation and version, tenant, retention policy, index schema, and object-storage backend. Document the current Datadog or other source route independently. A dual-write pilot must not be mistaken for a completed migration, and duplicate log delivery must be included in the traffic accounting.
Inventory the consumers before defining labels. Identify the incident queries, alerts, audit searches, service-level dashboards and on-call workflows that need to function after the cutover. For each, record the current query expression, owning team, expected event types and the maximum acceptable investigation delay as a locally approved target. Preserve representative log samples with sensitive content redacted. A migration cannot be validated by counting rows if the retained logs no longer answer the questions operators need to ask.
- Scope identifiers: cluster, namespace, environment, tenant, log source and pipeline revision.
- Critical classes: authentication and authorization events, privileged changes, application errors, ingress failures and control-plane signals required by the organization.
- Query contract: service isolation, time-window filtering, correlation by trace or request identifier, and one realistic investigation workflow per service.
- Baseline: incoming bytes and records, indexed streams, relevant query latency, collector errors and receiver rejection counts.
Understand why one additional label can create many streams
Loki uses the complete set of indexed label names and values to identify a log stream. Grafana documents that high-cardinality or short-lived label values produce many streams, increase index pressure and fragment data into small chunks. The number of labels alone is not the useful metric: even several individually bounded labels can create numerous combinations. Conversely, a small stable set can isolate high-value workloads without indexing every field in each record.
A practical starting policy uses long-lived context such as cluster, namespace, service and deployment environment as candidate index labels. Treat that as a design choice, not a universal Grafana-required schema. Pod names, container IDs, request IDs, user IDs and trace IDs vary with workload or request activity. Those fields often remain useful for investigations, but their usefulness does not make them appropriate stream identifiers. Grafana specifically warns about k8s.pod.name and service.instance.id in default OpenTelemetry-to-Loki label mappings.
Use structured metadata for frequently searched, high-cardinality fields when the selected Loki version and storage schema support it. Structured metadata travels with each log entry but is not indexed as a stream label. It is not a free substitute for indexing: metadata still contributes bytes, is subject to limits and may change query execution cost. Confirm that the deployment uses the required TSDB index and a schema version supporting chunk format V4 before relying on this feature.
Inspect the actual OTLP and collector mapping
Draw the ingestion path before changing it: Kubernetes sources -> Grafana Alloy or OpenTelemetry Collector -> OTLP HTTP exporter -> Loki distributor -> streams and structured metadata -> storage -> Grafana queries. Make a copy of the currently deployed collector configuration and the Loki tenant configuration. Note where resource attributes are created, renamed, promoted into labels, converted to structured metadata or removed. A label decision made in the collector can interact with the destination’s own OTLP mapping.
Grafana documents native OTLP ingestion with the OpenTelemetry Collector’s otlphttp exporter targeting the base /otlp path, with the exporter appending the logs endpoint. It also documents that Loki’s default index-label mapping includes Kubernetes resource attributes and that the defaults can be changed. Inspect the exact mapping in the deployed version instead of assuming a dashboard label was configured explicitly by the application. Structured metadata must be allowed for the OTLP ingestion path; turning it off can cause payload rejection.
Create one version-controlled label contract with three fields for each proposed attribute: destination (index, structured metadata, log body or intentionally excluded), justification (which query or alert requires it) and owner. Attach one example record showing the attribute’s type and expected value population. Review that contract when new workloads are added. The collector’s configuration revision and Loki’s mapping revision should be stored beside pilot measurements so a later comparison is reproducible.
Measure cardinality rather than relying on an ingestion-success signal
Run Grafana’s documented LogCLI series analysis against the pilot tenant and interval: logcli series '{}' --since=1h --analyze-labels. Review the returned distinct values and stream combinations. Repeat over a comparable interval after a deployment, restart or CronJob cycle. The series analysis describes streams visible in the queried time range; it must not be interpreted as a permanent estimate of all future workload cardinality. For large tenants, narrow the scope to the pilot service or namespace and record the filter used.
Where an API-driven check is needed, the Loki HTTP API documents label and series endpoints. Use approved tenant authentication and inspect results for the affected time range. A single successful HTTP query proves reachability, not complete collection. Compare the same time windows in the source pipeline and Loki. Count expected log records for a defined test fixture, allow for timestamp and buffering effects, and investigate discrepancies before treating a lower stream count as a success.
Collect receiver-side evidence at the same time. Record ingestion requests and accepted traffic, rate-limit or active-stream rejections, collector retry and queue behavior, and Loki ingester resource pressure using metrics present in the deployed version. Loki documents limits for active streams and ingestion, including max_global_streams_per_user, and identifies rejected-entry metrics such as loki_discarded_samples_total for certain validation failures. Do not invent a universal acceptable number of streams. Establish local ceilings from the observed workload and the receiver’s actual capacity.
- Indexed stream combinations per scoped namespace and service, measured before and after policy change.
- Unique value population for candidate high-cardinality labels during ordinary operation and deployment churn.
- Log records and bytes accepted versus source records and bytes emitted, using matching sampling windows.
- Receiver rejection and retry reasons, collector backlog, ingester memory pressure and the volume of very small chunks where observable.
- Query correctness and latency for the signed-off incident and security search fixtures.
Move high-cardinality context without breaking investigations
For one pilot service, remove k8s.pod.name or an ephemeral instance identifier from the index mapping only after confirming that the same value is retained as structured metadata or in the log body when required. Re-run the real investigation query against the new route. Grafana documents that structured metadata can be used in LogQL label-filter expressions even though it is not indexed in the stream selector. That means a query may first select stable streams by service or namespace and then filter the returned entries by a pod or trace identifier.
Query semantics matter. For example, select a bounded stream with {service_name="checkout", namespace="production"} if those are the confirmed labels in this environment, and then apply an appropriate filter for a structured metadata value. Do not copy this literal selector into production until the actual label names are known. Test whether searches can still find a specific authorization failure, trace correlation or application exception, and record both the returned events and the query duration.
Review the consequences of a label change on alerts, dashboards and saved queries. A reduction in index cardinality may break a query that explicitly used the removed label inside the stream selector. Update query expressions and alert rules in the same controlled change. Where structured metadata is involved, be aware that extracted fields can also increase the cardinality of derived LogQL metric results unless unwanted fields are excluded from the aggregation.
Use a reversible shadow-ingestion experiment
Deploy the candidate configuration to a separate pilot pipeline or otherwise isolate the test stream from the production route. Keep the original collection configuration and rollback artifact intact. Run two tests: a steady traffic window and a churn window that deliberately creates and removes representative pods. Do not use fabricated workloads as proof of real production capacity; use them only to exercise known failure modes. Keep the input workload and experiment duration recorded so differences are not confused with changing application demand.
The acceptance decision should be explicit. Fewer Loki streams are beneficial only if log delivery remains complete for required events, critical queries still work, receiver rejections are not increasing and operating costs have a credible measurement basis. A locally selected ceiling may be expressed as stream combinations per active service, query response time at a defined concurrency or maximum acceptable rejected entries. These are organization-specific SLOs, not limits prescribed by Grafana.
- Pass: index labels are stable during pod churn, approved searches return the expected records, no unexplained ingestion gaps occur and the collector/receiver remain within measured capacity.
- Investigate: streams decline but important alerts stop matching, structured metadata disappears, or the new query path becomes materially slower under representative load.
- Fail: required logs are rejected, the receiver reaches its active-stream limit, the collector cannot drain its queue, or the team cannot reproduce a security investigation.
- Rollback: restore the previous collector and Loki mapping configuration, return traffic to the known-good route, check source-to-destination continuity, and preserve both before/after evidence sets.
Failure modes that make a pilot look better than production
The first false positive is measuring one quiet hour in a namespace that has no deployment churn. The second is testing only a stable application while excluding Jobs or short-lived sidecars. The third is equating a reduced number of indexed streams with reduced total ingestion bytes. Structured metadata still consumes space, and unchanged log volume can remain expensive to process or retain. The fourth is ignoring hard rejection signals while Grafana queries appear to work against data that arrived before the rejected window.
The most damaging failure is silent loss of investigative context. Dropping a request identifier to simplify the index is different from preserving that identifier as searchable structured metadata. Likewise, moving logs away from a premium service does not inherently provide the same access controls, retention, alerting or audit evidence. Validate these properties separately with their owners. Keep a dated record of what was implemented, what was observed, what failed and who approved the cutover.
Operational sign-off checklist
- The migration scope, tenant, Kubernetes workload inventory and collector/Loki versions are recorded.
- The label contract identifies index labels, structured metadata, discarded fields and responsible owners.
- Baseline and post-change stream analyses cover both normal traffic and a deployment-churn interval.
- Representative incident, trace-correlation, authentication and administrative-event searches are demonstrated and stored.
- Ingestion and rejection metrics are reviewed against explicit local thresholds, with no unexplained missing required events.
- Dashboard and alert owners approve changed LogQL selectors and downstream behavior.
- Rollback configuration, routing switch and continuity verification are tested before moving the remaining namespaces.
This workflow yields a reproducible evidence package: scoped log fixtures, policy revision, stream analysis, receiver health, query test results and a cutover decision. It supports an architecture and cost review, but it does not establish regulatory compliance, independent assessment or authorization. For a broader migration plan, pair this focused Loki validation with the existing Datadog-to-Grafana guide and upstream telemetry-routing controls. The engineering outcome is a stable label index and preserved incident visibility, not an attractive low stream count on its own.
Related resources
- Datadog to Grafana Migration
- Reduce Datadog Log Ingestion Cost
- OpenTelemetry Gateway Cardinality Control
Sources
- Understand labels | Grafana Loki documentation
- Cardinality | Grafana Loki documentation
- What is structured metadata | Grafana Loki documentation
- Modify default OpenTelemetry labels | Grafana Loki documentation
- Ingesting logs to Loki using OpenTelemetry Collector | Grafana Loki documentation
- Loki HTTP API | Grafana Loki documentation
- Enforce rate limits and push request validation | Grafana Loki documentation
Continue reading
- How to Validate OpenTelemetry Collector Persistent Queues During Backend Outages
Validate OpenTelemetry Collector persistent queues through backend outages and restarts, measure queue recovery, and identify telemetry loss before rollout.
- Prometheus Remote Write Backpressure: Diagnose Before Adding Shards
Diagnose Prometheus remote write backpressure with sender metrics, receiver errors and reversible queue changes before increasing shard concurrency.
- How to Build an OpenTelemetry Gateway That Controls Cardinality Before Backend Ingestion
A practical OpenTelemetry Collector gateway design for controlling metric cardinality, filtering low-value telemetry, and protecting backend ingestion.
Written by
Tymur Chmeruk
Cloud Security & Infrastructure Engineer · Baltimore–Washington Metro · [email protected]