Skip to main content
A Counter is a synchronous instrument that records values that only increase over time. Counters are ideal for tracking totals like request counts, bytes sent, or errors encountered.

When to Use Counter

Use a Counter when:
  • Values only increase (never decrease)
  • You’re counting discrete events
  • You want to track cumulative totals
  • Resets should only happen on application restart
Common examples:
  • HTTP requests served
  • Bytes transmitted
  • Errors encountered
  • Items processed
  • Cache hits
Do not use Counter for values that can decrease. Use UpDownCounter instead.

API Reference

The add method records an increment to the counter. The value must be non-negative.

Creating a Counter

Counters support u64 and f64 data types:

Recording Measurements

Use the add method to record increments:

Complete Example

Here’s a complete example tracking HTTP requests:

Attributes and Cardinality

Attributes add dimensions to your counter, allowing you to slice the data in different ways:
Each unique combination of attributes creates a separate time series.
Cardinality matters! Each unique attribute combination creates a new time series. Avoid high-cardinality attributes like user IDs or request IDs, as they can cause memory issues and poor query performance.

Good Attributes (Low Cardinality)

  • HTTP method (GET, POST, PUT, DELETE)
  • HTTP status code (200, 404, 500)
  • Endpoint patterns (/api/users, /api/posts)
  • Environment (production, staging)
  • Region (us-east-1, eu-west-1)

Bad Attributes (High Cardinality)

  • User IDs
  • Request IDs
  • Timestamps
  • Email addresses
  • Full URLs with query parameters

Cloning Counters

Counters implement Clone, allowing you to share them across your application:
Clone counters rather than creating duplicates with the same name. Creating multiple counters with the same name can lower SDK performance.

Counter vs. ObservableCounter

Choose based on how you track the data:
See Observable Instruments for more details on asynchronous counters.

UpDownCounter Alternative

If your values can both increase and decrease, use UpDownCounter instead:

Best Practices

  1. Use descriptive names: http_requests_total is better than requests
  2. Include units: Specify units like "requests", "By" (bytes), or "ms"
  3. Keep cardinality low: Limit unique attribute combinations
  4. Reuse instruments: Clone counters instead of creating duplicates
  5. Choose the right type: Use u64 for counts, f64 for fractional values

Next Steps

Histogram

Record value distributions like request latency

Gauge

Record independent point-in-time values

Observable Instruments

Use callbacks to report measurements

Views

Customize how counters are aggregated