When the Server Looks Healthy but Your App Is Paralyzed
Early in my backend career, I had an on-call shift I’ll never forget. CPU usage sat quietly at 8%, dozens of gigabytes of RAM were free, and the Uvicorn process was running cleanly. Yet customer complaints came flooding in. The app was completely frozen, and the checkout endpoint was silently churning out a barrage of 500 errors. Terminal logs whipped by like a rainstorm. I felt completely helpless—I had no clue which API was backed up, or whether our error rate was sitting at 2% or 50%.
Tools like htop and node_exporter only tell you if the host machine is still breathing; they are completely blind to the logic running inside your code. To pinpoint the real problem, you need application-level metrics. In this guide, we’ll build an end-to-end monitoring stack with Prometheus and Grafana following the RED method—quick, clean, and ready for production.
Understanding the RED Method and Prometheus
To monitor RESTful APIs or microservices effectively, SRE and DevOps teams rely heavily on the RED Method pioneered by Tom Wilkie:
- Rate (RPS): The number of requests hitting your system per second.
- Errors: The number of failed requests, primarily HTTP 5xx codes or critical business logic failures.
- Duration (Latency): The time taken to process a request. Teams typically track p95 or p99 percentiles rather than misleading averages.
Prometheus gathers data via a pull-based model. Every 5 to 15 seconds, it scrapes your FastAPI application‘s /metrics endpoint to pull runtime statistics. We’ll leverage the prometheus-fastapi-instrumentator library, which provides a turnkey middleware to collect standard metrics without polluting your route handlers.
Hands-On Implementation in 4 Steps
Step 1: Attach Instrumentator to Your FastAPI App
Install the required packages into your virtual environment:
pip install fastapi uvicorn prometheus-fastapi-instrumentator
Create a main.py file simulating typical API requests and intermittent failures:
import time
import random
from fastapi import FastAPI, HTTPException
from prometheus_fastapi_instrumentator import Instrumentator
app = FastAPI(title="FastAPI Monitoring Demo")
# Activate automated metrics collection middleware
Instrumentator().instrument(app).expose(app, endpoint="/metrics")
@app.get("/")
def home():
return {"status": "ok"}
@app.get("/api/v1/orders")
def get_orders():
# Simulate DB query delay between 50ms and 300ms
delay = random.uniform(0.05, 0.3)
time.sleep(delay)
return {"items": ["order_101", "order_102"], "latency_sec": round(delay, 3)}
@app.post("/api/v1/checkout")
def checkout():
# Simulate a 20% chance of payment gateway error
if random.random() < 0.2:
raise HTTPException(status_code=500, detail="Payment gateway timeout")
return {"status": "success", "order_id": "ord_999"}
Start the application:
uvicorn main:app --host 0.0.0.0 --port 8000
Visit http://localhost:8000/metrics. If you see dozens of text lines prefixed with http_requests_total, your instrumentation is working properly.
Step 2: Configure Prometheus and Docker Compose
Create a prometheus.yml file defining how Prometheus scrapes metrics from FastAPI:
global:
scrape_interval: 5s
scrape_configs:
- job_name: 'fastapi-app'
metrics_path: '/metrics'
static_configs:
- targets: ['host.docker.internal:8000']
Spin up Prometheus and Grafana together using docker-compose.yml:
version: '3.8'
services:
prometheus:
image: prom/prometheus:latest
container_name: prometheus_demo
volumes:
- ./prometheus.yml:/etc/prometheus/prometheus.yml
ports:
- "9090:9090"
extra_hosts:
- "host.docker.internal:host-gateway"
grafana:
image: grafana/grafana:latest
container_name: grafana_demo
ports:
- "3000:3000"
depends_on:
- prometheus
Launch the containers with a single command:
docker compose up -d
Step 3: 3 Essential PromQL Queries You Need to Master
Send a bunch of requests to your API to generate metrics. Then open http://localhost:9090 and test these three queries:
1. Calculate Requests Per Second (RPS):
sum(rate(http_requests_total{job="fastapi-app"}[1m]))
To break this down by individual route endpoints, group by the handler label:
sum by (handler) (rate(http_requests_total{job="fastapi-app"}[1m]))
2. Measure Error Rate Percentage (% Error Rate):
sum(rate(http_requests_total{job="fastapi-app",status=~"5.."}[1m]))
/
sum(rate(http_requests_total{job="fastapi-app"}[1m])) * 100
3. Measure p95 Latency:
histogram_quantile(0.95, sum(rate(http_request_duration_seconds_bucket{job="fastapi-app"}[5m])) by (le))
This tells you that 95% of requests completed faster than the reported duration, leaving the slowest 5% in the tail latency bracket.
Step 4: Build Visual Dashboards in Grafana
- Log in to
http://localhost:3000using default credentialsadmin/admin. - Navigate to Connections > Data Sources, choose Prometheus, set the URL to
http://prometheus:9090, and click Save & Test. - Select Create Dashboard > Add visualization and build three dedicated panels:
- Panel 1 (RPS): Visualization type Time Series. Paste the PromQL RPS query and set the unit to
requests/sec (rps). - Panel 2 (Error Rate): Visualization type Stat or Gauge. Paste the error rate percentage query, setting a red alert threshold if errors exceed 3%.
- Panel 3 (p95 Latency): Visualization type Time Series. Paste the histogram quantile query and set the unit to
seconds (s). If latency climbs above 0.5s, your service is facing a bottleneck.
- Panel 1 (RPS): Visualization type Time Series. Paste the PromQL RPS query and set the unit to
Wrapping Up
Setting up this monitoring stack takes only about 15 minutes. In return, you eliminate the guesswork when troubleshooting production anomalies. Every fluctuation in response times or error spikes is immediately visible on your dashboards.
When scaling out to Kubernetes clusters or multi-worker deployments, be sure to inject identifying labels like env=production or release_version. Doing so will let you isolate issues instantly right after any new rollout.

