Skip to content
ImagineWorld

Metrics That Matter (RED, USE, and KPIs)

node_idnode-book_mastering-distributed-observability-in-rust_chapter-06-metrics-that-matter-red-use-and-kpis
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num6
chapter_titleMetrics That Matter (RED, USE, and KPIs)
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Chapter 6 — Metrics That Matter (RED, USE, and KPIs)

Section titled “Chapter 6 — Metrics That Matter (RED, USE, and KPIs)”

In Chapter 5, we added database instrumentation to OpenTel E-Commerce. Every SQL query now appears as a span in Jaeger SELECT products, INSERT orders, TRANSACTION checkout. When a customer complained about a slow checkout, you opened Jaeger, found their trace, and saw exactly what happened: the reserve_stock query took 520ms, accounting for 65% of the total request time. You optimized the query, deployed the fix, and verified the next trace showed 45ms, problem solved.

Then the leadership asked How often was this happening? How many customers were affected?

You stare at Jaeger. It shows individual traces beautifully, but to answer “how many” requires manually searching through thousands of traces. You could filter by service and time range, but there’s no way to see:

  • How many checkout requests failed due to slow inventory queries this week?
  • Is the average checkout time increasing over time?
  • What percentage of requests are experiencing this issue?
  • What’s the p99 latency for all INSERT orders operations today?
  • What’s our checkout conversion rate—and did it drop when latency spiked?
  • How much revenue are we losing to failed transactions?

This is the gap that metrics fill.

Traces excel at showing what happened in a single request. Metrics excel at showing how often things happen across your entire system. So far, we’ve learned how to gain visibility into individual requests HTTP calls, database queries, and service-to-service communication. This chapter gives you visibility into patterns across millions of operations.

In this chapter, we’ll instrument OpenTel E-Commerce with metrics that complement your existing traces and database spans.

What this chapter covers:

  • What a metric actually is: name, value, dimensions, and time series
  • Metric types: counters, gauges, and histograms
  • Aggregation temporality: cumulative vs delta
  • Synchronous vs asynchronous instruments
  • The RED method for request-driven metrics
  • The USE method for resource utilization
  • Business KPIs: conversion rates, revenue tracking, and funnel analysis
  • Automatic HTTP metrics vs custom business metrics
  • Implementing metrics with OpenTelemetry in Rust
  • Exporting to Prometheus and visualizing in Grafana
  • Practical instrumentation of Orders, Inventory, and Gateway services

Many developers think of metrics as “numbers about the system” technically true, but useless. A metric is a named measurement with dimensions, and understanding this distinction transforms how you instrument code.

  1. Name: What you’re measuring (checkout_attempts_total, order_value_dollars, inventory_stock_level)
  2. Value: The measurement at a point in time (1542, 75.00, 23)
  3. Dimensions: Key-value (also called labels or attributes) pairs that add context (service=orders, status=success, product_id=abc‑123)

Think about what happens when a customer completes a purchase. An e-commerce system doesn’t just record “75.00 sale”. It captures the measurement name (order total), the value ($75.00), and a small set of low-cardinality context attributes (which service handled it, the outcome, the payment method, the product category). Without that context, the number is nearly useless. Which service? Did it succeed? What kind of payment drove the most revenue?

Resist the urge to attach high-cardinality or sensitive context, such as customer identities, individual product IDs, or shipping addresses, to a metric, those belong in traces and logs (see the cardinality discussion below). Metrics aggregate behavior across many events.

The same applies to system metrics. A counter showing “1,542 requests” means nothing without knowing which service, which endpoint, and whether those requests succeeded or failed.

When you add dimensions to a metric, each unique combination creates a separate time series, an independent sequence of measurements over time.

Consider tracking checkout attempts in OpenTel E-Commerce:

# Metric: checkout_attempts_total
# Dimensions: status, payment_method
# These create THREE separate time series:
checkout_attempts_total{status="success", payment_method="credit_card"} -> [10:00->142, 10:01->156, 10:02->171, ...]
checkout_attempts_total{status="failed", payment_method="credit_card"} -> [10:00->8, 10:01->12, 10:02->15, ...]
checkout_attempts_total{status="success", payment_method="paypal"} -> [10:00->95, 10:01->103, 10:02->118, ...]

Note on service as a dimension: When you query Prometheus, you’ll often see results grouped by job or service — but that’s actually a resource attribute (service.name) attached once per process, not a per-measurement dimension you set on each record() call. Throughout this chapter, treat service as something the SDK adds for you when metrics arrive at the backend.

How to read this notation:

Each line represents a single time series. Let’s break down the third line:

  • checkout_attempts_total: The metric name (what you’re measuring)
  • {status="success", payment_method="paypal"}: The label set (dimensions that create this unique time series)
  • ‑>: “produces” or “contains”
  • [10:00‑>95, 10:01‑>103, 10:02‑>118, ...]: A sequence of timestamp→value pairs
    • 10:00‑>95: At 10:00 AM, the counter value was 95
      • 10:01‑>103: At 10:01 AM, the counter value was 103 (8 new checkouts in that minute)
      • 10:02‑>118: At 10:02 AM, the counter value was 118 (15 new checkouts in that minute)

Each time series is stored, indexed, and queried independently. Prometheus doesn’t see “one metric” it sees three separate data streams.

Prometheus collects and stores its metrics as time series data, i.e. metrics information is stored with the timestamp at which it was recorded, alongside optional key-value pairs called labels (dimensions).

Storage cost: One time series with 7-day retention and 60-second intervals require:

(7 days × 24 hours × 60 minutes) × 16 bytes ≈ 161 KB

Small per series, but the number of series grows with every dimension combination.

When you record a metric to your backend (Prometheus, etc.), it creates a unique time series for every distinct combination of labels (attributes). This is where the danger lies.

Imagine your metrics backend is a warehouse, and every time series is a unique shelf.

The Safe Warehouse (Scenario A)

You organize your warehouse by broad categories:

  • 4 product types
  • 5 regions
  • 50 stores
  • 10 departments

That’s 4times5times50times10=10,0004 \\times 5 \\times 50 \\times 10 = 10,000 unique shelves.

  • Storage: ~1.6 GB
  • Result: ✅ Neat, organized, easy to find things. Your warehouse manager (Prometheus) is happy.

The Hoarder’s Warehouse (Scenario B)

Now you decide to give every single customer their own personal shelf.

  • 10,000 existing categories
  • times\\times 1,000,000 customers (high-cardinality dimension)

Suddenly, you need 10 billion shelves.

  • Storage: ~1.6 PB (Petabytes!)
  • Result: ❌ The warehouse collapses. The manager quits. You’re bankrupt.

This is Cardinality Explosion. It happens when you add a dimension with too many unique values (like user_id, request_id, or trace_id) to a metric.

Common anti-patterns that cause cardinality explosion:

  1. High-cardinality IDs: user_id, request_id, session_id, trace_id
    • ❌ checkout_attempts{user_id="abc‑123"} → millions of series
      • ✅ checkout_attempts{service="orders", status="success"} → dozens of series
  2. Unbounded strings: Email addresses, IP addresses, product names
    • ❌ orders_total{customer_email="[email protected]"} -> millions of series
      • ✅ orders_total{service="orders", payment_method="credit_card"} -> dozens of series
  3. Timestamps as dimensions: Millisecond precision, exact timestamps
    • ❌ checkout_duration{timestamp_ms="1707840123456"} -> 86.4 million series per day
      • ✅ checkout_duration{service="orders"} -> histogram buckets handle time automatically

Rule of thumb: If a dimension is unbounded or likely to grow into hundreds or thousands of unique values, it probably doesn’t belong in a metric. Use trace attributes instead.

The rule: Dimension values must be low-cardinality. Use categories, not identifiers.

Bad (High Cardinality)Good (Low Cardinality)
user_id="u_abc123..."user_type="premium"
order_id="ord_xyz..."order_status="pending"
request_id="req_..."(don’t include at all)
product_uuid="..."product_category="electronics"

Table 6.1 – High-cardinality versus low-cardinality dimensions for metric labels

Individual identifiers belong in traces and logs, not metrics. Metrics aggregate behavior across many events.

Metrics represent measurements in context. Think about managing a large retail store during the holiday rush. You don’t just ask “how are sales?”, but you measure. Customers per hour, failed payments, checkout wait time, and cashier utilization. Each number tells part of the story.

Your distributed system is no different.

Store MetricSystem EquivalentWhat It Reveals
Customers per hourRequest RateIs traffic spiking?
Failed paymentsError RateIs the register broken?
Checkout wait timeDuration (Latency)Are lines moving slowly?
Cashier utilizationResource SaturationIs the team overwhelmed?

Table 6.2 – Retail store metrics mapped to distributed system metrics

And just like in a store, no single metric tells the whole story. A store with zero failed payments but huge lines (high latency) is still losing customers. A store with idle cashiers but high error rates likely has broken registers.

This is why observability frameworks like RED and USE exist; they ensure you’re measuring the complete picture of your system’s health.

OpenTelemetry (and most metrics systems) support three fundamental metric types, Counters, Gauges and Histograms. Understanding, each one is essential.

A counter is a cumulative value that only increases (or resets to zero on restart). Use counters for events that happen discretely, such as requests processed, errors encountered, and bytes sent.

# Counter examples
http_requests_total{service="orders", status="200"} = 15,423
inventory_reservation_failures_total{failure_reason="insufficient_stock"} = 87
items_sold_total{category="electronics"} = 3,291

Counters track cumulative events. They answer questions like “how many requests have we served?” or “how many checkouts failed?”.

The raw value is less interesting than its rate of change. If http_requests_total was 15,000 an hour ago and is 15,423 now, your service handled 423 requests in the last hour, or about 7 requests per minute.

In Prometheus query language (PromQL), you calculate rates with the rate() function:

rate(http_requests_total[5m]) # requests per second, averaged over 5 minutes

Think of a cash register’s lifetime sales count. The total sales since the store opened 5 years ago aren’t very actionable. But the rate (sales per hour) tells the manager exactly how busy the store is right nowis and when it is at its busiest and slowest. This is what we mean by the rate of change, and it helps you decide when to open more registers or schedule more staff.

