How to Design Metric Names and Labels for JavaScript Apps



You open a monitoring dashboard and find req_count, requestsTotal, http_requests, and api_request_counter all measuring the same thing. Each was added by a different developer at a different time. Nobody knows which is correct, and all four are generating time series that cost money.

This is what happens when metric naming is treated as an afterthought. The names you choose and the labels you attach become permanent fixtures of your observability stack within days. Renaming metrics after they’re emitted to production is painful enough that most teams never do it, or suffer the consequences when they try.

This guide covers how to design metric names and labels for JavaScript apps, whether you’re running Node.js servers, Cloudflare Workers, Vercel edge functions, or any other JavaScript runtime. It defines every core term, shows the code, and gives you decision frameworks you can apply immediately.

Want to see these patterns in action? Follow the metrics quickstart guide to go from code to a live dashboard in minutes.


Glossary of Core Terms

Before getting into rules and patterns, these are the terms you need to understand. Each one maps to a concrete concept in your JavaScript instrumentation code.

Metric Name

The unique identifier for what you’re measuring. It answers the question “what is this number?”

A metric name like myapp_http_request_duration_seconds tells you the application (myapp), the domain (http_request), what’s being measured (duration), and the unit (seconds). A name like dur tells you nothing.

Why it matters: The metric name is permanent. Once your app starts emitting a metric, even in staging, that name is effectively locked in. The PUMAC framework puts it bluntly: “you will not rename it, or you will suffer the consequences.”

Label / Attribute / Dimension / Tag

These four words all mean the same thing: a key-value pair that adds context to a metric. Prometheus calls them “labels.” OpenTelemetry calls them “attributes.” Datadog calls them “tags.” CloudWatch and some analytics systems call them “dimensions.”

// In prom-client, labels are declared upfront
const requestCounter = new Counter({
  name: 'myapp_http_requests_total',
  help: 'Total HTTP requests',
  labelNames: ['method', 'route', 'status_code']
});

// Then set per-observation
requestCounter.labels('GET', '/api/users', '200').inc();

Why it matters: Labels are how you slice and filter your data after collection. The label design decision, what goes in the name versus what goes in a label, is the single most consequential choice you’ll make.

For a deeper treatment, see label naming conventions and low-cardinality strategies.

Counter

A monotonically increasing value. It only goes up (or resets to zero on restart). Total requests served, total errors encountered, total bytes sent.

In Prometheus convention, counter names must end with _total. So myapp_http_requests_total, not myapp_http_requests. OpenTelemetry adds the _total suffix automatically when exporting to Prometheus format, so OTel instruments don’t include it in their names.

Gauge

A value that goes up and down. Active connections, queue depth, memory usage, temperature.

Gauges don’t get a _total suffix. A gauge named myapp_active_connections makes sense. A gauge named myapp_active_connections_total does not.

Histogram

A distribution of values across predefined buckets. Request durations, response sizes, queue wait times.

// OpenTelemetry JS SDK
const histogram = meter.createHistogram('http.client.request.duration', {
  description: 'Duration of outbound HTTP requests',
  unit: 's',
  advice: {
    explicitBucketBoundaries: [0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10]
  }
});

Bucket boundaries matter. Too few and you lose resolution. Too many and you inflate the time series count, because each bucket creates its own series. For hands-on implementation details, see how to instrument counters and histograms in JavaScript.

Cardinality

The total number of unique time series produced by a metric. It equals the product of all unique values across all labels.

A request counter with 3 environments, 5 services, and 10 status codes produces 3 × 5 × 10 = 150 time series. Add a user_id label with 1 million users, and that same metric balloons to 150 million series.

Why it matters: This is the number that controls your monitoring bill. Observability platforms like Datadog charge per custom metric, and Splunk bills based on ingest volume. Uncontrolled cardinality directly inflates both.

Metric Set / Namespace

A logical grouping of related metrics under a shared prefix or scope. In Prometheus, this is the prefix portion of the name (myapp_). In OpenTelemetry, it’s typically the first segment of the dotted name (http.server.*). In API-first metrics services, you might define a named metric set that groups related counters and histograms together.

Base Unit

Always use base units: seconds (not milliseconds), bytes (not kilobytes), meters (not kilometers). This is a convention shared by both Prometheus and OpenTelemetry.

The reason is consistency. If some metrics use milliseconds and others use seconds, every dashboard panel and alert rule needs to know which is which. Standardizing on base units eliminates that guesswork.

Metric Type Suffix

The suffixes _seconds, _bytes, and _total signal what a metric measures and how to interpret it. Without these indicators, engineers spend time guessing whether they’re looking at a counter, a gauge, or a histogram.

Prometheus convention puts the unit in the name: myapp_request_duration_seconds. OpenTelemetry convention puts the unit in instrument metadata instead and keeps the name clean: http.server.request.duration with unit: "s".

Flush / Buffer

How metrics are batched and sent from your application to the collection backend. This is especially critical in serverless and edge environments where the handler might terminate before metrics are transmitted.

In Cloudflare Workers, you use ctx.waitUntil() to keep the runtime alive during flush. In Vercel, you use after(). Getting this wrong means losing data silently. For configuration details, see configuring buffering and flush behavior.

Recording Rule

A pre-aggregated metric computed from raw metrics, typically by a Prometheus server. Recording rules reduce cardinality at query time by collapsing high-dimensional data into summarized series. In serverless contexts where you don’t run Prometheus, the equivalent is designing your metric schemas to be pre-aggregated before emission.


Naming Convention Rules: Prometheus vs. OpenTelemetry

The two dominant standards for metric naming disagree on fundamental patterns. This causes real confusion, especially when JavaScript developers read Prometheus documentation but instrument with OpenTelemetry, or vice versa.

Aspect Prometheus OpenTelemetry
Case style snake_case dot.notation for namespacing, snake_case within segments
Counter suffix _total required Added automatically on Prometheus export
Unit in name Yes (_seconds, _bytes) No, unit goes in instrument metadata
Service name in name Yes, as prefix (myapp_) No, service identity belongs in resource attributes
Allowed characters [a-zA-Z_:][a-zA-Z0-9_:]* Dots, dashes, and other characters allowed
Namespace delimiter Underscore (_) Dot (.)

The Translation Problem

When OpenTelemetry metrics are exported to Prometheus, dots become underscores, units get appended as suffixes, and _total is added to counters. So an OTel instrument named http.server.request.duration with unit: "s" becomes http_server_request_duration_seconds in Prometheus.

According to an OpenTelemetry compatibility survey, 60% of OTel users who query with PromQL preferred keeping the original dotted names, while 40% wanted Prometheus-style underscore names. Practitioners on forums report that this split creates confusion when teams share dashboards across tools.

Which Should JavaScript Developers Choose?

If you’re running a Prometheus server and querying with PromQL, use Prometheus conventions directly. Your names will match what appears in queries and dashboards with no translation layer.

If you’re using OpenTelemetry SDKs, or if you’re sending metrics to an API-first service without a Prometheus backend, OTel-style naming is cleaner. It separates concerns better: the name identifies what you’re measuring, the unit metadata says the unit, and resource attributes say who’s measuring it.

If you’re working with Cloudflare Workers Analytics Engine, neither convention applies directly. Analytics Engine uses blobs (strings for grouping and filtering) and doubles (numeric values). There are no rigid naming constraints, but applying consistent naming patterns still matters for queryability.

For teams migrating between systems, see migrating metrics from Prometheus for practical translation guidance.


The Name vs. Label Decision Framework

This is where most naming mistakes happen. The question is simple: should this piece of information be part of the metric name, or should it be a label?

The Decision Flow

Step 1: Is the value static and known at compile time?

If yes, put it in the metric name. Examples: http_server_requests_total vs. http_client_requests_total. The distinction between server and client is architectural, not something that changes per request.

Step 2: Is the value dynamic but bounded?

If the value changes per observation but has a finite, predictable set of possibilities, use a label. HTTP methods (~10 values), status code classes (~5 values), route patterns (bounded by your route definitions) all qualify.

Step 3: Is the value unbounded?

If the number of possible values can grow without limit, do not use it as a label. User IDs, request IDs, email addresses, full URLs with query parameters, these create cardinality explosions.

Good Labels vs. Bad Labels

Label Cardinality Verdict Alternative
method (GET, POST, etc.) ~10 Good —
status_code (200, 404, 500) ~50 Good Use status_class (2xx, 4xx, 5xx) for even lower cardinality
route (/api/users, /api/orders) Bounded by app routes Good, if normalized —
user_id Millions Bad user_tier or user_type
request_id Unbounded Bad Remove entirely
email PII + unbounded Bad email_domain if needed
url with query params Unbounded Bad Normalize to route pattern
ip_address High cardinality + PII Bad region or ip_range

Route Path Normalization

One of the most common mistakes in JavaScript apps is using raw request URLs as label values. A route like /api/users/12345 should become /api/users/:id before it’s used as a label. Otherwise, every unique user ID creates a new time series.

// Bad: raw path creates unbounded cardinality
requestCounter.labels('GET', req.url, '200').inc();

// Good: normalize to route pattern
requestCounter.labels('GET', '/api/users/:id', '200').inc();

Most JavaScript web frameworks (Express, Hono, Fastify) give you access to the matched route pattern. Use that instead of the raw URL.

For a complete treatment of label design for serverless applications, see designing metric schemas for serverless applications.


Cardinality: The Number That Controls Your Bill

Understanding cardinality is non-negotiable when designing metric names and labels for JavaScript apps. Every unique combination of label key-value pairs creates a new time series, and each time series costs storage, memory, and often money.

How to Calculate Cardinality Before You Ship

Before adding a label, multiply out the possibilities:

Total series = (unique values of label_1) 
             × (unique values of label_2) 
             × (unique values of label_3)
             × ...

A request duration histogram with method (8 values), route (20 routes), status_code (15 codes), and 10 histogram buckets produces 8 × 20 × 15 × 10 = 24,000 time series. That’s manageable. Add an unbounded user_id label and the number becomes meaningless because it never stops growing.

The Prometheus core team at Robust Perception recommends keeping per-metric cardinality below 10 unique values per label as a general rule of thumb.

Serverless Amplifies the Risk

In traditional server deployments, the number of metric-emitting instances is relatively stable. In serverless and edge environments, dynamic scaling generates unique identifiers for each container, function invocation, or deployment version.

Practitioners on Reddit report that frequent deployments in serverless setups can add new function_version labels with every release cycle, pushing series counts into the millions without anyone noticing until the bill arrives. A Cloudflare Workers function processing high traffic volumes with per-invocation labels can generate staggering cardinality in minutes.

One notable exception: Cloudflare’s Workers Analytics Engine stores every data point independently, so each point can have unique blob values without the cardinality penalty that Prometheus-style systems impose. If you’re working in that ecosystem, the constraints are different. See collecting metrics from Cloudflare Workers for specifics.

Cost Math

Many hosted metrics platforms bill by row volume or active series count. If a poorly designed label increases your cardinality by 100x, your bill increases proportionally. For API-first metrics services, every row counts against your plan’s monthly allotment.

To understand how metric volume maps to plan tiers, compare plan features and find the right row volume for your usage.


JavaScript Code Patterns

Here’s how these naming principles translate into actual JavaScript code across different runtimes and libraries.

Node.js with prom-client

const { Counter, Histogram, register } = require('prom-client');

// Counter: snake_case, app prefix, _total suffix, base unit implied
const httpRequestsTotal = new Counter({
  name: 'myapp_http_requests_total',
  help: 'Total number of HTTP requests received',
  labelNames: ['method', 'route', 'status_code']
});

// Histogram: includes unit (_seconds), bounded labels
const httpRequestDuration = new Histogram({
  name: 'myapp_http_request_duration_seconds',
  help: 'HTTP request duration in seconds',
  labelNames: ['method', 'route'],
  buckets: [0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10]
});

// Usage in an Express middleware
app.use((req, res, next) => {
  const end = httpRequestDuration.startTimer();
  res.on('finish', () => {
    const route = req.route?.path || 'unknown';
    httpRequestsTotal.labels(req.method, route, String(res.statusCode)).inc();
    end({ method: req.method, route });
  });
  next();
});

Notice: labelNames are declared at definition time, not at observation time. This prevents typos and enforces consistency.

OpenTelemetry JS SDK

const { MeterProvider } = require('@opentelemetry/sdk-metrics');
const { OTLPMetricExporter } = require('@opentelemetry/exporter-metrics-otlp-http');

const meterProvider = new MeterProvider({
  readers: [/* configured reader */]
});

