Schema Design for Metrics Ingestion: Best Practices


TL;DR: Schema design for metrics ingestion determines how metric data is structured before it enters a storage backend. The choices you make about metric names, labels, types, and schema width directly affect query performance, storage costs, and whether your pipeline survives at scale. This guide covers the core components, naming conventions, wide vs. narrow patterns, cardinality control, and serverless-specific considerations that every developer building an ingestion pipeline needs to understand.

A metrics ingestion schema is the contract between your application code and your storage backend. It specifies the metric name, type, labels, timestamp precision, and value encoding for every data point that enters the system. Get it right, and queries are fast, storage is predictable, and your pipeline scales cleanly. Get it wrong, and you’ll face cardinality explosions, ballooning costs, and dashboards that take 20 seconds to load.

The term sits at the intersection of observability engineering and database design. Unlike application schemas that evolve through migrations, metrics schemas tend to calcify quickly. Once your app starts emitting a metric (even in QA), its name and structure become effectively permanent. That permanence makes upfront schema design for metrics ingestion one of the highest-leverage decisions in any observability stack.

If you’re building a metrics pipeline for the first time, the metrics quickstart guide walks through the full path from code to dashboard.

Core Components of a Metrics Schema

Every metrics ingestion schema consists of five elements. Understanding each one prevents the most common design mistakes.

Metric name

The identifier for what is being measured. Prometheus established the dominant naming convention: namespace_subsystem_name_unit_suffix. For example, http_server_request_duration_seconds tells you the namespace (http), subsystem (server), measurement (request_duration), and unit (seconds).

Key rules from the Prometheus naming docs:

  • Use snake_case: lowercase words separated by underscores.
  • Always include the unit in the name, using base units (seconds, bytes, meters) rather than prefixed units (milliseconds, kilobytes).
  • Do not embed label names into the metric name. http_request_duration_seconds is correct; http_request_duration_seconds_by_method is wrong.

One practitioner captured the permanence problem well in a widely shared GitHub gist: “Renaming metrics is painful and dangerous. You will not do it, or you will suffer the consequences.” Think early, think twice.

For JavaScript-specific naming guidance, see metric names and labels for JavaScript apps.

Labels (tags/dimensions)

Key-value pairs that add context to a metric. Labels like method="GET", status_code="200", and region="us-east-1" let you slice and aggregate data without creating separate metrics for every combination. The guiding principle: one concept, one metric name; everything else is a label.

Timestamp

When the measurement occurred. Most systems use Unix timestamps with millisecond or second precision. Higher precision means more storage; second-level precision is sufficient for the vast majority of application metrics.

Value

The numeric measurement itself, typically a float64 or integer. Counters emit cumulative totals; gauges emit instantaneous values.

Metric type

The type determines how the value should be interpreted. OpenTelemetry defines five standard types: gauge, sum, histogram, exponential histogram, and summary.

Metric Types in the Schema

Each metric type serves a different measurement purpose, and choosing the wrong type creates schema problems that compound over time.

Counter: A monotonically increasing value. Use for things that only go up: requests served, errors emitted, bytes transferred. The backend calculates rates from the raw cumulative value.

Gauge: A point-in-time snapshot. Use for values that go up and down: memory usage, active connections, queue depth.

Histogram: A distribution of observed values, bucketed into configurable ranges. Use for latency, response size, or any measurement where you need percentiles. Histogram bucket boundaries are part of your schema design and deserve careful thought. The histogram bucket design guide covers this in detail.

Summary: Pre-calculated quantiles computed on the client side. Less flexible than histograms because you can’t re-aggregate summaries across instances. Generally, prefer histograms unless you have a specific reason not to.

Exponential histogram: An OpenTelemetry addition that automatically scales bucket boundaries using an exponential function. Eliminates the need to manually configure bucket ranges, which simplifies schema design for metrics ingestion when you don’t know the value distribution in advance.

To get hands-on with counters and histograms, instrument counters and histograms in JavaScript provides working examples.

Wide vs. Narrow Schema

This is the most consequential structural choice in schema design for metrics ingestion. It determines how many rows you write, how efficiently you query, and how much you pay for storage.

Narrow schema (one metric per row)

Each row contains a single metric value with its metadata:

| timestamp  | metric_name              | labels              | value |
|------------|--------------------------|---------------------|-------|
| 1710000000 | http_request_duration_s  | method=GET,path=/   | 0.045 |
| 1710000000 | http_request_total       | method=GET,path=/   | 142   |