When to use counters:

  • Total requests handled
  • Total errors by type
  • Total bytes transferred
  • Total orders placed
  • Total items added to cart

A gauge is a value that can go up or down. It represents a point-in-time measurement, such as the current queue depth, active connections, and items in a shopping cart.

# Gauge examples
cart_items_current{user_type="guest"} = 3
db_connections_active{service="orders"} = 12
inventory_stock_available{product_category="electronics"} = 847
memory_used_bytes{service="products"} = 134217728

How to read gauge notation:

Unlike counters (which show cumulative totals over time), gauges show current snapshot values:

  • memory_used_bytes{service="products"} = 134217728: Right now, the products service is using 134,217,728 bytes (128 MB) of memory
  • db_connections_active{service="orders"} = 12: Right now, there are 12 active database connections
  • inventory_stock_available{product_category="electronics"} = 847: Right now, there are 847 electronics items in stock

The = shows the current value at the time of measurement. This value can go up or down with each measurement.

Gauges answer, “How much right now?” unlike counters, the raw value is the interesting number. Think of inventory stock levels, it’s a snapshot that fluctuates up (restocking) and down (sales). When a customer tries to buy an item, the current stock level is the only number that matters for the decision.

When to use gauges:

  • In-flight requests: How many users are waiting right now? (e.g., http.server.active_requests)
  • Queue depth: How many jobs are backing up in Redis?
  • Business state: How many items are currently in stock? (e.g., inventory_levels)
  • Memory usage: Are we about to OOM? (e.g., process.memory.usage)
  • Connection pools: Are we running out of database connections?

A histogram captures the distribution of values over a range. Rather than storing every individual measurement, it counts how many measurements fall into predefined buckets.

This is crucial for latency. Imagine your checkout endpoint has these response times over the last minute:

50ms, 55ms, 48ms, 52ms, 51ms, 890ms, 53ms, 49ms, 47ms, 52ms

The average is 129.7ms, but hides reality: 9 out of 10 requests completed in ~50ms, while one outlier took 890ms. The average makes the system look worse than it is for most users, while simultaneously hiding that some users had a terrible experience.

Histograms solve this by grouping requests into buckets:

# 9 requests were fast (under 100ms)
http_request_duration_seconds_bucket{le="0.1"} = 9
# 10 requests were total (adds the 890ms outlier)
http_request_duration_seconds_bucket{le="1.0"} = 10

Suddenly, the outlier is visible. You can see that while 90% of requests are fast (le="0.1"), there is a gap between 0.1s and 1.0s during which one poor user gets stuck.

From this, we can calculate percentiles:

  • p50 (Median): The “Typical” User. Half of your requests are faster than ~51ms.
  • p99 (The Outlier): The “Unlucky” User. 1% of your requests are slow (890ms).
  • p99.9: The “Very Unlucky” User. 1 in 1000 requests.

Averages hide the unhappy users. Percentiles expose them. This is why logistics companies track delivery reliability, not just average speed. A courier who delivers every package in exactly 2 days is reliable. A courier who averages 2 days but takes 1 day half the time and 10 days the other half is a disaster. The average is the same, but the customer experience is radically different. Distributions reveal what averages hide.

Customizing Histogram Buckets OpenTelemetry’s default buckets are often too broad. For fast services, you need to zoom in on the milliseconds that matter:

meter
.f64_histogram("http.server.request.duration")
.with_boundaries(vec![0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0])
.build();

This gives you 10ms granularity for fast requests while still capturing slow outliers.

When to use histograms:

  • Request latency: How long does /checkout take? (e.g., http.server.request.duration)
  • Response size: Are we accidentally sending 10MB JSON blobs? (e.g., http.response.body.size)
  • Queue wait time: How long do background jobs wait before processing?
  • Database query duration: Which SQL queries are slowing down the system?
  • Business metrics: What is the distribution of order values? (e.g., order_value_dollars)

When to avoid: Do not use histograms for categorical data (use bar charts instead) or when you need to analyze multiple dimensions simultaneously.

Different instruments produce different data shapes in your backend.

1. Counters & Gauges: The Single Line

Simple instruments produce a single time series.

# Counter (Measurement: "http.requests")
http_requests_total 1542
# Gauge (Measurement: "db.connections")
db_connections 12

2. Histograms: The Three Parts

Histograms are unique. A single histogram instrument (e.g., http.server.request.duration) exports three distinct metrics to Prometheus. Think of it as a package deal:

SuffixPurposeExample Value
_countHow many? (The Rate)1542 requests total
_sumHow much? (The Average)245.7 seconds total time
_bucketDistribution (The Percentiles)1200 requests ≤ 0.1s

Table 6.3 – The three Prometheus metrics produced by a single histogram instrument