const meter = meterProvider.getMeter('myapp');

// OTel style: dotted name, unit in metadata, no _total suffix
const requestCounter = meter.createCounter('http.server.requests', {
  description: 'Total HTTP requests received',
  unit: '1'  // dimensionless count
});

const requestDuration = meter.createHistogram('http.server.request.duration', {
  description: 'HTTP request duration',
  unit: 's',
  advice: {
    explicitBucketBoundaries: [0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10]
  }
});

// Usage: attributes (OTel's term for labels) are passed per observation
requestCounter.add(1, {
  'http.request.method': 'GET',
  'http.route': '/api/users/:id',
  'http.response.status_code': 200
});

Key differences from prom-client: the unit is metadata rather than part of the name, attribute names use OTel semantic conventions with dots, and the service identity comes from the resource layer, not the metric name.

API-First Metrics (Serverless)

For serverless environments where you can’t run a Prometheus exporter or OTel collector, API-first metrics services let you send data directly over HTTP. You define a metric set, record counters and histograms in your handler code, and flush before the function terminates.

// Pseudocode for API-first serverless metrics
export default {
  async fetch(request, env, ctx) {
    const start = Date.now();
    
    // ... handle request ...
    
    const duration = (Date.now() - start) / 1000; // convert to seconds
    
    // Record metrics with bounded labels
    metrics.counter('http_requests_total', 1, {
      method: request.method,
      route: '/api/users/:id',
      status: '200'
    });
    
    metrics.histogram('http_request_duration_seconds', duration, {
      method: request.method,
      route: '/api/users/:id'
    });
    
    // Flush before handler terminates
    ctx.waitUntil(metrics.flush());
    
    return response;
  }
};

The naming rules are identical regardless of the transport mechanism. Lowercase, prefixed, with units, and bounded labels. For a full walkthrough of this pattern, see the end-to-end example from app to dashboard.

Cloudflare Workers Analytics Engine

Analytics Engine uses a different model. Instead of named labels, you write blobs (strings) and doubles (numbers) to indexed data points.

export default {
  async fetch(request, env, ctx) {
    const start = Date.now();
    
    // ... handle request ...
    
    env.METRICS.writeDataPoint({
      blobs: [
        request.method,           // blob1: HTTP method
        '/api/users/:id',         // blob2: normalized route
        '200'                     // blob3: status code
      ],
      doubles: [
        1,                        // double1: request count
        (Date.now() - start)      // double2: duration in ms
      ],
      indexes: [request.cf?.colo] // sampling key
    });
    
    return response;
  }
};

Because Analytics Engine stores each data point independently, you don’t face the same cardinality constraints as Prometheus-style systems. Still, consistent naming of what each blob position represents is essential for query clarity. Document your schema somewhere your team can find it.


Common Mistakes Checklist

These are the naming and labeling mistakes that practitioners hit most often. Fixing them after the fact is expensive, so catch them before you ship.

1. Encoding dynamic values in metric names

If you find yourself procedurally generating metric names like myapp_user_123_requests, you should be using a label instead. Metric names are for static categories. Dynamic values belong in labels.

2. Missing unit suffixes

Without _seconds, _bytes, or _total, engineers have to guess what a metric measures. Is request_duration in seconds? Milliseconds? Microseconds? The suffix eliminates ambiguity.

3. Using camelCase instead of snake_case

httpRequestDuration looks natural in JavaScript, but metric names follow their own conventions. Use http_request_duration_seconds for Prometheus-style or http.request.duration for OTel-style. Your code’s variable names can be camelCase; the metric’s name should not be.

4. High-cardinality labels

This bears repeating because it’s the most expensive mistake. Never use user_id, request_id, session_id, full URLs, email addresses, or IP addresses as label values. Use bounded alternatives like user_tier, region, or normalized route patterns.

5. Mixing naming conventions across the team

When one developer uses req_total and another uses request_count, searching for HTTP-related metrics becomes a guessing game. Establish a naming convention document and enforce it in code review. The convention matters less than consistency.

6. Not normalizing route paths

Express gives you req.route.path, which returns /api/users/:id. Using req.originalUrl instead gives you /api/users/12345?include=profile, which is a cardinality bomb. Always normalize.

7. Putting the metric type in the name

