Types of Metrics (Counters, Gauges, Histograms)
Introduction
In observability, metrics are crucial for monitoring the performance and health of systems. Metrics can be broadly categorized into three types: Counters, Gauges, and Histograms.
Counters
A Counter is a cumulative metric that only increases over time. It is ideal for tracking events such as the number of requests received, errors, or completed tasks.
Key Characteristics of Counters
- Monotonically increasing: Counters never decrease.
- Resettable: They can be reset to zero, but it's uncommon.
- Used for aggregating counts over time.
Example usage in Prometheus:
http_requests_total{method="POST", handler="comments"} 1027
Gauges
A Gauge is a metric that represents a single numerical value that can arbitrarily go up and down. Gauges are suitable for tracking values such as temperature, memory usage, or current active sessions.
Key Characteristics of Gauges
- Can increase or decrease: Gauges can reflect both upward and downward trends.
- Useful for measuring instantaneous values.
Example usage in Prometheus:
memory_usage_bytes{instance="localhost:9090"} 524288000
Histograms
A Histogram samples observations and counts them in configurable buckets. It is useful to visualize the distribution of data points, such as request durations or response sizes.
Key Characteristics of Histograms
- Tracks the count and sum of observations: Histograms can calculate averages and percentiles.
- Configurable buckets: You can define the ranges for the histogram.
Example usage in Prometheus:
http_request_duration_seconds{method="GET", handler="homepage"} 0.0045
Best Practices
- Choose the right metric type based on what you are measuring.
- Use consistent naming conventions for metrics.
- Monitor cardinality to avoid performance issues.
- Aggregate metrics over time for better insights.
FAQ
What is the difference between a Counter and a Gauge?
A Counter only increases over time, while a Gauge can increase or decrease, reflecting the current state.
When should I use a Histogram over a Gauge?
Use a Histogram when you need to observe the distribution of a data set, such as response times, instead of a single value.
Can Counters be reset?
While Counters can technically be reset to zero, this is typically not done in practice, as it would lose the historical data.