This is why histograms are so powerful: a single instrument gives you Rate (from effectively the count. Latency (from the buckets), and, effectively, Errors (if you filter the count). One metric to rule them all.

Aggregation Temporality: Cumulative vs Delta

Section titled “Aggregation Temporality: Cumulative vs Delta”

When a counter reports its value, there’s a subtle but important question: Is this the total since the process started, or just the change since the last report?

This concept is called Temporality, and it works exactly like your car’s dashboard.

  1. Cumulative (The Odometer): Reports the running total since the start.
    • Day 1: 10,000 miles
      • Day 2: 10,100 miles
      • Prometheus expects this. It calculates the rate by subtracting yesterday’s total from today’s.
  2. Delta (The Trip Meter): Reports only the change since the last report.
    • Day 1: 100 miles
      • Day 2: 100 miles
      • StatsD expects this. It just wants to know “how much happened just now”

Why does this matter?

Different backends have different expectations:

  • Prometheus expects cumulative counters and uses rate() to calculate per-second rates
  • StatsD expects delta values

When using OTLP, you configure the exporter with the backends’ preferred temporality. For Prometheus, OpenTelemetry exporters default to cumulative temporality, which is what Prometheus OTLP receivers expect.

// In our telemetry setup, the OTLP exporter automatically uses
// cumulative temporality when targeting Prometheus - no configuration needed
let exporter = MetricExporter::builder()
.with_http()
.with_endpoint(metrics_endpoint)
.build();

For OpenTel E-Commerce, we send metrics via OTLP to Prometheus 3.0, using cumulative temporality. The defaults work correctly out of the box.

Synchronous vs. Asynchronous: Push vs. Pull

Section titled “Synchronous vs. Asynchronous: Push vs. Pull”

There are two ways to record metrics, and choosing the wrong one is a common source of bugs.

  1. Synchronous (Push): You call the SDK when an event happens.
    • Analogy: Sending a text message. “I just arrived!”
      • Usage: Request latency, bytes sent, error counts. You control when it sends.
    // Synchronous: YOU call the instrument
    counter.add(1,&[]);
  2. Asynchronous (Pull): The SDK calls you periodically.
    • Analogy: A doctor’s checkup. The doctor measures your weight during the visit. You don’t text the doctor every time you eat a sandwich.
      • Usage: Memory usage, thread counts, queue depths. The SDK controls when it reads.

Why this matters: If you try to track “current memory usage” with a synchronous gauge, you have to manually call record() everywhere memory changes. It’s impossible. Instead, you register a callback, and OpenTelemetry “pulls” the value every 60 seconds.

// Asynchronous: the SDK pulls the value when it needs to export
let pool = state.db_pool.clone();
meter
.u64_observable_gauge("db.pool.connections.active")
.with_description("Current active database connections")
.with_callback(move |observer| {
// This closure runs every collection interval (default: every 60s)
// sqlx Pool: size() = total managed, num_idle() = idle
// Active connections = size - idle
let active = pool.size().saturating_sub(pool.num_idle() as u32);
let max = pool.options().get_max_connections();
observer.observe(active as u64, &[
KeyValue::new("pool.state", "active"),
]);
observer.observe(max as u64, &[
KeyValue::new("pool.state", "max"),
]);
})
.build();
Sync (You Push)Async (SDK Pulls)Best For…
CounterObservableCounterEvents (Requests, Errors, cache hits)
UpDownCounterObservableUpDownCounterBusiness State (Items in cart, Job queue size)
GaugeObservableGaugeSystem State (CPU, Memory, Connection Pools)
Histogram(none)Distributions (Latency, Payload Size)

Table 6.4 – Synchronous versus asynchronous instruments and what each is best for

Why no Async Histogram? Histograms track distributions of events. You can’t “poll” a distribution; you have to record every event as it happens to capture the percentile.

Rule of Thumb:

  • Is it an event? (User clicked detailed, Request finished, Error occurred) rightarrow\\rightarrow Synchronous (Push).
  • Is it a state? (Memory usage, Queue size, Thread count) rightarrow\\rightarrow Asynchronous (Pull).

Example: Connection Pool Metrics

// In telemetry initialization, after creating the pool
pub fn register_pool_metrics(meter:&Meter,pool:Pool<Postgres>) {
let pool_clone = pool.clone();
// Active connections (observable gauge)
meter
.u64_observable_gauge("db.pool.connections.active")
.with_description("Active connections in the pool")
.with_callback(move |observer| {
// sqlx Pool: size() = total managed, num_idle() = idle
// Active = size - idle
let active = pool_clone.size().saturating_sub(pool_clone.num_idle() as u32);
observer.observe(active as u64,&[]);
})
.build();
// See \`products/src/telemetry.rs\` for idle connections and utilization metrics
}

The key insight: synchronous instruments are for events (things that happen), asynchronous instruments are for state (things that exist). Requests happen; use synchronous counters. Connection counts exist; use observable gauges.

RED Metrics: Request-Oriented Observability

Section titled “RED Metrics: Request-Oriented Observability”

Now that we understand the metric types, which metrics should we actually collect? Two frameworks guide this decision: RED for request-driven services and USE for resources.

RED stands for:

  • R ate: How many requests per second?
  • E rrors: How many of those requests fail?
  • D uration: How long do requests take?

For any service that handles requests (including nearly every microservice), RED metrics serve as the baseline. They answer the fundamental question: Is this service healthy from the user’s perspective?

Request rate is like foot traffic in a store. It tells you how busy your service is. A sudden drop might indicate the doors are locked (upstream failure). A sudden spike means you need more staff (autoscaling).

Key Insight: According to OpenTelemetry semantic conventions, you don’t need a separate counter for request rate. The http.server.request.duration histogram automatically tracks count internally (see “What Each Instrument Produces” in Section 6.2). When exported to Prometheus, a histogram creates:

  • http_server_request_duration_seconds_count - total count of observations
  • http_server_request_duration_seconds_sum - sum of all durations
  • http_server_request_duration_seconds_bucket{le="..."} - bucket counts for percentiles

Just like we used axum‑tracing‑opentelemetry (OtelAxumLayer) in Chapter 4 to automatically create trace spans for every HTTP request, we’ll use axum‑otel‑metrics (HttpMetricsLayerBuilder) to automatically record this histogram, no hand-rolled middleware needed:

// Automatic HTTP metrics — just add the layer to your router
let metrics = HttpMetricsLayerBuilder::new().build();
// ...
let app = Router::new()
.route("/orders", post(handlers::create_order))
.layer(metrics) // ← Automatic RED metrics

The library automatically records http.server.request.duration with semantic convention attributes (http.request.method, http.route, http.response.status_code, server.address), as well as http.server.active_requests and request/response body size histograms. Path normalization is handled automatically no regex needed.

Try it: Monitor Request Rate

  1. Open Prometheus at http://localhost:9090.
  2. Run this query to see the request rate across all services:
# Request rate per second by service
rate(http_server_request_duration_seconds_count[5m])

To zoom in on a specific endpoint (like creating orders), filter by route and method:

rate(http_server_request_duration_seconds_count{http_route="/orders", http_request_method="POST"}[5m])

Error rate is often the first indicator that something is wrong. Track both the count and the rate relative to the total number of requests.

Key Insight: With the axum‑otel‑metrics library, errors are automatically tracked through the http.response.status_code attribute on the histogram. Every response—successful or failed—is recorded, so you can filter for errors in your queries without any custom code:

Try it: Monitor Error Rate

Run this query to see the rate of failed requests (4xx and 5xx):

# Error rate (4xx and 5xx)
rate(http_server_request_duration_seconds_count{http_response_status_code=~"4..|5.."}[5m])

To see the percentage of requests that are failing (a key KPI), divide errors by total traffic:

# Error percentage
(
sum(rate(http_server_request_duration_seconds_count{http_response_status_code=~"4..|5.."}[5m]))
/
sum(rate(http_server_request_duration_seconds_count[5m]))
* 100
)
or vector(0)

Duration (latency) directly impacts user experience. As we saw with histograms, percentiles reveal what averages hide.

Try it: Monitor Latency

Run this query to see multiple percentiles at once:

# p50, p90, and p99 latency
histogram_quantile(0.50, sum(rate(http_server_request_duration_seconds_bucket[5m])) by (le))
histogram_quantile(0.90, sum(rate(http_server_request_duration_seconds_bucket[5m])) by (le))
histogram_quantile(0.99, sum(rate(http_server_request_duration_seconds_bucket[5m])) by (le))

Focus on:

  • p50: Typical experience (half of users faster)
  • p90: Most users’ worst experience
  • p99: Tail latency (important for SLAs)
  • p99.9: Extreme outliers (often reveal systematic issues)

For standard HTTP services, we get RED metrics for free. However, we also need custom metrics to track business logic.

Metric LayerWhat it tracksExample
RED (Automatic)Is the service healthy?http.server.request.duration (covers Rate, Errors, Duration for all services)
Business (Custom)Is the business healthy?orders.checkout.failures, inventory.stock.level

Table 6.5 – Automatic RED metrics versus custom business metrics by tracking purpose

Key Business Metrics to Add:

Business QuestionSignalMetric Name
Are users failing to buy?Checkout Errorsorders.checkout.failures (Counter)
Is the warehouse full?Stock Levelinventory.stock.level (Gauge)
How long do reservations take?Reservation Latencyinventory.reservation.duration (Histogram)

Table 6.6 – Key business metrics to add and the signals they provide

USE Metrics: Resource-Oriented Observability

Section titled “USE Metrics: Resource-Oriented Observability”

While RED focuses on customers (Request speed, Errors), USE focuses on the store infrastructure (Resources).

Think of your service like a physical store:

  • RED = Checkout Lanes: Are customers happy? Is the line moving?
  • USE = Warehouse & Staff: Is the shelf full? Is the staff overworked? Is there a line for the forklift?

USE stands for:

  • U tilization: How busy is the resource? (e.g., 90% of connections in use)
  • S aturation: Is work piling up? (e.g., tasks waiting for a thread)
  • E rrors: Is the resource failing? (e.g., connection refused, disk full)

USE is valuable for identifying capacity bottlenecks before they impact users.

Utilization measures the proportion of a resource currently in use. High utilization isn’t inherently bad, but sustained high utilization often precedes problems.

We have already implemented a utilization metric for our database connection pool in the Implementing Metrics section. The pattern is always the same: (active / max) * 100.

When utilization hits 100%, work starts to queue (Saturation).

Resources to monitor:

ResourceUtilization MetricConcern Threshold
CPUprocess.cpu.utilization>80% sustained
Memoryprocess.memory.utilization>85%
DB connectionsdb.pool.utilization>70%
Thread poolruntime.threads.utilization>90%

Table 6.7 – Resource utilization metrics and recommended concern thresholds

Saturation and Errors: The Breaking Points

Section titled “Saturation and Errors: The Breaking Points”

When utilization hits 100%, systems don’t just stop; they queue (Saturation) or crash (Errors).

Saturation happens when demand exceeds capacity, forcing work to wait. This is the primary cause of latency spikes.

  • Signal: Non-zero queue depth or increasing wait duration.
  • Metric: db.pool.wait_duration (Histogram).
  • Reality: The resource is working, but users are waiting.

Errors happen when the queue is full or the resource is broken.

  • Signal: Timeouts, “Pool Exhausted”, “Connection Refused”.
  • Metric: db.pool.errors (Counter).
  • Reality: The resource has given up. Users get 500s.

What to measure:

ResourceSaturation (Latency)Errors (Failure)
DB Pooldb.pool.wait_duration (Histogram)db.pool.errors (Connection timeout)
CPU/Threadsqueue.pending (Gauge)thread.pool.rejection (Counter)
Disksystem.disk.io_timesystem.disk.out_of_space

Table 6.8 – Saturation and error metrics by resource for the USE method

Key Insight: Monitor Saturation to predict problems (e.g., rising latency). Monitor Errors to react to outages (users are failing).

You can find the implementation of these metrics in code/chapter_6/products/src/telemetry.rs.

RED and USE metrics tell you how your system is performing (request rates, error percentages, latency distributions, resource utilization). These are essential for operational health. But they don’t answer the question that ultimately matters: Is the business succeeding?

A system can have perfect RED metrics (99.9% success rate, p99 latency under 100ms, zero resource saturation) while the business quietly fails. Checkout conversion might drop from 85% to 62% due to a subtle UX bug that doesn’t trigger errors. Revenue per order could decline if a change to the pricing algorithm inadvertently steers customers toward cheaper products. Technical metrics see nothing wrong; business metrics scream.

This section bridges the gap between technical observability and business outcomes. We’ll instrument OpenTel E-Commerce with three business KPIs:

  1. Conversion Rate: What percentage of checkout attempts complete successfully?
  2. Cart Abandonment: How long does checkout take, and where do users drop off?
  3. Revenue per Request: What’s the dollar impact of each transaction?

These metrics transform observability from “the system works” to “the system delivers value.”

Automatic HTTP Metrics vs Business Metrics

Section titled “Automatic HTTP Metrics vs Business Metrics”

Before we implement business KPIs, it’s important to understand what metrics we already have and why we need more.

OpenTel E-Commerce uses HttpMetricsLayer from the axum‑otel‑metrics crate, which automatically instruments every HTTP request with OpenTelemetry-compliant metrics:

  • http.server.request.duration (Histogram): Request latency with labels for method, route, and status code
  • http.server.active_requests (UpDownCounter): Number of requests currently being processed
  • http.server.request.body.size (Histogram): Request body sizes
  • http.server.response.body.size (Histogram): Response body sizes

These metrics give us complete RED metrics at the HTTP layer —request rates, error rates (via status codes), and duration distributions. They’re essential for operational health.

So why do we need custom metrics?

HTTP metrics tell you what happened at the transport layer. Business metrics tell you what happened in your domain. Consider this scenario:

HTTP metrics say:

# 100 requests to /orders, 80 returned 200 OK, 20 returned 400 Bad Request
http_server_request_duration_count{http_route="/orders", http_response_status_code="200"} = 80
http_server_request_duration_count{http_route="/orders", http_response_status_code="400"} = 20

Business metrics say:

# 100 checkout attempts, 95 passed validation, 80 completed
# 12 failed due to price mismatches (possible attack)
# 5 failed due to insufficient stock (inventory issue)
# 3 failed due to product validation errors (data quality issue)
checkout_funnel_started_total = 100
checkout_funnel_payment_info_total = 95
checkout_funnel_completed_total = 80
orders_checkout_failures_total{failure_reason="price_mismatch"} = 12
orders_checkout_failures_total{failure_reason="order_creation"} = 5
# Revenue impact: $6,400 generated, average order value $80
orders_total_amount_USD_sum = 6400
orders_total_amount_USD_count = 80

The HTTP metrics tell you, “20 requests failed.” The business metrics tell you:

  1. Why they failed (price mismatches vs stock issues vs validation errors)
  2. Where in the funnel they failed (before or after payment validation)
  3. Business impact: $6,400 in revenue, 80% conversion rate

HTTP metrics are necessary but not sufficient. They can’t measure:

  • Dollar amounts (revenue, order values)
  • Business logic outcomes (conversion rates, funnel stages)
  • Domain-specific failure reasons (price mismatches, stock issues)
  • Customer behavior (time to checkout, cart abandonment)

This is why we need both layers of metrics:

  • HTTP layer (HttpMetricsLayer): Transport-level health (requests, status codes, latency)
  • Business layer (custom orders/src/metrics.rs): Domain outcomes (revenue, conversion, failure attribution)

The rest of this section shows how to implement the business layer.

Conversion Rate: Measuring the Checkout Funnel

Section titled “Conversion Rate: Measuring the Checkout Funnel”

Every e-commerce platform has a conversion funnel, the sequence of steps a customer takes from browsing to completing a purchase. In traditional analytics, you’d track page views: product page -> cart page -> checkout page -> confirmation page. But in microservice architecture, the funnel lives in API calls, not page views.

For OpenTel E-Commerce, the checkout funnel has three stages:

  1. Funnel Started: Customer initiates checkout (POST /orders)
  2. Payment Info Validated: Products and prices are confirmed (no validation errors)
  3. Funnel Completed: Transaction commits successfully (order created)

The conversion rate is the percentage of started checkouts that complete:

Conversion Rate = (Funnel Completed / Funnel Started) × 100

A healthy e-commerce platform typically sees 70-90% conversion https://www.smartinsights.com/ecommerce/ecommerce-analytics/ecommerce-conversion-rates/. Drops below 70% indicate problems, payment gateway issues, inventory failures, or UX friction.

We’ll add three counters to track funnel stages. In orders/src/metrics.rs, add:

pub struct OrdersMetrics {
// ... existing metrics ...
// Business KPI metrics: Conversion funnel
/// Checkout funnel started (order creation initiated)
pub funnel_started: Counter<u64>,
/// Checkout funnel reached payment validation
pub funnel_payment_info: Counter<u64>,
/// Checkout funnel completed successfully
pub funnel_completed: Counter<u64>,
}

Initialize them in the metrics() function:

funnel_started: meter
.u64_counter("checkout.funnel.started")
.with_description("Checkout attempts initiated")
.build(),
funnel_payment_info: meter
.u64_counter("checkout.funnel.payment_info")
.with_description("Checkout reached payment validation")
.build(),
funnel_completed: meter
.u64_counter("checkout.funnel.completed")
.with_description("Checkout successfully completed")
.build(),

In orders/src/handlers/orders.rs, instrument the create_order handler at three points:

Stage 1: Funnel Started

pub async fn create_order(
State(state): State<AppState>,
Json(request): Json<CreateOrderRequest>,
) -> impl IntoResponse {
let start = Instant::now();
metrics().checkout_attempts.add(1,&[]);
// Business KPI: Conversion funnel started
metrics().funnel_started.add(1,&[]);
// ... validation logic ...
}

Stage 2: Payment Info Validated

After product and price validation succeeds (before stock reservation):

// Validate price matches actual product price
if item.unit_price != product.final_price {
record_checkout_failure("price_mismatch",&start);
return (StatusCode::BAD_REQUEST, /* ... */).into_response();
}
}
// Business KPI: Payment info validated (all products and prices confirmed)
metrics().funnel_payment_info.add(1,&[]);
// Reserve stock for all items...

