Designing Metric Schemas for Serverless Applications (2026)


What Is a Metric Schema?

A metric schema is the structured definition of how each metric data point is described and organized before it leaves your application code. Think of it as the contract between your instrumentation layer and your metrics backend. Every data point you emit has a shape, and that shape needs to be intentional.

In OpenTelemetry’s framework, a well-defined metric rests on four pillars: its instrument type, its name, its unit, and its attributes. This maps cleanly to the components of any metric schema:

  • Metric name: the identifier (http_request_duration_seconds)
  • Metric type: counter, gauge, histogram, or summary
  • Labels/attributes: key-value dimensions that slice the data (method="GET", region="us-east-1")
  • Unit: the measurement unit (seconds, bytes, requests)
  • Namespace/prefix: the ownership scope (myapp_worker_)
  • Metric set: a logical grouping of related metrics emitted together

Why does this matter for serverless? Because bad schema decisions compound fast. A poorly chosen label creates thousands of unique time series. A missing unit makes dashboards unreadable. A metric name you need to change six months later breaks every alert and query that references it.

Serverless environments add three constraints that traditional schemas don’t face: there’s no persistent process to accumulate state, there’s no stable host identity to label by, and push-based ingestion is the only viable option. Every definition in this glossary is written with those constraints in mind.

If you’re new to serverless architecture and observability, start there for the broader context before diving into schema specifics.

Metric Types

The four standard metric types form the backbone of any schema. Choosing the right type for each measurement is one of the first decisions you’ll make, and the hardest to reverse later.

Counter

A counter is a metric that only increases over time or resets to zero on restart. It tracks events that accumulate: requests served, errors occurred, bytes transmitted.

Serverless use case: Invocation counts, error totals, throttle events, bytes sent. Counters are the workhorse of serverless metrics because most of what you care about in a function is “how many times did this thing happen?”

Naming rule: Counters must end with _total. So http_requests_total, not http_requests.

Serverless gotcha: Traditional counters accumulate in memory across thousands of requests. A serverless function might serve one request and die. Your schema needs to account for the fact that each counter value might represent a single increment, flushed and forgotten. The aggregation happens at the backend, not in your code.

Gauge

A gauge is a metric whose value can go up or down. It represents a point-in-time snapshot rather than an accumulated total.

Serverless use case: Concurrent executions, memory usage during invocation, queue depth upstream.

Serverless gotcha: Gauges are inherently harder in serverless. There’s no long-lived process to continuously sample memory or CPU. You get one snapshot per invocation at best. Design your schema knowing that gauge readings from serverless functions will be sparse and event-driven, not continuous.

Histogram

A histogram measures how values distribute across predefined ranges (buckets). It answers questions like “what percentage of requests took longer than 500ms?”

Serverless use case: Request duration, cold start latency distribution, response payload sizes. Histograms are critical for serverless counters and histograms because latency percentiles matter more than averages when cold starts create bimodal distributions.

Bucket selection tip: For typical serverless latency, consider buckets at 5ms, 10ms, 25ms, 50ms, 100ms, 250ms, 500ms, 1s, and 5s. Cold starts on Lambda or Workers can range from 50ms to several seconds, so your buckets need to capture that full range without wasting resolution on irrelevant intervals.

Summary

A summary computes quantiles (p50, p95, p99) client-side, inside your application process.

Serverless use case: Almost none. Summaries require accumulating observations over time and computing percentiles in memory. A function that lives for 50 milliseconds doesn’t have enough data or compute budget to do this meaningfully. Use histograms instead and let your backend compute quantiles.

For a hands-on walkthrough of implementing these types, see instrumenting counters and histograms in JavaScript.

Metric Naming Conventions

Naming is the first schema decision and the last thing you want to change. Renaming a metric after it’s in production means updating dashboards, alerts, queries, and documentation. Treat metric names like API endpoints: once published, they’re a contract.

The Pattern

The standard structure follows a namespace_subsystem_name_unit pattern using snake_case:

myapp_worker_request_duration_seconds
myapp_api_errors_total
myapp_worker_response_bytes_total

The Rules

Use lowercase with underscores. This convention, popularized by Prometheus and adopted broadly across the ecosystem, keeps names readable and consistent. Only [a-zA-Z0-9:_] characters are valid in metric names, and colons are reserved for user-defined recording rules.

Always include the unit, and use base units. Seconds, not milliseconds. Bytes, not kilobytes. This prevents confusion when two teams emit duration metrics with different scales. request_duration_seconds is unambiguous. request_duration is not.

Add type-specific suffixes. Counters get _total. Don’t manually add _sum, _bucket, or _count because those are generated automatically by client libraries for histogram and summary types.

Prefix with a namespace. The prefix indicates ownership. myapp_worker_requests_total is clearly yours. requests_total could belong to anything.

Anti-Patterns

Embedding variable data in names: request_user_12345_duration_seconds creates a new metric for every user. The user identifier belongs in a label, not the name.

Omitting units: request_latency tells you nothing about whether the value is in seconds, milliseconds, or nanoseconds.

Inconsistent casing: Mixing httpRequests with http_requests_total in the same schema guarantees confusion.

Labels and Attributes

Labels (called “attributes” in OpenTelemetry) are key-value pairs attached to a metric that let you slice and filter data. They’re the most powerful part of a metric schema and, in serverless environments, the most dangerous.

Good Labels for Serverless

These have bounded, predictable value sets:

  • function_name: which function emitted the metric
  • region: where the function executed (us-east-1, eu-west-1)
  • environment: production, staging, development
  • http_method: GET, POST, PUT, DELETE, PATCH
  • status_code: 200, 404, 500 (or grouped as 2xx, 4xx, 5xx)
  • route: /api/users, /api/orders (if your route set is finite)

Bad Labels for Serverless

These have unbounded or extremely high-cardinality value sets:

  • invocation_id: unique per request, creates a new time series every single invocation
  • user_id: potentially millions of unique values
  • request_body_hash: effectively infinite
  • container_id: ephemeral and meaningless in serverless, changes constantly

The core principle: every label value set must be bounded. If you can’t enumerate the possible values (or at least cap them at a reasonable number), it doesn’t belong as a label. Log it instead.

OpenTelemetry’s semantic conventions formalize this through three requirement levels: Required, Recommended, and Opt-In. Attributes that may have high cardinality can only be defined at the Opt-In level. This tiered approach is worth adopting even if you’re not using OTel directly.

For deeper guidance on this topic, the guide on label naming and low-cardinality strategies covers specific patterns and enforcement techniques.

Cardinality

Cardinality is the number of unique time series created by the combination of a metric name and its label values. It’s the single most important concept when designing metric schemas for serverless applications, and the one most likely to cause production incidents and cost surprises.

How Cardinality Multiplies

A single metric with three labels creates a time series for every unique combination of those label values:

20 routes × 5 HTTP methods × 3 regions = 300 unique time series

That’s manageable. But add function_version (10 versions in active deployment) and environment (3 environments):

20 × 5 × 3 × 10 × 3 = 9,000 unique time series from one metric

Now multiply by the 15 metrics in your schema. You’re at 135,000 series. Most metrics backends charge by series count or ingested rows, so cardinality directly translates to cost.

Serverless-Specific Cardinality Traps

Serverless platforms amplify cardinality risks in ways that traditional infrastructure doesn’t. Dynamic scaling generates unique identifiers for each container, pod, or function instance. Frequent deployments add new function_version labels. In a serverless setup processing millions of requests, these labels push series counts into ranges that overwhelm backends and budgets.

A GitLab merge request documented a real production incident where metrics labels contained user-supplied data, leading to a cardinality explosion that destabilized their monitoring system. Practitioners on the Cortex GitHub also debate the practical tradeoff, with one developer asking “is it generally better to have more timeseries with less cardinality than less timeseries with more cardinality?” The answer for serverless is almost always: fewer series, tightly controlled labels.

One practitioner described how a serverless app wrote each invocation_id as a log field, and the log index doubled in size. The fix was simple: stop using per-request identifiers as indexed dimensions. Invocation IDs are valuable for debugging individual requests, but they belong in logs, not metric labels.