This is the Prometheus model. You keep a series table (id, metric name, labels) and a samples table (series id, time, value). It works well when metrics are sparse, dynamic, or sampled independently.

Wide schema (multiple metrics per row)

Related metrics share a row, eliminating repeated timestamps and metadata:

| timestamp  | labels              | request_duration_s | request_total |
|------------|---------------------|--------------------|---------------|
| 1710000000 | method=GET,path=/   | 0.045              | 142           |

Wide schemas can reduce storage requirements by 20-30% in high-frequency measurement scenarios and reduce query times by 40-60% for multi-parameter analysis, according to research from Quix.io.

When to use each

Use wide when your metric sets are small, stable, and emitted together. If common queries need multiple metrics at the same timestamp in one result row, wide is the clear winner.

Use narrow when metrics are dynamic, user-defined, or vary by tenant. A narrow schema avoids constant schema changes when new metrics appear.

There’s also a hybrid approach: use a narrow base table but materialize wide views for your most-queried metric combinations. Practitioners on the Altinity knowledge base describe materializing columns for the top 20% of metrics while keeping everything else in a flexible narrow format.

The schema width you choose also directly affects row counts, which matters for estimating rows, retention, and cost on usage-based platforms.

Naming Conventions That Scale

Bad naming is the most common schema design mistake, and the hardest to fix after the fact.

The rule is simple: one concept gets one metric name. All contextual information goes into labels. If you find yourself creating http_request_duration_seconds_get and http_request_duration_seconds_post, stop. The HTTP method belongs in a method label, not in the name.

A practical naming checklist:

  1. Start with an application or namespace prefix: myapp_
  2. Add the subsystem: myapp_http_
  3. Describe what is measured: myapp_http_request_duration_
  4. Append the base unit: myapp_http_request_duration_seconds
  5. Add the type suffix where appropriate: _total for counters, _bucket for histogram buckets

Never use camelCase or PascalCase. Never include dynamic values in the name. Never duplicate label dimensions in the name. These rules sound obvious, but violations are everywhere in production systems. GitLab, for example, filed an internal issue after discovering that metrics labels contained user-supplied data, leading directly to cardinality explosion.

Labels, Cardinality, and the Explosion Problem

Labels are what make metrics useful. They’re also what make metrics expensive if you’re not careful.

What cardinality means for metrics

Cardinality is the number of distinct values a label can take. A region label with three possible values (us-east, us-west, eu-west) has cardinality 3. A user_id label across a million users has cardinality 1,000,000.

Here’s the critical insight that many developers miss: the cardinality of a metric with multiple labels is the product of the cardinality of each individual label. A metric with region (3 values), method (4 values), and status_code (5 values) produces 3 × 4 × 5 = 60 time series. Add a user_id label with 100,000 values, and you’re suddenly tracking 6 million series.

Why this destroys metrics systems

In a relational database, high cardinality makes an index more useful. In a metrics system, high cardinality creates millions of separate time series that all need to be held in memory. Practitioners report that cardinality explosions cause memory spikes from 60% to 95% utilization, with dashboard query times degrading from milliseconds to over 10 seconds.

One team described resolving a production incident only after blocking the offending metric at the ingestion layer entirely, then educating the team on cardinality best practices.

Good labels vs. bad labels

Good: Low cardinality and stable. Service name, region, environment, HTTP method, status code class (2xx, 4xx, 5xx).

Bad: Unbounded or high cardinality. User ID, request ID, trace ID, session token, full URL path, dynamically generated strings.

The routing rule: High-cardinality dimensions belong in logs or traces, not metrics. Metrics systems are designed for fast aggregation across many events. Logs and traces capture individual events with arbitrary detail. Choosing the wrong telemetry backend for a high-cardinality dimension is a design error that no amount of relabeling fully fixes.

For a deeper treatment with concrete strategies, the guide on label naming and cardinality covers enforcement patterns. You can also explore the dedicated article on understanding metric cardinality.

Push vs. Pull Ingestion and Schema Impact

The ingestion model you choose shapes what your schema needs to include.

Pull model (Prometheus scraping)

Prometheus scrapes HTTP endpoints on a schedule. The schema only needs to define what’s exposed at the /metrics endpoint. This model assumes long-lived services that are consistently reachable at a known address.

It works well for traditional server-based deployments. The scraper controls the collection interval, and each scrape gets a consistent snapshot.

Push model

The application sends metrics to a remote endpoint. This adds requirements to the schema: you need to handle batch formatting, timestamp assignment, and authentication. But it removes the assumption that your process will be alive when the scraper arrives.

The serverless problem