Stage 3: Funnel Completed

When the transaction commits successfully:

match result {
Ok(created_order) => {
let duration = start.elapsed().as_secs_f64();
metrics().checkout_duration.record(duration, &[
KeyValue::new("outcome", "success"),
]);
// Business KPI: Conversion funnel completed
metrics().funnel_completed.add(1,&[]);
// ... record other success metrics ...
}
}

In Prometheus, calculate the conversion rate:

# Overall conversion rate (percentage)
(
checkout_funnel_completed_total /
checkout_funnel_started_total
) * 100

Expected result: 80-95% in a healthy system.

To see conversion rate over time (5-minute windows):

(
rate(checkout_funnel_completed_total[5m]) /
rate(checkout_funnel_started_total[5m])
) * 100
or vector(0)

If you see NaN (Not a Number), it means there’s no data yet. Run the traffic generation script (./scripts/generate_traffic.sh) to populate metrics. The or vector(0) fallback ensures the query returns 0% when there are no checkouts yet.

Funnel drop-off analysis:

# Percentage reaching payment validation
(rate(checkout_funnel_payment_info_total[5m]) / rate(checkout_funnel_started_total[5m])) * 100
or vector(0)
# Percentage completing after payment validation
(rate(checkout_funnel_completed_total[5m]) / rate(checkout_funnel_payment_info_total[5m])) * 100
or vector(0)

If the first percentage is low (<90%), customers are encountering product validation errors. If the second is low, stock reservation or transaction failures are the issue.

Cart Abandonment: Understanding Time-to-Checkout

Section titled “Cart Abandonment: Understanding Time-to-Checkout”

In a traditional e-commerce platform, cart abandonment measures how many users add items to their cart but never complete checkout. Industry average: 60-80% of carts are abandoned.

OpenTel E-Commerce doesn’t have persistent carts—checkout happens in a single API call. But we can still measure time-to-checkout: how long does the entire checkout process take? Long checkout times correlate with abandonment in real systems.

Add a histogram to measure checkout duration from start to completion. In orders/src/metrics.rs:

Two checkout-duration histograms, on purpose: the Orders service exposes two histograms that sound similar. orders.checkout.duration (checkout_duration in the struct) is the operational view used by the RED dashboards it records every attempt, success, or failure, with a status attribute. checkout.time_to_completion (time_to_checkout in the struct, used here) is the business KPI — only successful checkouts, no extra labels, optimized for funnel analysis. PromQL examples in this section use the canonical Prometheus name checkout_time_to_completion_seconds_*. If you’d rather collapse the two, pick one canonical name (we recommend orders.checkout.duration) and add outcome=success as a filter in your KPI queries.

pub struct OrdersMetrics {
// ... existing metrics ...
// Business KPI metrics: Time tracking
/// Time from checkout start to completion
pub time_to_checkout: Histogram<f64>,
}

Initialize it:

time_to_checkout: meter
.f64_histogram("checkout.time_to_completion")
.with_description("Time from checkout start to completion")
.with_unit("s")
.build(),

Record it on successful checkout (in create_order handler):

match result {
Ok(created_order) => {
let duration = start.elapsed().as_secs_f64();
// Business KPI: Time from checkout start to completion
metrics().time_to_checkout.record(duration,&[]);
// ... other success metrics ...
}
}

Average time to checkout:

sum(rate(checkout_time_to_completion_seconds_sum[5m])) /
sum(rate(checkout_time_to_completion_seconds_count[5m]))

Expected: <1 second for most checkouts.

Percentiles (p50, p90, p99):

# p50 (median)
histogram_quantile(0.5, sum(rate(checkout_time_to_completion_seconds_bucket[5m])) by (le))
# p90
histogram_quantile(0.9, sum(rate(checkout_time_to_completion_seconds_bucket[5m])) by (le))
# p99
histogram_quantile(0.99, sum(rate(checkout_time_to_completion_seconds_bucket[5m])) by (le))

If p99 is >5 seconds, investigate slow database queries or inventory service latency. Long checkout times frustrate users and increase real-world cart abandonment.

Technical metrics measure system behavior. Revenue metrics measure business impact. The most direct business metric: how much money does each request generate**?**

We already track orders.total.amount (a histogram of order dollar values). This enables powerful revenue analysis.

Where does _USD come from? The histogram is created with .with_unit("USD"), and the OTLP-to-Prometheus translation appends the unit to the metric name (just like _seconds for time histograms). So orders.total.amount becomes orders_total_amount_USD_* (_sum, _count, _bucket) in PromQL.

sum(rate(orders_total_amount_USD_sum[5m])) /
sum(rate(orders_total_amount_USD_count[5m]))

This calculates the average dollar value of completed orders over the last 5 minutes.

Why this matters: If AOV drops from 75to75 to 45, something changed, maybe a promotion attracted budget conscious customers, or a bug is preventing high-value items from being added to orders. Technical metrics won’t catch this, but revenue metrics will.

# p50: Half of orders are below this value
histogram_quantile(0.5, sum(rate(orders_total_amount_USD_bucket[5m])) by (le))
# p90: 90% of orders are below this value
histogram_quantile(0.9, sum(rate(orders_total_amount_USD_bucket[5m])) by (le))
# p99: Top 1% of orders (high-value customers)
histogram_quantile(0.99, sum(rate(orders_total_amount_USD_bucket[5m])) by (le))

This reveals customer segments. If p99 is 500butp50is500 but p50 is 30, you have a bimodal distribution—most customers are low-value, but a small segment drives significant revenue. Losing those high-value customers would devastate revenue even if order volume stays constant.

# Dollars per second
sum(rate(orders_total_amount_USD_sum[5m]))

Multiply by 3600 to get dollars per hour:

sum(rate(orders_total_amount_USD_sum[5m])) * 3600

Why this matters: This is the metric that directly ties to business goals. If this number drops, revenue is declining—even if request rates, error rates, and latency look healthy.

Connecting Business KPIs to Technical Metrics

Section titled “Connecting Business KPIs to Technical Metrics”

The power of business KPIs emerges when you correlate them with technical metrics. A drop in conversion rate isn’t actionable on its own, you need to know why it dropped.

Example correlation queries:

Conversion rate vs p99 latency:

# Conversion rate
(
(rate(checkout_funnel_completed_total[5m]) / rate(checkout_funnel_started_total[5m])) * 100
)
or vector(0)
# p99 checkout latency (same canonical metric used elsewhere in this section)
histogram_quantile(0.99, sum(rate(checkout_time_to_completion_seconds_bucket[5m])) by (le))

Graph these together. If conversion rate drops when p99 latency spikes, slow checkouts are causing users to abandon.

Revenue vs error rate:

# Revenue per hour
sum(rate(orders_total_amount_USD_sum[5m])) * 3600
# Checkout error rate
(
(rate(orders_checkout_failures_total[5m]) / rate(orders_checkout_attempts_total[5m])) * 100
)
or vector(0)

If revenue drops correlate with error rate spikes, payment gateway failures, or inventory issues, they are costing money.

Technical metrics tell you the system is working. Business KPIs tell you the system is delivering value.

Consider this scenario:

  • RED metrics: 99.5% success rate, p99 latency 150ms
  • USE metrics: 45% CPU, 60% memory, no saturation
  • Business KPIs: Conversion rate dropped from 82% to 58%

