In this lesson, you will learn how to distinguish between Counter and Histogram metrics to effectively track system performance and application behavior.
The Counter: Tracking Cumulative Events
A Counter is a monotonic metric; its value can only increase (or reset to zero upon process restart). You use counters for events that represent a total count of occurrences. Because they only ever go up, they are perfect for calculating rates of change, such as "requests per second" or "total errors logged."
Think of a Counter as a simple tally mark on a wall. Every time an event happens, you add one.
// Incrementing a counter for total request volume
httpRequestsCounter.inc();
The Histogram: Tracking Distributions
A Histogram is significantly more complex. Rather than a single sum, a Histogram samples observations—typically request durations—and places them into configurable "buckets." This allows you to calculate quantiles (like the P99 latency) to understand the distribution of your data.
If a Counter tells you how many requests occurred, a Histogram tells you how those requests performed across the board. You can see not just the average latency, but how many requests fall within specific time windows (e.g., 0–100ms, 100–300ms, >500ms).
// Measuring the duration of an operation
const end = httpRequestDurationHistogram.startTimer();
// ... logic execution ...
end(); // Automatically buckets the duration
Why the Distinction Matters
If you use a Counter to track latency by averaging durations, you lose the ability to detect "long-tail" latency (the unlucky users waiting seconds for a response). By using a Histogram, you maintain a granular view of your service’s tail-end performance. Conversely, using a Histogram to count simple events (like counting total users) introduces unnecessary memory overhead, as the library must maintain bucket state rather than a single integer.
When choosing between them, ask yourself: "Am I tracking the frequency of an occurrence, or the distribution of a value?" If it's frequency, pick a Counter. If it's a duration or size, use a Histogram.
Key Takeaway: Use Counters for cumulative totals of events, and Histograms for tracking the distribution and quantiles of latency or request sizes.