Managing Cardinality

  • Label allowlists: Only permit known, approved label keys and values in your instrumentation code.
  • Aggregation proxies: Aggregate high-cardinality data before it hits your backend.
  • CI linting: Add automated checks that flag new labels with unbounded value sets before code merges.
  • Regular audits: Review your active series count monthly. Growth should correlate with new features, not new label values.

Understanding the cost implications matters too. Review how metrics plan features relate to row limits and retention to keep spending predictable.

Metric Sets and Namespacing

A metric set is a logical grouping of related metrics that are emitted together from the same service or function group. Think of it as a container for all the metrics that belong to one unit of your application.

Why Group Metrics?

When you define a metric set, you establish a boundary around related measurements. All the HTTP metrics for your API gateway live in one set. All the queue processing metrics for your worker live in another. This grouping aids discovery (developers can browse metric sets to understand what’s instrumented), prevents naming collisions between teams, and maps cleanly to dashboards.

The pattern is one metric set per service or per function group. A Cloudflare Worker handling authentication gets its own set (auth_worker). The payment processing function gets another (payments_worker).

Namespacing in Practice

Namespaces are the prefix portion of a metric name. They signal ownership and scope:

auth_worker_login_attempts_total
auth_worker_token_validation_duration_seconds
payments_worker_charges_total
payments_worker_charge_amount_dollars

Without namespaces, login_attempts_total could belong to any service. With them, the metric is self-documenting.

When your metric set definition lives in code alongside your instrumentation, dashboards can be auto-generated from the schema itself, reducing the manual work of building visualizations from scratch. This code-first approach to metric sets is especially valuable when moving fast on serverless projects.

Ready to define metric sets and see them on a dashboard? The metrics quickstart guide walks through the full code-to-dashboard path.

Flush Semantics

Flush semantics define how and when buffered metric data gets sent from your application to the metrics backend. In traditional applications, this is a background concern. In serverless, it’s a first-class schema design problem.

Why Flush Matters in Serverless

A serverless function’s lifecycle is brutally simple: receive request, process, respond, die. Any metric data sitting in a buffer when the function terminates is lost. An Amazon patent application notes that traditional metrics logging architectures introduce undesirable latency in environments where a function’s lifecycle is measured in seconds.

Platform-Specific Patterns

Cloudflare Workers: Use ctx.waitUntil() to keep the function alive after the response is sent, giving the metrics client time to flush. More detail in Cloudflare Workers waitUntil() patterns.

Vercel/Next.js: Use the after() API to schedule a post-response callback for flushing. See Vercel after() for metrics flush.

AWS Lambda: Extensions or synchronous flush before the response. No equivalent of waitUntil exists natively.

Schema Implications

Design your metrics to be safely batchable and idempotent. If a flush fails and retries, duplicate data points shouldn’t corrupt your aggregations. Counters handle this naturally (re-sending an increment is usually fine), but gauges can be trickier because a duplicate snapshot might overwrite a more recent value.

The deeper guide on buffering and flushing in serverless edge code covers batching strategies, payload size limits, and retry behavior.

Push vs. Pull Ingestion

The ingestion model, push or pull, has direct consequences for how you design metric schemas for serverless applications.

Pull Model (Prometheus-Style)

Prometheus scrapes a /metrics HTTP endpoint on your service at regular intervals. This works well for long-running servers but fundamentally breaks in serverless. A discussion in the Prometheus developers Google Group highlights the problem: deploying a service with an external TCP API that needs protection from public access isn’t practical when functions only exist for milliseconds.

Even if you could expose an endpoint, the function would be dead before the next scrape interval. Pull-based schemas assume persistent processes. Serverless doesn’t have them.

Push Model

Push-based ingestion (HTTP POST to a metrics API) is the serverless default. Your function collects metrics during execution, then pushes them to a backend before or after responding.

Push-friendly schemas favor self-describing payloads. Each batch should include the metric name, type, labels, value, and timestamp so the backend doesn’t need to maintain state about what it expects. This is why designing metric schemas for serverless applications means thinking about payload structure, not just metric definitions.

For a broader look at how push-based telemetry fits into the MELT framework and OpenTelemetry, that guide covers the full picture.

OpenTelemetry Semantic Conventions for FaaS