What happened? A subtle bug in the inventory service is incorrectly marking products as out of stock. Technically, the system works, requests succeed, latency is fine, and resources are healthy. But 38% of customers who try to buy can’t complete checkout. Revenue is plummeting.

Technical metrics missed it. Business KPIs caught it immediately. This is why business KPIs aren’t optional; they’re the metrics that connect observability to outcomes.

OpenTel E-Commerce needs metrics instrumentation. We’ll extend the telemetry module from Chapter 4 to include the OpenTelemetry Metrics SDK.

In Cargo.toml, notice the following dependencies:

[dependencies]
# ...
# Note: Use reqwest-blocking-client for metrics (PeriodicReader thread has no Tokio runtime)
opentelemetry-otlp = { version = "0.31", default-features = false, features = [
"grpc-tonic", "http-proto", "reqwest-blocking-client", "trace", "metrics", "logs", "internal-logs"
] }
# Automatic HTTP metrics middleware (pinned to a commit SHA so the example keeps
# building even if the upstream \`main\` branch makes breaking changes)
axum-otel-metrics = { git = "https://github.com/ttys3/axum-otel-metrics.git", rev = "ab04b0510fdac894028dca95727d2c395d56e5a1" }
# ... existing tracing dependencies

The axum‑otel‑metrics crate is the metrics counterpart to axum‑tracing‑opentelemetry from Chapter 4. Just as OtelAxumLayer automatically creates trace spans for incoming HTTP requests, HttpMetricsLayerBuilder automatically records http.server.request.duration histograms with OpenTelemetry semantic convention attributes.

The features for opentelemetry‑otlp:

  • grpc‑tonic - gRPC transport for traces (to Jaeger)
  • http‑proto - HTTP transport for metrics (to Prometheus)
  • reqwest‑blocking‑client - Blocking HTTP client for metrics (required because the PeriodicReader runs on a separate thread without a Tokio runtime)

In Chapter 4 we exposed a free function shutdown_telemetry(tracer_provider) that the application called explicitly before exit. Now that we have a second provider (MeterProvider) — and Chapter 7 will add a third for logs — it’s cleaner to bundle them into a single guard value whose Drop implementation flushes everything for us:

products/src/telemetry.rs
/// Holds every provider we initialize. Keep this value alive for the
/// lifetime of the application; dropping it flushes pending telemetry
/// and shuts each provider down in turn.
pub struct TelemetryGuard {
tracer_provider: SdkTracerProvider,
meter_provider: SdkMeterProvider,
}
impl Drop for TelemetryGuard {
fn drop(&mut self) {
if let Err(e) = self.meter_provider.shutdown() {
eprintln!("MeterProvider shutdown failed: {e:?}");
}
if let Err(e) = self.tracer_provider.shutdown() {
eprintln!("TracerProvider shutdown failed: {e:?}");
}
}
}

Evolving from Chapter 4: The standalone shutdown_telemetry() function is replaced by this guard pattern. The application no longer must remember to call shutdown_telemetry(), simply hold the guard returned by init_telemetry for the lifetime of the program (let _telemetry = telemetry::init_telemetry("orders");) and drop it at the end of main to flush both traces and metrics. Chapter 7 will extend this struct with a logger_provider field, and the same Drop impl will continue to work.

With the guard in place, init_telemetry simply wires up both providers and returns them:

// See products/src/telemetry.rs for the full implementation
pub fn init_telemetry(service_name: &str) -> TelemetryGuard {
// 1. Create a Resource to identify the service. \`service.name\` is a
// *resource* attribute attached once per process — it's *not* set on
// each individual measurement.
let resource = Resource::builder()
.with_service_name(service_name.to_string())
.build();
// 2. Resolve the metrics endpoint. The real implementation honors
// \`OTEL_EXPORTER_OTLP_METRICS_ENDPOINT\` (and falls back to
// \`OTEL_EXPORTER_OTLP_ENDPOINT\`); the literal below is just a
// development-time default if no env var is set.
let metrics_endpoint = std::env::var("OTEL_EXPORTER_OTLP_METRICS_ENDPOINT")
.or_else(|_| std::env::var("OTEL_EXPORTER_OTLP_ENDPOINT"))
.unwrap_or_else(|_| "http://localhost:9090/api/v1/otlp/v1/metrics".into());
let exporter = MetricExporter::builder()
.with_http()
.with_endpoint(&metrics_endpoint)
.build()
.expect("Failed to create metric exporter");
// 3. Build the MeterProvider
let provider = SdkMeterProvider::builder()
.with_resource(resource)
.with_periodic_exporter(exporter)
.build();
// 4. Set as global provider
global::set_meter_provider(provider.clone());
// ... tracing init (also reads OTEL_EXPORTER_OTLP_TRACES_ENDPOINT) ...
TelemetryGuard {
tracer_provider,
meter_provider: provider,
}
}

Endpoint precedence: The OpenTelemetry SDK uses OTEL_EXPORTER_OTLP_<SIGNAL>_ENDPOINT (e.g. OTEL_EXPORTER_OTLP_METRICS_ENDPOINT), then falls back to the generic OTEL_EXPORTER_OTLP_ENDPOINT. Anything you pass to .with_endpoint(...) in code wins over both — explicit configuration always overrides environment variables in opentelemetry‑otlp.

Each service creates a Meter from the global provider. The meter is the factory for creating metric instruments. Since axum‑otel‑metrics handles HTTP RED metrics automatically, our metrics structs only contain business-specific metrics:

// See orders/src/metrics.rs for full implementation
pub struct OrdersMetrics {
pub checkout_attempts: Counter<u64>,
pub order_total_amount: Histogram<f64>,
// ... other metrics (failures, duration, item count)
}
static METRICS: OnceLock<OrdersMetrics> = OnceLock::new();
pub fn metrics() -> &'static OrdersMetrics {
METRICS.get_or_init(|| {
let meter = global::meter("orders-service");
OrdersMetrics {
checkout_attempts: meter
.u64_counter("orders.checkout.attempts")
.with_description("Total checkout attempts")
.build(),
order_total_amount: meter
.f64_histogram("orders.total.amount")
.with_unit("USD")
.build(),
// ... init other metrics
}
})
}

In addition to HTTP and business metrics, the Orders service should expose database pool metrics for USE monitoring (see Section 6.3). Add this to the service initialization:

orders/src/main.rs
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
// Initialize telemetry
let _telemetry = telemetry::init_telemetry("orders-service");
// Create database pool
let pool = // pool creation ...;
// Register pool metrics (USE method - utilization, saturation, errors)
let meter = opentelemetry::global::meter("orders-service");
telemetry::register_pool_metrics(&meter,pool.clone());
// ... rest of server setup
}

The register_pool_metrics function from Section 6.3 creates observable gauges that automatically report:

  • db.pool.connections.active — currently active connections
  • db.pool.connections.idle — available idle connections
  • db.pool.utilization (with unit %) — percentage in use

These metrics enable the USE dashboard panels in Section 6.6.

The Orders service demonstrates these metrics in action, focusing on the checkout flow we traced in previous chapters.

Automatic HTTP Metrics with axum-otel-metrics

Section titled “Automatic HTTP Metrics with axum-otel-metrics”

In Chapter 4, we used OtelAxumLayer from axum‑tracing‑opentelemetry to automatically create trace spans for every incoming HTTP request. For metrics, we follow the same pattern: use HttpMetricsLayerBuilder from axum‑otel‑metrics to automatically record RED metrics for all requests.

orders/src/main.rs
fn create_router(state: AppState) -> Router {
// Build the HTTP metrics layer — records http.server.request.duration
// automatically for every request with semantic convention attributes
let metrics = HttpMetricsLayerBuilder::new().build();
Router::new()
// ...
.layer(metrics) // ← Automatic RED metrics (new in Ch. 6)
// ...
}

That’s it. No hand-rolled middleware, no path normalization regex, no manual attribute construction. The library handles:

  • http.server.request.duration (Histogram) — request latency in seconds, with semantic convention attributes:
    • http.request.method (e.g., GET, POST)
      • http.route (normalized path: /orders/{uuid})
      • http.response.status_code (e.g., 200, 404, 500)
      • server.address (host header)
  • http.server.active_requests (UpDownCounter) concurrent in-flight requests
  • http.server.request.body.size (Histogram) request body sizes in bytes
  • http.server.response.body.size (Histogram) response body sizes in bytes

Path normalization (replacing /orders/abc123 with /orders/{uuid}) is handled automatically using Axum’s route definitions, the same mechanism OtelAxumLayer uses for trace spans. This ensures low-cardinality metrics even with dynamic path parameters.

Why not hand-roll with middleware::from_fn? You can write custom middleware that creates histograms, normalizes paths with regex, and builds attributes manually. But HttpMetricsLayerBuilder does all of this out of the box—correct attribute names, proper semantic conventions, automatic path normalization—without the boilerplate. For most Axum services, the library approach is both simpler and more correct. This mirrors our Chapter 4 decision to use OtelAxumLayer over a custom TraceLayer.

HTTP RED metrics are now automatically. The checkout handler only needs business-specific instrumentation for domain operations that the HTTP layer can’t see:

orders/src/handlers/orders.rs
pub async fn create_order(...) -> ... {
let start = Instant::now();
// 1. Record attempt
metrics().checkout_attempts.add(1,&[]);
// Business KPI: Conversion funnel started
metrics().funnel_started.add(1,&[]);
// ... validate products, reserve inventory ...
// 2. On success: Record duration and business value
let duration = start.elapsed().as_secs_f64();
metrics().checkout_duration.record(duration, &[
KeyValue::new("outcome", "success"),
]);
metrics().order_total_amount.record(
order.total_amount.to_f64().unwrap_or(0.0),
&[],
);
Ok(Json(OrderResponse::from(order)))
}
// Helper to record failures with reasons
fn record_checkout_failure(reason: &str, start: &Instant) {
// Record failure count and duration labeled with "outcome=failure"
metrics().checkout_failures.add(1, &[
KeyValue::new("reason", reason.to_string()),
]);
metrics().checkout_duration.record(
start.elapsed().as_secs_f64(),
&[KeyValue::new("outcome", "failure")]
);
}

The Inventory service manages stock levels, a perfect candidate for USE metrics alongside RED.

