> ## Documentation Index
> Fetch the complete documentation index at: https://notes.kodekloud.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Demo Latency Distribution Visualization Histograms and Heatmaps

> Guide to visualizing latency distributions with Prometheus histograms and Grafana heatmaps, including deployment steps, PromQL queries, and dashboard provisioning

In the previous lab we focused on time-series panels — the standard visualizations for Prometheus metrics. This lesson introduces additional visualizations: histograms and heatmaps. These let you visualize latency as a distribution instead of a single aggregated value, and show how that distribution evolves over time.

Heatmaps are especially useful for spotting whether the entire request population is slowing down (e.g., 100% of requests shift) versus only a tail (e.g., the 95th percentile). Percentiles remain important for SLOs and alerting, but heatmaps preserve distribution + time for richer troubleshooting.

Below are the deployment/provisioning steps used in this lesson followed by concrete guidance for adding histogram and heatmap panels in Grafana.

## Deploy the demo application and provision the Grafana dashboard

1. Run the app setup script to deploy the demo backend, frontend, and ServiceMonitors:

```bash theme={null}
chmod +x appsetup.sh && bash appsetup.sh
```

Representative console output (condensed):

```bash theme={null}
Step 3: Deploying backend to Kubernetes...
deployment.apps/order-backend created
service/order-backend created
Waiting for backend to be ready...
pod/order-backend-... condition met
✓ Backend deployed successfully

Step 4: Deploying frontend to Kubernetes...
deployment.apps/order-frontend created
service/order-frontend created
service/order-frontend-nodeport created
Waiting for frontend to be ready...
pod/order-frontend-... condition met
✓ Frontend deployed successfully

Step 5: Deploying ServiceMonitors...
servicemonitor.monitoring.coreos.com/order-backend created
servicemonitor.monitoring.coreos.com/order-frontend created
✓ ServiceMonitors deployed successfully
```

2. Apply the prebuilt Grafana dashboard ConfigMap (golden-signals):

```bash theme={null}
kubectl apply -f ~/.monitoring/golden-signals-configmap.yaml
kubectl logs -n monitoring deployment/prometheus-stack-grafana --since=5m
```

Representative sidecar log confirming dashboard provisioning (condensed):

```text theme={null}
/app/.venv/lib/python3.15/site-packages/urllib3/connectionpool.py:1110: InsecureRequestWarning:
  Unverified HTTPS request is being made to host '172.20.0.1'. Adding certificate verification is strongly advised.

{"time":"2026-08-18T05:35:27.154184+00:00","level":"INFO","msg":"Writing /tmp/dashboards/General/golden-signals-dashboard.json (ascii)"}
{"time":"2026-08-18T05:35:27.252440+00:00","level":"INFO","msg":"None sent to http://localhost:3000/api/admin/provisioning/dashboards/reload. Response: 200 OK ({\"message\":\"Dashboards config reloaded\"})"}
```

Provisioning dashboards via a ConfigMap + Grafana sidecar is an Infrastructure-as-Code pattern. It enables reproducible dashboards, version control, and automated dashboard deployments across environments.

***

## Why use heatmaps instead of (or in addition to) histograms?

* Histogram (single distribution): aggregates bucketed latencies across the entire time range and gives you one distribution snapshot (useful for percentiles and overall shape).
* Heatmap (distribution over time): preserves the time dimension by rendering a histogram per time slice. Color indicates density, so you can see when the distribution shifts and how the tail behaves over time.

Quick comparison:

| Visualization | Time Dimension | Good for |
| - | - | - |
| Histogram (aggregated) | No | Single-window distribution, percentiles (p50/p95/p99) |
| Heatmap | Yes | Tracking distribution changes over time, spotting population-wide shifts |

***

## Create a backend latency histogram (single aggregated distribution)

1. In Grafana, edit your dashboard → Add panel:
   * Title: Backend HTTP Latency Distribution
   * Visualization: Histogram (or keep time series and switch to Histogram)
   * Optionally hide the legend for a cleaner view.

2. Example PromQL to produce a single percentile (P95) time-series derived from histogram buckets:

```promql theme={null}
histogram_quantile(
  0.95,
  sum(rate(http_server_duration_milliseconds_bucket{http_target!~"/metrics|/health"}[$__rate_interval])) by (le)
)
```

Notes:

* `histogram_quantile()` computes the percentile from bucket counts.
* The query above produces a single timeseries (p95) — not a histogram visualization itself.
* Save the panel. This represents the distribution aggregated across the selected dashboard time range (e.g., last 15 minutes).

Limitations:

* Aggregated histograms lose the per-time-slice evolution of the distribution. If you need to know *when* a shift happened, use a heatmap.

***

## Create a backend latency heatmap (distribution over time)

1. Add a new Grafana panel:
   * Title: Backend HTTP Latency Distribution Over Time
   * Visualization: Heatmap
   * Unit: milliseconds
   * Color scheme: Spectral (useful for clear density contrast)
   * In "Calculate from data" set to No so Grafana uses your histogram buckets directly
   * Tooltip: enable "Show histogram" and set tooltip Y-axis to show histogram

2. Prometheus query — feed Grafana the bucket counts per time slice:

```promql theme={null}
sum by (le) (
  increase(
    http_server_duration_milliseconds_bucket{job="order-backend", http_target!~"/metrics|/health"}[$__rate_interval]
  )
)
```

Why this query works:

* Use the `_bucket` metric (the histogram bucket series).
* `increase(...[$__rate_interval])` returns the delta for each bucket during each Grafana interval; this produces per-time-slice counts.
* `sum by (le)(...)` aggregates across all labels except `le` (the bucket boundary). Grafana expects bucketed series keyed by `le`.

3. Configure heatmap options:
   * Format: Heatmap
   * Color scheme: Spectral (or any perceptually uniform palette)
   * Tooltip: Show histogram, set Y-axis to histogram
   * Save the dashboard.

![A dark-themed Grafana dashboard displaying order-processing metrics, with multiple charts and histograms showing HTTP latency distribution (p50/p95/p99) and time-series latency spikes. The panels include legends for endpoints like /api/orders and /health and controls for time range and refresh.](https://mintcdn.com/kodekloud-c4ac6d9a/qM9vA-hQoWNCxcKa/images/Grafana-Prometheus-for-Metrics-Driven-Observability/Visualizing-Metrics-in-Grafana/Demo-Latency-Distribution-Visualization-Histograms-and-Heatmaps/grafana-orders-latency-dashboard.jpg?fit=max\&auto=format\&n=qM9vA-hQoWNCxcKa\&q=85\&s=8ecaaee2b89e39e9bf712ea0936f0a20)

### Heatmap color selection — why Spectral helps

A multi-color palette (Spectral) makes density differences easy to spot: high-density areas appear red while low-density areas stay blue. That contrast helps you quickly identify when requests concentrate in higher-latency buckets.

### Hover histogram behavior

By enabling “Show histogram” in the tooltip and setting the tooltip Y-axis to histogram, Grafana surfaces the full bucket counts for the selected time column. This gives you both the time-series context and the exact distribution for that instant.

Correct heatmap query (repeated for clarity):

```promql theme={null}
sum by (le) (
  increase(
    http_server_duration_milliseconds_bucket{job="order-backend", http_target!~"/metrics|/health"}[$__rate_interval]
  )
)
```

***

## Use the order-processing UI to observe distribution changes

While the heatmap is visible, change the demo application's load and processing latency settings to see how the heatmap reacts. Typical controls include:

* Traffic level (low / medium / high)
* Average processing latency (fast / slower)
* Simulated error rate

When you reduce processing latency (for example, switching the demo from “slower” to “faster”), you should see:

* High-density regions shift from higher-latency buckets to lower-latency buckets over time.
* The tail (higher buckets) shrinks as queued requests complete.
* The heatmap reveals the exact times when the distribution moved.

![A screenshot of an "Order Processing Dashboard" web interface showing controls for Async Request Rate, Average Processing Latency, and Simulated Error Rate with radio buttons selected. The page also includes a "Process Order Manually" button and metric panels (total orders, successful, failed, avg latency).](https://mintcdn.com/kodekloud-c4ac6d9a/qM9vA-hQoWNCxcKa/images/Grafana-Prometheus-for-Metrics-Driven-Observability/Visualizing-Metrics-in-Grafana/Demo-Latency-Distribution-Visualization-Histograms-and-Heatmaps/order-processing-dashboard-controls-metrics.jpg?fit=max\&auto=format\&n=qM9vA-hQoWNCxcKa\&q=85\&s=597fe4c6f85093c56275da381fdc8bdb)

Which panel identifies the exact change?

* The aggregated histogram shows the overall distribution but not when a change occurred.
* The heatmap preserves distribution per time slice and is therefore best for identifying the exact timestamp when latency began to decrease. Hover any column to inspect the histogram for that moment.

When using `increase(...[$__rate_interval])`, ensure your Grafana dashboard interval aligns with your scrape interval and the cardinality of bucket series. Very long intervals or mismatched scrape configs can produce misleading deltas. Test queries in Prometheus/Explore first if results look unexpected.

***

## Summary & best practices

* Histograms give you a single aggregated distribution across the selected time window; use them for percentiles (p50/p95/p99).
* Heatmaps add time to the distribution, letting you see how latency buckets change over time.
* For Prometheus + Grafana heatmaps:
  * Use the `_bucket` metric.
  * Feed Grafana per-interval counts with `increase(...[$__rate_interval])`.
  * Aggregate with `sum by (le)(...)` so only the `le` bucket label remains.
* Choose a perceptually clear color map (Spectral or similar) to highlight density differences.
* Provision dashboards using ConfigMaps + Grafana sidecar for reproducible, version-controlled dashboards.

If you want, I can provide a copy‑paste-ready JSON panel snippet you can add to your golden-signals ConfigMap to provision the heatmap automatically.

## Links and references

* Prometheus histogram docs: [https://prometheus.io/docs/practices/histograms/](https://prometheus.io/docs/practices/histograms/)
* Grafana heatmap panel docs: [https://grafana.com/docs/grafana/latest/panels/visualizations/heatmap/](https://grafana.com/docs/grafana/latest/panels/visualizations/heatmap/)
* Prometheus query language (PromQL): [https://prometheus.io/docs/prometheus/latest/querying/basics/](https://prometheus.io/docs/prometheus/latest/querying/basics/)

> [card] [Watch Video](https://learn.kodekloud.com/user/courses/grafana-prometheus-for-metrics-driven-observability/module/38f09b30-873f-4fee-aef2-95161646dfdc/lesson/d002b604-78ab-4b28-a880-16e30f16bb7f)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.