Practitioners on the Prometheus community forum are blunt about this: “The Pushgateway is really designed for individual short-lived jobs (e.g., cron) rather than dynamic serverless applications.” For serverless or managed systems from major cloud providers, the Pushgateway doesn’t fit.

An API-first push model, where developers send counters and histograms directly from application code, sidesteps the Pushgateway entirely. This approach requires lighter schemas with bounded label sets, because each push needs to include all context (there’s no persistent process to accumulate state).

Schema Design for Serverless and Edge Ingestion

Traditional schema design for metrics ingestion assumes a process that runs for hours or days, accumulating counters and exposing them on demand. Serverless functions break every one of those assumptions.

A Cloudflare Worker or Vercel Edge Function might live for 50 milliseconds. There’s no agent to install, no sidecar to run, no /metrics endpoint to scrape. The schema needs to work within these constraints:

Fewer labels, bounded dimensions. Every label increases the row count and the payload size of each flush. In a serverless context where you’re paying per invocation and per row stored, keep labels to a maximum of 4-5 per metric. Prefer labels you can enumerate ahead of time.

Flush semantics matter. The metric data sitting in memory is worthless if the function exits before flushing. Schema design and buffering and flush strategies are tightly coupled in short-lived handlers. You need to batch efficiently and flush before the runtime terminates.

Row count awareness. On usage-based platforms, schema width directly translates to cost. A narrow schema emitting 10 metrics per request at 100,000 requests per day produces 1 million rows daily. A wide schema emitting the same data might produce 100,000 rows. That’s a 10x cost difference.

To compare how different plans handle these row volumes, compare plan features and row limits for specifics.

Schema Evolution and Versioning

Metrics schemas change. New features require new metrics. OpenTelemetry semantic conventions update across versions. Teams rename things they shouldn’t have named that way in the first place.

OpenTelemetry addresses this with schema URLs, which describe how telemetry data should be interpreted and how it can be transformed when conventions change between versions. Each telemetry payload includes a schema URL that identifies the convention version used.

For streaming-based ingestion pipelines, schema registries (like those in Confluent’s ecosystem) enforce schema validation at write time. Ignoring schema evolution leads to data corruption and pipeline failures, particularly when producers and consumers disagree about field types or label sets.

Practical rule: Design for additive-only changes. Add new metrics and new labels freely. Never remove or rename existing ones without a deprecation period. If your schema registry supports compatibility modes, use “backward compatible” as the default.

Pre-Aggregation at Ingestion Time

Not every metric needs to be stored at full resolution. Pre-aggregation at ingestion time is one of the most effective ways to control storage costs without losing the metrics that matter.

PostHog’s engineering team provides a striking example. When designing their app metrics schema, they optimized for cheap ingestion over flexible querying. The result: nearly 2 billion metrics aggregated into just 6 MB of disk using ClickHouse’s SimpleAggregateFunction and in-memory pre-aggregation before flushing to Kafka.

This tradeoff isn’t free. Pre-aggregated data loses the ability to drill into individual data points or re-aggregate along dimensions that weren’t preserved. But for metrics where you only need time-range filtering and basic aggregation (which covers most operational dashboards), the storage savings are enormous.

Common pre-aggregation strategies:

  • Rollup tables: Store 1-minute, 5-minute, and 1-hour aggregates alongside raw data. Query the coarsest resolution that satisfies the request.
  • Materialized views: In ClickHouse, create materialized views that aggregate on insert, so the raw data can expire quickly while summaries persist.
  • Client-side aggregation: Buffer metrics in the application and send pre-summed values. This reduces both network overhead and storage row counts.

For more on managing cost through retention and aggregation, see cost optimization techniques for hosted metrics plans.

Concrete Schema Example: ClickHouse Time-Series Pattern

For teams building their own storage backend, ClickHouse has become a popular choice for metrics. The optimal schema pattern for time-series data follows specific rules:

  • Put the timestamp in the ORDER BY key, but not first. Place low-cardinality filter dimensions before it.
  • Use monthly or daily partitioning for efficient TTL-based expiration.
  • Apply LowCardinality to repeated string fields (metric names, label values).
  • Use Delta and Gorilla compression codecs for float series.
  • Set TTL to automatically expire old data.

A simplified ClickHouse schema:

CREATE TABLE metrics (
    metric_name LowCardinality(String),
    labels Map(LowCardinality(String), String),
    timestamp DateTime,
    value Float64
)
ENGINE = MergeTree()
PARTITION BY toYYYYMM(timestamp)
ORDER BY (metric_name, timestamp)
TTL timestamp + INTERVAL 30 DAY;