inventory/src/metrics.rs
pub struct InventoryMetrics {
// Track reservation attempts to measure traffic
pub reservation_attempts: Counter<u64>,
// Track latency to find bottlenecks
pub reservation_duration: Histogram<f64>,
// Track business outcome (units sold/reserved)
pub reserved_quantity: Counter<u64>,
// ... other metrics (failures, etc.)
}
static METRICS: OnceLock<InventoryMetrics> = OnceLock::new();
pub fn metrics() -> &'static InventoryMetrics {
METRICS.get_or_init(|| {
let meter = global::meter("inventory-service");
InventoryMetrics {
reservation_attempts: meter
.u64_counter("inventory.reservation.attempts")
.with_description("Total stock reservation attempts")
.build(),
reservation_duration: meter
.f64_histogram("inventory.reservation.duration")
.with_unit("s")
.build(),
reserved_quantity: meter
.u64_counter("inventory.reserved.quantity")
.with_unit("units")
.build(),
// ... init other metrics
}
})
}
// inventory/src/handlers/inventory.rs (simplified)
pub async fn reserve_stock(...) -> impl IntoResponse {
let start = Instant::now();
// 1. Record incoming demand (Traffic)
metrics().reservation_attempts.add(1,&[]);
// ... execute database reservation ...
let duration = start.elapsed().as_secs_f64();
match result {
Ok(success) if success => {
// 2. Success: Record latency and business value
metrics().reservation_duration.record(duration, &[
KeyValue::new("outcome", "success"),
]);
metrics().reserved_quantity.add(request.quantity as u64,&[]); // Business Value
// ... return OK ...
}
_ => {
// 3. Failure: Record error reason and latency
let reason = if let Ok(false) = result { "insufficient_stock" } else { "database_error" };
metrics().reservation_failures.add(1, &[
KeyValue::new("reason", reason),
]);
metrics().reservation_duration.record(duration, &[
KeyValue::new("outcome", "failure"),
]);
// ... return Error ...
}
}
}

The OtelMart gateway routes requests to backend services. As an API gateway, it doesn’t own business domain logic, but it focuses on request routing, aggregation, and upstream service health. Its metrics reflect this role.

Note on Architecture: This chapter shows a typed UpstreamClient with explicit methods (get_product, check_stock, create_order) to clearly demonstrate metric instrumentation patterns. The actual codebase uses a transparent proxy pattern (proxy::products, proxy::inventory, proxy::orders) for simpler routing. Both approaches support the same metrics instrumentation—the patterns shown here apply to any HTTP client code.

The gateway’s own HTTP RED metrics (http.server.request.duration) are like in Orders and Inventory. The metrics struct only contains upstream service metrics but, these require manual instrumentation because they measure outbound HTTP calls, not incoming requests.

Why manual? In Chapter 4, we added reqwest‑tracing to automatically create trace spans for outbound HTTP calls. But reqwest‑tracing only produces spans—it does not emit metrics. Unlike the server side, where axum‑otel‑metrics gives us http.server.request.duration for free, there is no equivalent Rust crate that automatically records http.client.request.duration histograms for outbound requests. This is a gap in the current ecosystem, so we instrument client-side RED metrics by hand.

otelmart/src/metrics.rs
use opentelemetry::{global, metrics::Histogram};
use std::sync::OnceLock;
/// Gateway-specific metrics.
/// Inbound HTTP RED metrics are handled automatically by axum-otel-metrics.
/// This struct tracks outbound (upstream) service call metrics.
pub struct GatewayMetrics {
// Upstream service metrics - critical for gateway health
pub upstream_request_duration: Histogram<f64>,
}
static METRICS: OnceLock<GatewayMetrics> = OnceLock::new();
pub fn metrics() -> &'static GatewayMetrics {
METRICS.get_or_init(|| {
let meter = global::meter("otelmart-gateway");
GatewayMetrics {
// Upstream: Duration (histogram automatically tracks count)
// Manual because these are outbound HTTP calls, not served requests
upstream_request_duration: meter
.f64_histogram("http.client.request.duration")
.with_description("Duration of requests to upstream services")
.with_unit("s")
.build(),
}
})
}

The gateway calls the Products, Inventory, and Orders services. We wrap these calls to capture upstream latency and errors:

otelmart/src/proxy/mod.rs
pub async fn proxy_request(
service_url: &str,
req: Request,
http_client: &ClientWithMiddleware,
) -> impl IntoResponse {
let start = Instant::now();
// 1. Forward request to upstream service
let response = http_client.request(method,⌖_url).send().await;
let duration = start.elapsed().as_secs_f64();
// 2. Derive service name from URL (e.g., "http://products:3001" -> "products")
let upstream_service = derive_upstream_service(service_url);
match response {
Ok(resp) => {
let status = resp.status();
// 3. Record success with status code
metrics().upstream_request_duration.record(duration, &[
KeyValue::new("upstream.service", upstream_service),
KeyValue::new("http.request.method", method_str),
KeyValue::new("http.response.status_code", status.as_u16() as i64),
]);
// ... forward response ...
}
Err(_) => {
// 4. Record connection failure
metrics().upstream_request_duration.record(duration, &[
KeyValue::new("upstream.service", upstream_service),
KeyValue::new("http.request.method", method_str),
KeyValue::new("error.type", "connection_error"),
]);
// ... return 503 ...
}
}
}

A gateway’s health depends on its upstream services. The metrics we capture answer critical questions:

QuestionMetric QueryWhy It Matters
Is the gateway responsive?histogram_quantile(0.99, http_server_request_duration_seconds_bucket)Gateway’s own latency
What’s the request rate?rate(http_client_request_duration_seconds_count[5m])Request volume by service
Which upstream is slow?histogram_quantile(0.99, http_client_request_duration_seconds_bucket)Identify the bottleneck service
Are upstream failing?rate(http_client_request_duration_seconds_count{error_type!=""}[5m])Detect service degradation
What’s the error breakdown?Filter by error_type attributeConnection vs HTTP vs parse errors

Table 6.9 – Gateway metric queries and the operational questions they answer

When the gateway’s p99 latency spikes, these metrics immediately reveal whether the problem is in the gateway itself or an upstream service and which one.

The Products service is a read-heavy catalog service. Unlike Orders and Inventory, it doesn’t have complex business operations; it serves product data from the database. Its instrumentation is minimal because axum‑otel‑metrics handles all the critical RED metrics automatically.

products/src/main.rs
fn create_router(state: AppState) -> Router {
// Build the HTTP metrics layer
let metrics = HttpMetricsLayerBuilder::new().build();
Router::new()
// ...
.layer(metrics) // ← Automatic RED metrics
// ...
}

The Products service has no business operations beyond database queries. All meaningful metrics come from the automatic HTTP instrumentation:

MetricWhat It Reveals
http.server.request.durationQuery latency (mostly database SELECT performance)
rate(http_server_request_duration_seconds_count)Catalog browse activity
http_response_status_code="404"Missing product requests (inventory sync issues?)

Table 6.10 – The metrics that the Products service gets automatically from HTTP instrumentation

If Products later adds features like search or recommendations, those would warrant custom metrics:

// Future: custom metrics for advanced features
pub struct ProductsMetrics {
pub search_queries: Counter<u64>,
pub search_duration: Histogram<f64>,
pub recommendation_cache_hits: Counter<u64>,
}

But for now, HTTP RED metrics tell the complete story.

The Metrics Pipeline: Direct OTLP to Prometheus

Section titled “The Metrics Pipeline: Direct OTLP to Prometheus”

With metrics instrumented in our services, we need infrastructure to collect, store, and visualize them. The architecture is surprisingly simple: services push metrics directly to Prometheus 3.0 via OTLP, eliminating the need for an intermediate collector.

Traditional Prometheus deployments use a pull model: Prometheus scrapes /metrics endpoints on each service. This works but creates operational overhead; services must expose endpoints, Prometheus must discover them, and firewalls must allow inbound connections.

Prometheus 3.0 introduced native OTLP support, flipping the model. Services push metrics to Prometheus’s OTLP receiver. This aligns with how we already send traces to Jaeger and simplifies the architecture:

Services -> OTLP Push -> Prometheus (metrics storage)
Services -> OTLP Push -> Jaeger (trace storage)
Both -> Grafana (visualization)

The benefits are immediate:

  • Consistent pattern: Same push model for traces and metrics
  • Simpler networking: Outbound-only connections from services
  • No service discovery: Services know where to send data
  • Native protocol: No format conversion needed

When a request hits the Orders service, here’s what happens:

  1. Instrumentation records: HttpMetricsLayerBuilder captures the request duration and increments counters
  2. SDK aggregates: The MeterProvider batches measurements in memory
  3. Periodic export: Every 60 seconds, the OTLP exporter sends accumulated metrics to Prometheus
  4. Prometheus stores: Time series are persisted in Prometheus’s TSDB
  5. Grafana queries: Dashboard panels execute PromQL queries against Prometheus

The diagram shows the complete flow:

Diagram illustrating a monitoring system architecture with three main sections: Instruments, Application, and Infrastructure. It shows data flow from metrics collection (Histogram, Counter, Gauge) through MeterProvider, PeriodicReader, and Exporters (OTLP HTTP, OTLP gRPC) to Prometheus 3.0 and Jaeger for querying via Grafana, highlighting communication protocols and ports (HTTP:9090, gRPC:4317). AI-generated content may be incorrect.

Figure 6.1 – The end-to-end telemetry pipeline showing metrics pushed to Prometheus 3.0 via OTLP HTTP and traces pushed to Jaeger via OTLP gRPC

Notice the separation: metrics flow via HTTP to Prometheus’s OTLP endpoint (/api/v1/otlp/v1/metrics), while traces flow via gRPC to Jaeger. This separation allows independent scaling and retention policies.

The infrastructure requires three components working together. Docker Compose orchestrates them:

services:
# Jaeger receives traces via OTLP gRPC on port 4317
jaeger:
image: jaegertracing/all-in-one:latest
ports:
- "16686:16686" # Jaeger UI
- "4317:4317" # OTLP gRPC receiver
environment:
- COLLECTOR_OTLP_ENABLED=true
# Prometheus 3.0 receives metrics via OTLP HTTP on port 9090
prometheus:
image: prom/prometheus:v3.0.0
command:
- '--config.file=/etc/prometheus/prometheus.yml'
- '--web.enable-otlp-receiver' # Enable native OTLP ingestion
volumes:
- ./prometheus.yml:/etc/prometheus/prometheus.yml:ro
ports:
- "9090:9090" # UI and OTLP endpoint
# Grafana queries both Prometheus and Jaeger
grafana:
image: grafana/grafana:latest
ports:
- "3000:3000"
depends_on:
- prometheus
- jaeger

The critical flag is ‑‑web.enable‑otlp‑receiver on Prometheus. Without it, the OTLP endpoint returns 404.

Prometheus configuration is minimal since we’re not scraping anything:

prometheus.yml
global:
scrape_interval: 15s # Used for rule evaluation timing
evaluation_interval: 15s # How often to evaluate recording/alerting rules
# No scrape_configs needed - we use OTLP push model exclusively

The scrape_interval and evaluation_interval settings remain because Prometheus uses them for internal operations (recording rules, alert evaluation), even though we’re not scraping services.

Each service needs two environment variables to know where to send telemetry:

# In docker-compose.yml, for each service:
environment:
- OTEL_EXPORTER_OTLP_TRACES_ENDPOINT=http://jaeger:4317
- OTEL_EXPORTER_OTLP_METRICS_ENDPOINT=http://prometheus:9090/api/v1/otlp/v1/metrics
- OTEL_SERVICE_NAME=orders # Becomes the 'job' label in Prometheus

Notice the different protocols: traces use gRPC (port 4317), metrics use HTTP with a specific path (/api/v1/otlp/v1/metrics). Our init_telemetry function from Section 6.5 reads these environment variables (OTEL_EXPORTER_OTLP_TRACES_ENDPOINT and OTEL_EXPORTER_OTLP_METRICS_ENDPOINT, falling back to OTEL_EXPORTER_OTLP_ENDPOINT) and configures the exporters accordingly. Anything passed explicitly to .with_endpoint(...) in code overrides whatever the environment provides.

The OTEL_SERVICE_NAME is particularly important for metrics. Prometheus converts this to a job label, which we use in queries to filter by service: http_server_request_duration_seconds_count{job="orders"}.

Once the stack starts, you can verify the pipeline is working by querying Prometheus directly:

curl 'http://localhost:9090/api/v1/query?query=http_server_request_duration_seconds_count' \
| jq '.data.result[] | {job: .metric.job}'

This queries for HTTP request metrics and groups them by service. A working pipeline shows:

{"job": "products"}
{"job": "inventory"}
{"job": "orders"}
{"job": "otelmart"}

If metrics don’t appear, the problem is usually one of three things:

  1. Services can’t reach Prometheus: Check Docker networking and that services can resolve prometheus:9090
  2. Prometheus didn’t start with OTLP enabled: Verify ‑‑web.enable‑otlp‑receiver in the command
  3. Exporters are configured incorrectly: Check service logs for OTLP export errors

The beauty of this architecture is its simplicity. No agents, no sidecars, no collectors. Services push, Prometheus stores, Grafana visualizes. This directness makes debugging straightforward that follow the path from instrument to storage.

Dashboards: Visualizing the Request Journey

Section titled “Dashboards: Visualizing the Request Journey”

Metrics in Prometheus are useful for querying, but their power emerges when visualized. Grafana transforms time series data into dashboards that reveal patterns invisible in raw numbers. This section teaches you to build dashboards that show system health at a glance.

Before querying metrics in Grafana, you need to understand how Prometheus stores OTLP metrics. When metrics arrive via OTLP, Prometheus applies transformations:

Original (OTLP)Prometheus StorageReason
http.server.request.durationhttp_server_request_duration_secondsDots -> underscores, unit appended
orders.checkout.attemptsorders_checkout_attempts_totalCounter gets _total suffix
db.pool.utilization (unit: %)db_pool_utilization_percentUnit appended

Table 6.11 – How OTLP metric names are transformed when stored in Prometheus

Histograms create multiple metrics from a single instrument:

  • http.server.request.duration becomes:
    • http_server_request_duration_seconds_bucket{le="0.1"} (bucket counts)
      • http_server_request_duration_seconds_count (total observations)
      • http_server_request_duration_seconds_sum (sum of all values)

The service.name resource attribute becomes the job label, which you use to filter by service.

Grafana needs a data source before it can query anything. Open Grafana at http://localhost:3000, log in (default credentials: admin/admin), and add Prometheus as a data source pointing to http://prometheus:9090. Test the connection—a green success message confirms Grafana can reach Prometheus.

Before building dashboards, verify metrics are flowing. Use Grafana’s Explore feature to run a test query: http_server_request_duration_seconds_count. If results appear, the pipeline works. If not, the problem is usually that services are not sending metrics or Prometheus is not receiving them.

RED metrics (Rate, Errors, Duration) form the baseline for any request-driven service. Build a dashboard that visualizes all three.

Request rate tells you how busy your services are (foot traffic). A sudden drop might indicate the doors are locked (upstream failure); a spike might explain increased wait times. The query derives the rate from the histogram’s count:

sum(rate(http_server_request_duration_seconds_count[5m])) by (job)

Breaking this down:

  • http_server_request_duration_seconds_count — total request count from the histogram
  • rate(...[5m]) — per-second rate averaged over 5 minutes
  • sum(...) by (job) — aggregate across all dimensions except service name

Visualize this as a time series graph with {{job}} as the legend. Units should be requests/sec. You’ll see separate lines for products, inventory, orders, and otelmart—each showing their customer load over time.

Error rate reveals when services start failing (customers leaving empty-handed). The query filters for 4xx and 5xx status codes:

(
sum(rate(http_server_request_duration_seconds_count{http_response_status_code=~"4..|5.."}[5m])) by (job)
/
sum(rate(http_server_request_duration_seconds_count[5m])) by (job)
* 100
)
or
(
sum(rate(http_server_request_duration_seconds_count[5m])) by (job) * 0
)

This calculates the percentage of requests that failed. The regex "4..|5.." matches any status code starting with 4 or 5. Multiply by 100 to get a percentage.

Use a time-series visualization with thresholds: green below 1%, yellow below 5%, and red at 5% or higher. These thresholds are arbitrary and can be adjusted based on your SLOs. The key is making problems visually obvious.

Average latency hides outliers. Percentiles reveal the truth about customer experience. The query calculates p50, p90, and p99:

# p50 (median)
histogram_quantile(0.5,
sum(rate(http_server_request_duration_seconds_bucket[5m])) by (le, job)
)
# p90 (90th percentile)
histogram_quantile(0.9,
sum(rate(http_server_request_duration_seconds_bucket[5m])) by (le, job)
)
# p99 (99th percentile)
histogram_quantile(0.99,
sum(rate(http_server_request_duration_seconds_bucket[5m])) by (le, job)
)

The histogram_quantile function requires the le (less than or equal) label from histogram buckets. It interpolates between buckets to estimate percentiles. The rate() function is necessary because histogram buckets are cumulative counters.

Create three queries in the same panel. Units should be seconds. You’ll see three lines per service one for each percentile. The gap between p50 and p99 reveals variability. A tight cluster means consistent speed; a wide gap means some customers are stuck in line while others breeze through.

Technical metrics are necessary but insufficient. Business metrics reveal user impact. For an e-commerce system, checkout success rate is critical:

(
sum(rate(orders_checkout_attempts_total[5m]))
-
sum(rate(orders_checkout_failures_total[5m]))
)
/
sum(rate(orders_checkout_attempts_total[5m]))
* 100

This calculates (attempts ‑ failures) / attempts * 100. Visualize it as a Stat panel (single number) with thresholds: green above 95%, yellow above 90%, red below 90%. This single number tells you whether users can complete purchases, and no number of technical metrics can replace that signal.

USE metrics (Utilization, Saturation, Errors) to monitor resources. For our services, database connection pools are the critical resource.

db_pool_utilization_percent{job=~".+"}

This queries the observable gauge we registered in Section 6.3. Visualize it as a Gauge panel showing current utilization. Thresholds: green below 70%, yellow below 90%, red at 90% or higher. Sustained high utilization means you’re running out of connections.

db_pool_connections_idle{job=~".+"}

This is the second observable gauge we registered (db.pool.connections.idle). It tells you how many connections are available right now. Sustained zero idle connections, combined with high utilization, means the pool is the bottleneck, and new requests will block while waiting for a connection. If you need true wait-time histograms (e.g., db.pool.wait_duration), sqlx doesn’t expose them out of the box; you’d record them yourself around pool.acquire() calls. We deliberately keep the example simple and rely on utilization plus idle count for now.

Rather than querying undefined metrics, monitor actual business operations:

sum(rate(inventory_reservation_attempts_total[5m])) by (job)

This shows how often inventory reservations occur proxy for checkout load on the Inventory service.

Effective dashboards follow patterns:

  1. Top-line metrics first: Most critical numbers at the top (error rate, checkout success)
  2. Context below: Supporting details underneath (latency percentiles, resource utilization)
  3. One metric per panel: Don’t cram multiple unrelated metrics into one visualization
  4. Consistent time ranges: Synchronize time across all panels so you can correlate signals
  5. Thresholds indicate health: Green/yellow/red makes problems visually obvious

A well-designed dashboard answers “Is the system healthy?” at a glance. Detailed investigation occurs in separate drill-down dashboards or in Explore mode.

Beyond these specific queries, here are patterns for exploring metrics:

GoalPromQL PatternExample
Rate of counterrate(metric_total[5m])rate(orders_checkout_attempts_total[5m])
Percentage(a / b) * 100Error rate formula above
Histogram percentilehistogram_quantile(0.99, sum(rate(metric_bucket[5m])) by (le))Latency p99
Sum across labelssum(metric) by (label)sum(http_server_request_duration_seconds_count) by (job)
Increase over windowincrease(metric_total[1h])increase(orders_checkout_attempts_total[1h])

Table 6.12 – Common PromQL patterns for metric exploration