OpenTelemetry’s Semantic Conventions define a common set of attribute names, types, meanings, and valid values that give data consistent meaning across producers and consumers. For serverless, the FaaS semantic conventions provide a ready-made vocabulary.

What the Conventions Cover

The FaaS conventions specify standard metric names and attributes for function invocations, durations, cold starts, errors, and timeouts. They also define standard attribute keys like faas.name, faas.version, faas.trigger, and cloud.region.

Why This Matters for Schema Design

Adopting OTel conventions means your schema is compatible with any OTel-aware backend, dashboard, or analysis tool. It also means you don’t have to invent naming from scratch. When OpenTelemetry specifies that cold start initialization time should be measured in seconds, that’s a schema decision already made for you.

The tiered requirement levels (Required, Recommended, Opt-In) are particularly useful for serverless. High-cardinality attributes are explicitly classified as Opt-In, building cardinality awareness directly into the convention itself.

Essential Serverless Metrics to Design For

A complete metric schema for serverless applications should cover four categories, not just performance.

Performance metrics: Execution duration, cold start latency, end-to-end latency, throughput (requests per second). Cold start latency deserves its own dedicated metric, not just a label on a general duration histogram, because it’s the single most visible performance differentiator for serverless applications.

Reliability metrics: Error rates by type, timeout frequency, throttling occurrences, success rate. These tell you whether your function is healthy, not just fast.

Resource utilization: Memory usage per invocation, CPU time consumed, network bytes transferred, concurrent executions. In serverless, you’re billed for resources consumed, so utilization metrics are cost metrics in disguise.

Cost metrics: Invocation count, billed duration, memory-seconds. These map directly to your cloud provider’s billing dimensions and to your metrics backend’s ingestion costs.

Baselime’s research found that 58% of serverless engineers say observability is their biggest challenge. A schema that covers all four categories gives you the data to actually understand what’s happening, not just guess.

Schema Evolution and Versioning

Metric schemas change. New features need new labels. Old metrics get renamed. Fields get deprecated. How you handle these changes determines whether your dashboards and alerts survive.

Treat Names Like API Contracts

Renaming a metric is a breaking change. Every dashboard panel, alert rule, and query that references http_request_duration_seconds will break if you rename it to request_latency_seconds. Version your changes. Run old and new metrics in parallel during transitions. Deprecate, don’t delete.

OpenTelemetry’s schema_url

OTel provides a schema_url concept that attaches a version identifier to emitted telemetry. When your schema changes, consumers can check the version and apply transformations. This is especially relevant in serverless environments where multiple function versions may be running simultaneously during deployments, each emitting slightly different schemas.

Practical Advice

  • Add new labels as Opt-In first (following OTel’s tiered model)
  • Never remove a label that existing alerts depend on without a migration period
  • Document schema changes in the same repository as your instrumentation code
  • Use CI checks to detect unintentional schema changes (new label keys, renamed metrics)

Anti-Pattern Gallery

These mistakes show up repeatedly in serverless metric schemas. Each one includes the fix.

Anti-pattern 1: User ID in the metric name

# Bad
request_user_12345_duration_seconds 0.045

Fix: Use a bounded label instead.

# Good
request_duration_seconds{user_tier="premium"} 0.045

Anti-pattern 2: Invocation ID as a label

# Bad
function_duration_seconds{invocation_id="abc-123-def"} 0.032

This creates a new time series for every single request. Log the invocation ID. Don’t label it.

Anti-pattern 3: Unbounded route labels

# Bad
http_requests_total{route="/users/12345/profile"} 1

If routes contain dynamic segments, your label set is unbounded. Normalize routes to their pattern: route="/users/:id/profile".

Anti-pattern 4: Missing namespace

# Bad
requests_total 42

Six months later, three services all emit requests_total and nobody knows which is which.

# Good
auth_worker_requests_total 42

Anti-pattern 5: Milliseconds as the unit

# Bad
request_duration_milliseconds 45

The convention is base units. Use seconds. Every tool in the ecosystem expects it.

Metric Schema Checklist for Serverless