A name like myapp_request_gauge or myapp_errors_counter is redundant. The type is already communicated by the suffix convention (_total for counters) and the metric definition. Adding the type to the name creates confusion when conventions overlap.

8. Ignoring flush semantics in serverless

In serverless handlers, if you don’t explicitly flush metrics before the function terminates, your data is silently lost. This isn’t a naming issue per se, but it’s so commonly overlooked alongside naming work that it belongs here. See common pitfalls when instrumenting serverless handlers for the full list.

For broader instrumentation guidance, check the metrics instrumentation best practices guide.


Putting It All Together

Designing metric names and labels for JavaScript apps comes down to a handful of principles applied consistently:

  1. Names are permanent. Think twice before emitting any metric, even in staging.
  2. Use lowercase with consistent separators. Pick snake_case or dot.notation and stick with it across your team.
  3. Prefix with your app or domain name. Avoid collisions in shared namespaces.
  4. Include the unit. Base units only: seconds, bytes, not milliseconds or kilobytes.
  5. Labels are for bounded dynamic values. Method, route pattern, status code class. Not user IDs, not request IDs, not raw URLs.
  6. Calculate cardinality before you ship. Multiply out the label combinations. Keep each label under 10 unique values as a starting point.
  7. Normalize everything. Route paths, status codes (consider using classes like 2xx/4xx/5xx), and any other label value that could accidentally become unbounded.

These rules apply regardless of whether you’re using prom-client, the OpenTelemetry JS SDK, Cloudflare Workers Analytics Engine, or an API-first metrics service. The transport changes; the naming discipline doesn’t.

Ready to apply these patterns? See the end-to-end example to go from properly named metrics in your code to a working dashboard in minutes.


FAQ

What’s the difference between a label and an attribute?

Nothing, conceptually. Prometheus calls them “labels,” OpenTelemetry calls them “attributes,” Datadog calls them “tags,” and some analytics systems call them “dimensions.” They all mean the same thing: key-value pairs that add context to a metric observation.

Should I use Prometheus naming conventions or OpenTelemetry conventions?

If you’re running a Prometheus server and querying with PromQL, use Prometheus conventions (snake_case, _total suffix, unit in name). If you’re using OTel SDKs or an API-first metrics service without a Prometheus backend, OTel conventions (dot notation, unit in metadata) are cleaner. The critical thing is to pick one and enforce it across your team.

How many label values are too many?

The Prometheus core team recommends keeping cardinality below 10 unique values per label on any single metric endpoint. In practice, labels with up to 50 unique values (like HTTP status codes) are manageable for most setups. Anything that could grow without a known upper bound, like user IDs or session IDs, should never be a label.

Can I rename a metric after it’s in production?

Technically yes, but practically it’s very costly. Every dashboard, alert rule, and SLO that references the old name needs updating. During the transition, you’ll either lose historical continuity or run both old and new names simultaneously (doubling your cardinality). Treat metric names as permanent from the moment they’re emitted, even in QA environments.

Do these naming rules apply to Cloudflare Workers Analytics Engine?

Analytics Engine doesn’t enforce the same naming constraints because it stores each data point independently rather than creating time series per label combination. You won’t hit cardinality explosions the way Prometheus-style systems do. That said, consistent naming of what each blob position represents is still essential for writing clear queries and maintaining readable dashboards.

How do I handle metric flush in serverless JavaScript functions?

In Cloudflare Workers, use ctx.waitUntil(metrics.flush()) to keep the runtime alive during transmission. In Vercel, use the after() API. Without explicit flush handling, metrics from short-lived handlers are silently dropped. This is one of the most common instrumentation mistakes in serverless environments.

Should I put the service name in the metric name?

Prometheus convention says yes, as a prefix: myapp_http_requests_total. OpenTelemetry convention says no: the service identity belongs in resource attributes, not the metric name. This lets you reuse the same metric definition across services and filter by service at query time. Both approaches work; just be consistent.

What happens if different team members use different naming conventions?

You end up with a monitoring dashboard full of req_count, requestsTotal, http_requests, and api_request_counter, all measuring the same thing. Nobody knows which is authoritative, nobody trusts the data, and cleanup becomes a multi-sprint project. Write down your naming convention, put it in your repo’s contributing guide, and enforce it in code review.