For comprehensive PromQL documentation, see the Prometheus query documentation https://prometheus.io/docs/prometheus/latest/querying/basics/.

The key to effective dashboards is iteration. Start with RED and USE. Observe what patterns emerge. Add business metrics when technical metrics don’t explain user impact. Remove metrics that nobody looks at. A dashboard with 50 panels is useless—focus on the signals that matter.

Metrics reveal patterns best under realistic load. The following script simulates users browsing products, checking inventory, and completing purchases:

for i in {1..50}; do
# Browse products (80% of traffic)
curl -s http://localhost:4200/api/products > /dev/null
# Check specific item availability (60% of traffic)
curl -s http://localhost:4200/api/inventory/a7f3c5d2-1234-5678-9abc-def012345678/stock > /dev/null
# Complete purchase (20% of traffic - every 5th iteration)
if [ $((i % 5)) -eq 0 ]; then
curl -s -X POST http://localhost:4200/api/orders \
-H "Content-Type: application/json" \
-d '{
"customer_email": "test'$i'@example.com",
"items": [{
"product_uuid": "a7f3c5d2-1234-5678-9abc-def012345678",
"product_name": "Sample Product",
"quantity": 1,
"unit_price": "19.99"
}],
"shipping_address": {"first_name": "Test", "last_name": "User", "address_line1": "123 Main St", "city": "Springfield", "state": "IL", "postal_code": "62701", "country": "US"},
"payment": {"payment_method": "credit_card", "card_last4": "4242", "card_brand": "visa"}
}' > /dev/null
fi
sleep 0.5
done

This traffic pattern mimics reality: many users browse, fewer check specific items, and even fewer complete purchases. The 500ms delay between requests creates a sustained load without overwhelming the system.

Open Grafana at http://localhost:3000 and navigate to your RED dashboard. As traffic flows, watch the patterns emerge:

Request Rate shows the load distribution across services. The Gateway handles every request (100%), Products serve most browse traffic (80%), Inventory gets checked frequently (60%), but Orders only processes completed checkouts (20%). The ratio reveals your conversion funnel.

Error Rate should hover near zero. If you see spikes, check which service is failing. A 404 from Products might indicate missing catalog data. A 409 from Inventory indicates a stock reservation conflict. A 500 from Orders points to database or business logic failures.

Latency Percentiles tell multiple stories. Watch the gap between p50 and p99. A tight cluster means predictable performance. A wide gap in reveals outliers, but some requests are much slower. If p99 latency spikes, look at the corresponding service’s resource utilization. Is the database pool saturated? Is CPU maxed?

Checkout Success Rate is the single most important business metric. It should stay above 95%. If it drops, the problem might not show in technical metrics. Inventory might have stock, the database might be healthy, but a subtle bug in the checkout flow causes failures. This metric forces you to care about outcomes, not just system health.

Metrics detect problems; traces explain them. This is the observability loop:

  1. Grafana shows latency spike: p99 latency on Orders jumps from 100ms to 800ms at 14:32
  2. Open Jaeger at that timestamp: Search for Orders service traces around 14:32
  3. Identify the slow span: A trace shows database: INSERT order took 650ms (81% of total time)
  4. Investigate root cause: Check database metrics—connection pool utilization spiked to 95%
  5. Fix the issue: Increase pool size or optimize the query

Without metrics, you wouldn’t know when to look. Without traces, you wouldn’t know what to fix. Together, they form a complete diagnostic system.

As you observe the dashboards, watch for these patterns:

Sawtooth patterns in request rate indicate periodic batch operations or scheduled tasks. This is often normal, but unexpected sawtooth patterns might reveal retry storms or cascading failures.

Sudden drops to zero mean something broke. Check whether the service crashed, whether upstream routing failed, or whether a dependency went down.

Gradual latency increases suggest resource exhaustion. Memory leaks, connection pool depletion, or database table growth all manifest as slowly rising latency.

Error rate spikes that recover might indicate transient network issues, database failovers, or circuit breakers opening and closing. Sustained error rates mean something is broken and needs fixing.

Business metrics diverging from technical metrics reveal the most insidious problems. The system looks healthy (low CPU, low latency), but checkout success drops. This gap between technical health and business outcomes is why you instrument business operations separately.

The Journey from Instrumentation to Insight

Section titled “The Journey from Instrumentation to Insight”

You started this chapter by, adding a few lines of code to record metrics. Now you have dashboards showing request patterns, error rates, latency distributions, resource utilization, and business outcomes. The instrumentation was mechanical: call .record(), increment counters. The insight is emergent and the patterns that no individual metric or trace could reveal alone, a single metric or trace could reveal on its own.

This is the power of metrics at scale. A single trace shows one request’s journey. Metrics show your entire system’s behavior over time. Together, they transform observability from “something went wrong” to “here’s exactly what happened, when it started, and what to fix.”

In Chapter 7, we’ll add the final pillar: structured logs. You’ll see how logs, metrics, and traces work together metrics detect anomalies, traces pinpoint requests, and logs reveal the internal state that led to the problem.

Lessons Learned: How Metrics Change Developer Thinking

Section titled “Lessons Learned: How Metrics Change Developer Thinking”

Adding metrics to a system changes how developers approach problems. Here are the patterns that emerge:

Before histograms, teams optimize for average latency. A 100ms average feels acceptable. But adding percentiles often reveals that p99 is 2.3 seconds—one in a hundred users waits over two seconds, potentially thousands of people daily. Histograms reveal bimodal distributions: most requests complete in 50ms, but cache misses take 2+ seconds. Fixing cache hit rates improves user experience far more than micro-optimizing the happy path.

Lesson 2: Business Metrics Matter More Than Technical Ones

Section titled “Lesson 2: Business Metrics Matter More Than Technical Ones”

CPU utilization, memory usage, and request counts are necessary but insufficient. The metric that matters is, often checkout success rate or its equivalent. When that drops from 98% to 91%, revenue suffers—even when all technical metrics look healthy. Subtle race conditions in inventory reservation might only manifest under specific timing conditions. Technical metrics see nothing unusual; business metrics scream.

Lesson 3: Cardinality Discipline Saves Infrastructure

Section titled “Lesson 3: Cardinality Discipline Saves Infrastructure”

A common early mistake is adding a customer_id dimension to track per-user latency. Within a week, Prometheus consumes 40GB of memory, and queries take minutes. Removing that single dimension brings memory usage to 2GB and query times to milliseconds. The question to ask: “Will this dimension value have thousands of unique values?” If yes, it belongs in traces, not metrics.

Lesson 4: The RED/USE Combination Covers Most Needs

Section titled “Lesson 4: The RED/USE Combination Covers Most Needs”

Many teams add metrics reactively a new metric for each incident. A better approach: start with RED (for every request-handling service) and USE (for every shared resource), then add business-specific metrics. This framework ensures baseline coverage and prevents gaps.

Lesson 5: Metrics and Traces Complement Each Other

Section titled “Lesson 5: Metrics and Traces Complement Each Other”

Metrics tell you something is wrong. Traces tell you what is wrong. Without metrics, you don’t know where to look. Without traces, you can’t figure out why. Chapter 4 built traces. This chapter built metrics. Together, they form a diagnostic system more powerful than either alone.

This chapter transformed OpenTel E-Commerce from a system we could trace into a system we can monitor. Metrics provide the aggregate view that traces cannot—patterns across thousands of requests, trends over time, and early warning signs of degradation.

What we implemented:

  • Metric fundamentals: Name, value, dimensions, and time series with cardinality awareness
  • Three metric types: Counters for events, gauges for current state, histograms for distributions
  • What each instrument produces: Data point types and their fields (Sum, Gauge, Histogram)
  • Aggregation temporality: Understanding cumulative vs delta and when each applies
  • Synchronous vs asynchronous instruments: Push-based events vs pull-based state observation
  • RED metrics: Rate, Errors, Duration for request-driven services
  • USE metrics: Utilization, Saturation, Errors for resources
  • OpenTelemetry Metrics API: Meters, instruments, and attributes in Rust
  • Automatic HTTP metrics: axum‑otel‑metrics for RED metrics, manual instrumentation for business operations
  • Service instrumentation: Orders, Inventory, and Gateway with business metrics
  • Collection pipeline: OTLP -> Prometheus 3.0 (native) -> Grafana
  • Visualization: Dashboards for RED, USE, and business intelligence

The metrics toolkit:

What to MeasureApproachMetric Name Example
HTTP request duration, rate, errorsAutomatic (axum‑otel‑metrics)http.server.request.duration
Business eventsManual (Counter)orders.checkout.attempts, inventory.reservation.failures
Business operation durationManual (Histogram)orders.checkout.duration, inventory.reservation.duration
Current state (polled)Manual (ObservableGauge)db.pool.connections.active
Upstream service callsManual (Histogram)http.client.request.duration

Table 6.13 – The complete metrics toolkit with approach and example metric name

Key insight: Automatic + Manual = Complete Coverage

Just as Chapter 4 combined automatic tracing (OtelAxumLayer) with manual spans (#[instrument]), this chapter combines automatic metrics (HttpMetricsLayerBuilder) with manual business metrics. The library handles HTTP RED metrics following OpenTelemetry semantic conventions; you focus on domain-specific instrumentation:

  • HTTP RED (automatic): Request rate via rate(http_server_request_duration_seconds_count[5m])
  • Error filtering (automatic): Filter by http_response_status_code attribute for 4xx/5xx errors
  • Latency percentiles (automatic): Query histogram buckets with histogram_quantile()
  • Business metrics (manual): Domain operations like rate(orders_checkout_failures_total[5m])

This separation keeps your code focused on business logic while ensuring standard HTTP metrics are consistent across all services.

Key principles:

  • Automatic instrumentation for HTTP, manual for business logic
  • Low cardinality in dimensions, categories, not identifiers
  • Percentiles over averages for latency
  • RED for services, USE for resources
  • Synchronous for events, asynchronous for state
  • Business metrics reveal user impact
  • Metrics detect, traces explain

In Chapter 7, we’ll tackle the third pillar: logs. We’ll integrate structured logging with trace correlation, ensuring that when you click a span in Jaeger, you can see the exact log messages from that operation. The three pillars will finally converge into a unified observability system.