This pattern optimizes for the two most common query patterns: filtering by metric name and scanning a time range.

Common Schema Design Mistakes

These mistakes show up repeatedly in production incidents and practitioner discussions:

Putting user_id or request_id in labels. This is the single most common cause of cardinality explosion. These belong in logs or traces.

Inconsistent label names across metrics. Using env on one metric and environment on another makes cross-metric queries painful and error-prone.

Encoding dimensions into metric names. http_request_duration_seconds_get instead of using a method="GET" label. This creates dozens of metrics where one would suffice.

Using wide schemas for dynamic metric sets. If tenants define their own metrics or the set of measurements changes frequently, a wide schema requires constant DDL changes. Use narrow or hybrid.

Ignoring schema evolution. Changing a label’s meaning or type without versioning breaks downstream consumers silently. Use schema registries or at minimum, document changes.

Skipping units in metric names. Is request_duration in seconds or milliseconds? Without the unit in the name, every consumer has to guess.

Too many labels per metric. Each additional label multiplies the series count. Five labels with 10 values each produce 100,000 series. Keep it under five labels for most metrics.

Quick-Reference Checklist

Use this as a pre-flight check before deploying any new metric:

  1. Name follows convention: namespace_subsystem_name_unit in snake_case
  2. Type is explicit: Counter, gauge, histogram, or exponential histogram
  3. Labels are bounded: Every label has a known, finite set of values
  4. No high-cardinality labels: No user IDs, request IDs, or free-form strings
  5. Unit is in the name: Base units only (seconds, bytes, meters)
  6. Schema width matches the workload: Wide for stable, co-emitted metrics; narrow for dynamic sets
  7. Pre-aggregation considered: Does this metric need per-second resolution, or would 1-minute rollups suffice?
  8. Evolution plan exists: New labels are additive; removals go through deprecation
  9. Flush path verified: In serverless, the metric actually reaches the backend before the function exits
  10. Cost estimated: Row count projection aligns with your plan tier

If you’re ready to put these principles into practice, the end-to-end example shows the full path from instrumented app to working dashboard in minutes.

Frequently Asked Questions

What is schema design for metrics ingestion?

It’s the process of defining how metric data is structured before entering a storage system. This includes choosing metric names, label dimensions, types (counter, gauge, histogram), timestamp precision, and whether to use a wide or narrow row format. These decisions determine query performance, storage costs, and pipeline scalability.

What is the difference between wide and narrow metric schemas?

A narrow schema stores one metric value per row (timestamp, metric name, labels, value). A wide schema stores multiple related metrics in the same row (timestamp, labels, metric_a, metric_b). Wide schemas reduce storage by 20-30% and improve multi-metric query times by 40-60%, but they require a stable, known set of metrics. Narrow schemas handle dynamic or sparse metric sets better.

How do I prevent cardinality explosion in my metrics?

Keep labels low-cardinality and bounded. Never use user IDs, request IDs, session tokens, or free-form strings as label values. Remember that total cardinality is the product of all label cardinalities. Cap labels at roughly five per metric, and route high-cardinality data to logs or traces instead.

Does schema design change for serverless environments?

Yes, significantly. Serverless functions are short-lived, so you can’t rely on pull-based scraping or long-running agents. Push-based ingestion is required. Schemas should use fewer labels to keep payloads small and row counts low. Flush semantics become critical because the function may exit before data is sent.

Should I pre-aggregate metrics at ingestion time?

It depends on your query patterns. If your dashboards only need time-range filtering and basic aggregation, pre-aggregating before storage dramatically reduces costs. PostHog compressed nearly 2 billion metrics into 6 MB using this approach. The tradeoff is losing the ability to drill into raw individual data points after the fact.

How do I handle schema evolution for metrics?

Design for additive-only changes. Add new metrics and labels freely, but never remove or rename existing ones without a deprecation period. OpenTelemetry’s schema URL concept provides a versioning mechanism. For streaming pipelines, use a schema registry to validate data at write time and prevent type mismatches.

What naming convention should I use for metrics?

Follow the Prometheus convention: namespace_subsystem_name_unit_suffix in snake_case. Always include the base unit (seconds, bytes) in the name. Never embed label values or label names into the metric name. Treat metric names as permanent from the moment they’re first emitted.

How does schema width affect billing on usage-based platforms?

Directly. A narrow schema that emits 10 separate metrics per event creates 10 rows per event. A wide schema that combines those into one row creates 1 row. On platforms that bill by rows per month, this can represent a 10x cost difference for the same logical data.