Before shipping instrumentation, verify each item:

  • All metric names use snake_case with lowercase characters only
  • All counters end in _total
  • Every metric name includes the unit (in base units: seconds, bytes)
  • Every metric name has a namespace prefix indicating ownership
  • No labels contain unbounded value sets (no user IDs, request IDs, or container IDs)
  • Cold start latency is tracked as a dedicated histogram
  • The flush path is confirmed for your runtime (waitUntil for Workers, after for Vercel)
  • Cardinality has been calculated: routes × methods × regions × versions per metric
  • Schema changes are tracked in version control alongside code
  • At least one metric exists in each of the four categories (performance, reliability, resource, cost)

Quick Reference Table

Term Definition Serverless Relevance
Counter Metric that only increases or resets to zero Invocation counts, error totals, bytes sent
Gauge Point-in-time value that can go up or down Memory usage, concurrent executions (sparse readings)
Histogram Distribution of values across predefined buckets Cold start latency, request duration percentiles
Summary Client-side quantile computation Rarely used; too expensive for short-lived handlers
Label/Attribute Key-value dimension attached to a metric Must be bounded; no request IDs or user IDs
Cardinality Count of unique time series from label combinations Primary cost and performance risk in serverless
Metric Set Logical grouping of related metrics One per service or function group; aids discovery
Namespace Prefix indicating metric ownership Prevents collision across teams and services
Flush Process of sending buffered metrics to backend Critical path; data lost if function dies before flush
Push Ingestion HTTP POST of metrics to a collection endpoint Only viable model for ephemeral serverless functions
Schema Evolution Managing metric definition changes over time Treat like API versioning; deprecate, don’t delete

See these concepts in action with the end-to-end example from app to dashboard.

Frequently Asked Questions

What makes designing metric schemas for serverless applications different from traditional monitoring?

Three things. First, there’s no persistent process to accumulate metric state, so counters reset every invocation and aggregation moves to the backend. Second, there’s no stable host identity, so labels like hostname or instance_id are meaningless. Third, pull-based collection doesn’t work because functions are dead before the next scrape. Your schema must be push-native, self-describing, and designed for sparse, event-driven data.

How do I decide whether something should be a label or part of the metric name?

If the dimension has a small, bounded set of values (like HTTP methods or regions), make it a label. If it represents a fundamentally different measurement (like CPU time vs. memory usage), make it a separate metric. If the value set is unbounded or very large (like user IDs), don’t put it in either. Log it instead.

What is a safe cardinality limit for serverless metrics?

There’s no universal number, but a practical rule: calculate the cross-product of all your label value sets for each metric. If any single metric produces more than 10,000 series, investigate whether you can reduce label granularity. Most hosted metrics backends start charging noticeably above 100,000 total active series.

Should cold start latency be a separate metric or a label on duration?

A separate metric. Cold starts represent a fundamentally different code path (initialization plus execution vs. execution only). Mixing them into a single duration histogram with a cold_start=true label muddies the distribution. A dedicated function_cold_start_duration_seconds histogram gives you clean percentiles for the specific thing users care about most.

Why shouldn’t I use Prometheus pull-based collection with serverless functions?

Prometheus expects to scrape a persistent HTTP endpoint at regular intervals. Serverless functions exist only during invocation and have no stable address. Even if you deployed a sidecar endpoint, the function would be gone before the scraper arrives. Push-based ingestion, where the function sends metrics via HTTP POST before terminating, is the only model that works.

How do I handle metric schema changes without breaking existing dashboards?

Treat metric names as API contracts. Run old and new metrics in parallel during a transition period. Use OTel’s schema_url to version your definitions. Never remove or rename a metric that’s referenced in alerts or dashboards without a documented migration path and a deprecation window.

What’s the minimum set of metrics every serverless function should emit?

At minimum: invocation count (counter), error count (counter), execution duration (histogram), and cold start duration (histogram). These four cover the essential performance and reliability signals. Add memory usage (gauge) and a cost-relevant metric like billed duration if your platform exposes it.

How do metric sets relate to dashboards?

A metric set defines a logical grouping of metrics in your code. When your metrics backend understands this grouping, it can auto-generate a dashboard that visualizes all metrics in the set together. This is especially valuable in serverless where you want visibility fast without manually building panels for each function.