Custom Metrics - Counters, Gauges and Histograms with a Mini PHP App
1. Recap: From One Metric to a Complete Set
In the previous article, the mini Python application exposed a single metric — a request count. In practice, a real application wants to answer more specific business questions: how many orders were created? How long did each request take? How many connections are open right now? Each of these questions calls for a different type of metric. This article covers the three types that handle practically every use case — counter, gauge and histogram — with a second mini application, this time in plain PHP, exposing business metrics.
2. Counter: Only Goes Up (Until the Process Restarts)
A counter is a value that only increases (or resets, if the process restarts). It’s the right type for “how many times did something happen”: number of requests, number of errors, number of orders created. The previous article’s mini app already used a counter (app_requests_total).
The _total suffix in the name is a Prometheus convention to make it explicit that the metric is a cumulative counter, not an instantaneous value — it’s worth following this convention even when writing the text by hand.
# HELP orders_created_total Total orders created
# TYPE orders_created_total counter
orders_created_total 187
3. Gauge: Goes Up and Down Freely
A gauge represents a value that can increase or decrease at any moment — it’s the right type for “how much is there right now”: open connections, items in a queue, memory in use, temperature. Unlike a counter, there’s no expected direction.
# HELP orders_queue_size Number of orders waiting to be processed
# TYPE orders_queue_size gauge
orders_queue_size 4
4. Histogram: Distribution of Values in Buckets
A histogram captures the distribution of a continuous measurement — the most common case is response time. Instead of storing every individual value (unfeasible at high scale) or just an average (which hides outliers), a histogram counts how many observations fell into predefined ranges, called buckets.
# HELP orders_duration_seconds Time to process an order
# TYPE orders_duration_seconds histogram
orders_duration_seconds_bucket{le="0.1"} 120
orders_duration_seconds_bucket{le="0.5"} 180
orders_duration_seconds_bucket{le="1"} 195
orders_duration_seconds_bucket{le="+Inf"} 200
orders_duration_seconds_sum 42.7
orders_duration_seconds_count 200
Each _bucket{le="X"} line is cumulative: “how many observations were less than or equal to X seconds”. _sum is the sum of every observed value, and _count is the total number of observations (equal to the last bucket, +Inf). With these pieces, Prometheus can calculate approximate percentiles (p50, p95, p99) at query time, via histogram_quantile — without the application having to calculate any percentile itself.
5. Mini App in Plain PHP with Business Metrics
With no framework, using only PHP’s built-in server (php -S), an application that simulates order processing and exposes the three metrics above:
<?php
// app.php
$stateFile = __DIR__ . '/metrics_state.json';
function readState($file) {
if (!file_exists($file)) {
return ['requests_total' => 0, 'queue_size' => 0, 'durations' => []];
}
return json_decode(file_get_contents($file), true);
}
function writeState($file, $state) {
file_put_contents($file, json_encode($state));
}
$state = readState($stateFile);
if ($_SERVER['REQUEST_URI'] === '/metrics') {
$buckets = [0.1, 0.5, 1.0];
$durations = $state['durations'];
$sum = array_sum($durations);
$count = count($durations);
header('Content-Type: text/plain; version=0.0.4');
echo "# HELP orders_created_total Total orders created\n";
echo "# TYPE orders_created_total counter\n";
echo "orders_created_total {$state['requests_total']}\n";
echo "# HELP orders_queue_size Number of orders waiting to be processed\n";
echo "# TYPE orders_queue_size gauge\n";
echo "orders_queue_size {$state['queue_size']}\n";
echo "# HELP orders_duration_seconds Time to process an order\n";
echo "# TYPE orders_duration_seconds histogram\n";
$cumulative = 0;
foreach ($buckets as $le) {
$cumulative = count(array_filter($durations, fn($d) => $d <= $le));
echo "orders_duration_seconds_bucket{le=\"{$le}\"} {$cumulative}\n";
}
echo "orders_duration_seconds_bucket{le=\"+Inf\"} {$count}\n";
echo "orders_duration_seconds_sum {$sum}\n";
echo "orders_duration_seconds_count {$count}\n";
exit;
}
// Simulate processing a new order
$start = microtime(true);
$state['queue_size']++;
usleep(random_int(20_000, 400_000)); // simulate real work, 20-400ms
$state['queue_size']--;
$state['requests_total']++;
$state['durations'][] = round(microtime(true) - $start, 3);
writeState($stateFile, $state);
header('Content-Type: text/plain');
echo "order processed\n";
Starting it with PHP’s built-in server:
php -S 0.0.0.0:8001 app.php
Generating a few orders and checking the metrics:
for i in $(seq 1 10); do curl -s http://localhost:8001/ > /dev/null; done
curl http://localhost:8001/metrics
The state is persisted in a local JSON file just to keep the example simple and dependency-free — in a real application, these counters usually live in the process’ own memory (and each worker/process would expose its own, leaving aggregation across replicas to Prometheus).
6. Adding the PHP App to the Stack
# docker-compose.yml (excerpt added)
services:
php-app:
image: php:8.3-cli
working_dir: /app
volumes:
- ./app.php:/app/app.php
command: ["php", "-S", "0.0.0.0:8001", "app.php"]
ports:
- "8001:8001"
# prometheus.yml (job added)
- job_name: "php-app"
static_configs:
- targets: ["php-app:8001"]
7. Querying a Histogram with histogram_quantile
With data flowing, the most useful query on a histogram in PromQL is the latency percentile:
# p95 processing time over the last 5 minutes
histogram_quantile(0.95, rate(orders_duration_seconds_bucket[5m]))
# current queue size
orders_queue_size
# orders created per second
rate(orders_created_total[1m])
histogram_quantile reconstructs the approximate percentile from the bucket distribution — the more granular the buckets around the percentile of interest, the more accurate the estimate. It’s an approximation, not an exact calculation over individual values (which Prometheus never stores one by one), but good enough for the vast majority of latency observation use cases in production.
8. Conclusion and Next Steps
We covered the three fundamental metric types — counter for cumulative counts, gauge for values that go up and down, histogram for distributions like latency — and built a second mini application, now in plain PHP, exposing real business metrics. With two different applications already sending metrics to Prometheus, the next article switches pillars: how to send logs from these same applications to Loki, and why its indexing model is so different from Prometheus’.
References: