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
- HTTP requests served
- Bytes transmitted
- Errors encountered
- Items processed
- Cache hits
API Reference
add method records an increment to the counter. The value must be non-negative.
Creating a Counter
Counters supportu64 and f64 data types:
Recording Measurements
Use theadd 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: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 implementClone, allowing you to share them across your application:
Counter vs. ObservableCounter
Choose based on how you track the data:UpDownCounter Alternative
If your values can both increase and decrease, useUpDownCounter instead:
Best Practices
- Use descriptive names:
http_requests_totalis better thanrequests - Include units: Specify units like
"requests","By"(bytes), or"ms" - Keep cardinality low: Limit unique attribute combinations
- Reuse instruments: Clone counters instead of creating duplicates
- Choose the right type: Use
u64for counts,f64for 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