
Building an API is one thing. Keeping it healthy after deployment is a different challenge.
Imagine you've deployed a FastAPI application, and everything looks good during testing. Your endpoints respond quickly, database queries work as expected, and users can access the application without any issues.
A few days later, traffic increases. Some requests start taking three or four seconds to complete. Database connections occasionally time out, and users report that certain endpoints are slower than usual. You check the application logs, but nothing immediately explains the problem.
This is where monitoring becomes essential.
Without proper monitoring, you're mostly guessing. You might increase server resources, optimize database queries, or rewrite a piece of code without knowing whether any of those changes will solve the actual problem.
In this guide, we'll build a monitoring setup for a FastAPI application using Prometheus, Grafana, and OpenTelemetry. We'll collect application metrics, visualize performance, instrument requests, and explore how distributed tracing helps identify bottlenecks in production.
The goal isn't just to install a few monitoring tools. It's to understand how they work together and how to use them when something goes wrong.
1. Why Do FastAPI Applications Need Monitoring?
FastAPI provides excellent performance, asynchronous request handling, and automatic API documentation. However, it doesn't automatically give you a complete picture of how your application behaves in production.
You still need to answer questions such as:
How many requests is the application handling per second?
Which endpoints have the highest response times?
How often are requests failing?
Are database queries becoming slower?
Is CPU or memory usage increasing?
Which downstream service is causing a delay?
Did the latest deployment introduce a performance problem?
These questions become especially important when your application depends on PostgreSQL, MongoDB, Redis, external APIs, or background workers.
For example, suppose your /api/products endpoint usually responds in 150 milliseconds but suddenly starts taking 1.8 seconds.
There could be several reasons:
A database query is scanning too many records.
Redis is experiencing connection problems.
An external service is responding slowly.
The application is running out of available database connections.
Traffic has increased beyond the server's capacity.
Monitoring helps you narrow down the possibilities instead of making random changes.
Monitoring vs. Observability
These terms are related, but they aren't exactly the same.
Monitoring involves tracking known signals, such as request counts, error rates, CPU usage, and response times.
Observability goes further by helping you investigate unexpected behavior using the information your system produces.
For modern backend applications, three important types of telemetry are:
Metrics: Numerical measurements collected over time.
Logs: Individual records describing events that occurred in the application.
Traces: Records showing how a request moves through different components.
Prometheus is primarily used for metrics collection and querying. Grafana provides dashboards and visualization. OpenTelemetry provides APIs, SDKs, and instrumentation for generating and exporting telemetry, including metrics and traces.
Together, they give you a much clearer picture of your FastAPI application's health.
2. Understanding the Monitoring Architecture
Before writing code, let's understand how the components fit together.
A typical setup looks like this:
Client Request
|
v
FastAPI Application
|
+-----------+-----------+
| | |
v v v
Metrics Traces Logs
| | |
v v v
Prometheus OpenTelemetry Log Backend
| Collector |
v | |
+-----------+------------+
|
v
Grafana
|
v
Dashboards and AlertsThis is a conceptual architecture. The exact data flow depends on how you configure your exporters and storage backends.
Let's look at each component.
Prometheus: Collecting Metrics
Prometheus is an open-source monitoring system that collects numerical measurements from applications and infrastructure.
For example, your FastAPI application might expose metrics such as:
http_requests_total
http_request_duration_secondsPrometheus periodically scrapes the configured metrics endpoint and stores the collected time-series data.
You can then query that data using PromQL, Prometheus's query language.
Grafana: Visualizing Application Health
Grafana connects to data sources such as Prometheus and displays the collected information through dashboards.
You can create panels for:
Requests per second.
HTTP error rates.
API response-time percentiles.
CPU and memory usage.
Database connection pressure.
Service availability.
Instead of checking several terminal commands, you can open one dashboard and see whether the application is behaving normally.
OpenTelemetry: Instrumenting the Application
OpenTelemetry, often abbreviated as OTel, provides a standard way to generate and export telemetry.
It supports instrumentation for traces, metrics, and logs.
For distributed tracing, it can record how a request moves through multiple services.
Consider an API endpoint that performs the following operations:
Receives a request in FastAPI.
Queries PostgreSQL.
Calls an external payment service.
Stores a result in Redis.
Returns a response.
If the request takes two seconds, a trace can help show which operation consumed most of that time.
That is much more useful than knowing only the total response time.
3. Setting Up the FastAPI Project
Let's create a small FastAPI application and add monitoring to it.
We'll use:
FastAPI for the API.
Uvicorn as the ASGI server.
prometheus-clientfor Prometheus metrics.prometheus-fastapi-instrumentatorfor HTTP instrumentation.OpenTelemetry for distributed tracing.
Docker Compose to run the application, Prometheus, Grafana, and an OpenTelemetry Collector.
Start by creating a project directory:
mkdir fastapi-monitoring
cd fastapi-monitoringCreate a virtual environment:
python3 -m venv venv
source venv/bin/activateOn Windows, activate it with:
venv\Scripts\activateInstall the initial dependencies:
pip install fastapi "uvicorn[standard]" prometheus-client prometheus-fastapi-instrumentatorInstall the OpenTelemetry packages:
pip install \
opentelemetry-api \
opentelemetry-sdk \
opentelemetry-exporter-otlp \
opentelemetry-instrumentation-fastapi \
opentelemetry-instrumentation-loggingWe'll use the OTLP exporter to send telemetry to the OpenTelemetry Collector.
Create the following structure:
fastapi-monitoring/
├── app/
│ ├── __init__.py
│ └── main.py
├── prometheus/
│ └── prometheus.yml
├── otel-collector/
│ └── config.yml
├── docker-compose.yml
├── Dockerfile
└── requirements.txt4. Adding Prometheus Metrics to FastAPI
Let's begin with the simplest part: collecting HTTP metrics.
Create app/main.py:
from fastapi import FastAPI, HTTPException
from prometheus_fastapi_instrumentator import Instrumentator
app = FastAPI(
title="FastAPI Monitoring Demo",
version="1.0.0",
)
Instrumentator().instrument(app).expose(
app,
endpoint="/metrics",
)
@app.get("/")
async def root():
return {
"message": "FastAPI monitoring is running"
}
@app.get("/api/products")
async def get_products():
return {
"products": [
{"id": 1, "name": "Laptop"},
{"id": 2, "name": "Keyboard"},
{"id": 3, "name": "Mouse"},
]
}
@app.get("/api/slow")
async def slow_endpoint():
import asyncio
await asyncio.sleep(1)
return {
"message": "Request completed"
}
@app.get("/api/error")
async def error_endpoint():
raise HTTPException(
status_code=500,
detail="Simulated internal server error",
)Let's understand what's happening.
The Instrumentator automatically records HTTP-related metrics for supported FastAPI requests.
Calling .instrument(app) enables instrumentation, while .expose(app, endpoint="/metrics") adds an endpoint that Prometheus can scrape.
Start the application:
uvicorn app.main:app --reloadOpen the following endpoint on your local server:
http://localhost:8000/metricsYou'll see Prometheus-formatted metrics.
You can also test the application:
curl http://localhost:8000/
curl http://localhost:8000/api/products
curl http://localhost:8000/api/slow
curl http://localhost:8000/api/errorAfter sending a few requests, refresh the metrics endpoint.
The instrumentator should expose HTTP metrics, including request counts and request-duration observations, depending on its configuration and installed version.
Why Is This Useful?
Suppose your application handles 20,000 requests per hour. You don't want to inspect every request manually.
Instead, you can track aggregate measurements and identify patterns.
For example:
Are request counts increasing?
Is the 500 error rate higher than usual?
Are requests taking longer after a deployment?
Is a particular endpoint consistently slower than others?
Metrics make these questions easier to answer.
Be Careful with Metric Labels
Avoid using unique values such as user IDs, email addresses, request IDs, or arbitrary URLs as Prometheus labels.
For example, this is a bad idea:
http_requests_total{user_id="12345"}If every user generates a new label value, the number of time series can grow dramatically. This is known as high cardinality, and it can consume significant memory and storage.
Prefer bounded labels such as HTTP method, status code, and normalized route.
Use traces or structured logs when you need request-level investigation.
5. Configuring Prometheus
Now that the application exposes metrics, Prometheus needs to know where to scrape them.
Create prometheus/prometheus.yml:
global:
scrape_interval: 15s
evaluation_interval: 15s
scrape_configs:
- job_name: "fastapi"
metrics_path: /metrics
static_configs:
- targets:
- "app:8000"The scrape_interval controls how frequently Prometheus collects metrics.
Here, Prometheus scrapes the application every 15 seconds.
The target app:8000 assumes the FastAPI service is named app in Docker Compose. Docker Compose creates a network in which services can generally reach one another by service name.
If you're running Prometheus directly on your machine rather than in Docker, the target would normally be something like localhost:8000.
What Happens During a Scrape?
Prometheus sends an HTTP request to the application's /metrics endpoint.
The application responds with its current metric values and accumulated observations.
Prometheus stores the samples as time-series data, which you can query later.
For example, request counters can be used to calculate request rates over a time window.
Prometheus does not automatically discover every application on your network. You must configure scrape targets or set up an appropriate service-discovery mechanism.
6. Connecting Grafana to Prometheus
Prometheus collects and stores the metrics, but Grafana makes them easier to explore.
After launching Grafana, open its web interface and configure Prometheus as a data source.
Use the following values when running Grafana and Prometheus in the same Compose network:
Data source type: Prometheus
URL: http://prometheus:9090The hostname prometheus refers to the Prometheus service name in Docker Compose.
After saving the data source, open the Explore section and start running PromQL queries.
Query 1: Total Requests Per Second
sum(
rate(http_requests_total[5m])
)This query calculates the request rate over a five-minute window and sums it across matching time series.
The exact metric names depend on the instrumentation configuration. Inspect the /metrics output first and adapt the query if your installed version exposes different names.
Query 2: HTTP 5xx Error Rate
If your request counter includes a status label, a query might look like this:
sum(
rate(http_requests_total{status=~"5.."}[5m])
)This calculates the rate of HTTP 5xx responses.
If your metric uses a different label name, adjust the selector accordingly.
For a percentage error rate, divide the 5xx request rate by the total request rate and multiply by 100:
100 *
sum(rate(http_requests_total{status=~"5.."}[5m]))
/
clamp_min(
sum(rate(http_requests_total[5m])),
0.001
)The clamp_min() expression prevents division by zero when the total request rate is extremely low or zero. In a production dashboard, you may also choose to display no data when there is no traffic.
Query 3: Average Request Duration
The instrumentator commonly exposes request duration as a Prometheus histogram.
If the histogram uses the metric name http_request_duration_seconds, you can calculate average duration like this:
sum(
rate(http_request_duration_seconds_sum[5m])
)
/
sum(
rate(http_request_duration_seconds_count[5m])
)This gives average request duration across the selected time series.
Average latency is useful, but it can hide occasional slow requests. That's why production dashboards should also include percentiles.
Query 4: 95th Percentile Latency
For a histogram with a le bucket label:
histogram_quantile(
0.95,
sum by (le) (
rate(http_request_duration_seconds_bucket[5m])
)
)This estimates the 95th percentile of request duration over the selected time window.
In simple terms, approximately 95% of observed requests completed within this estimated duration, while the slowest 5% took longer.
Histogram quantiles are estimates, and their accuracy depends on the configured bucket boundaries and traffic volume.
7. Adding OpenTelemetry Tracing
Prometheus tells us that requests are slow. Distributed tracing helps explain why.
Let's instrument FastAPI with OpenTelemetry and export traces to an OpenTelemetry Collector.
The Collector will receive the traces and forward them to a tracing backend.
For this example, we'll use Jaeger as the trace storage and visualization backend. Grafana can remain our dashboarding tool for metrics, while Jaeger provides a dedicated interface for exploring traces.
This separation is common in monitoring stacks: Prometheus stores metrics, a tracing backend stores traces, and Grafana can integrate with supported data sources to correlate the signals.
Step 1: Configure OpenTelemetry
Create app/telemetry.py:
from opentelemetry import trace
from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import (
OTLPSpanExporter,
)
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
def configure_tracing() -> None:
resource = Resource.create(
{
"service.name": "fastapi-monitoring-api",
"deployment.environment": "development",
}
)
provider = TracerProvider(resource=resource)
exporter = OTLPSpanExporter(
endpoint="otel-collector:4317",
insecure=True,
)
provider.add_span_processor(
BatchSpanProcessor(exporter)
)
trace.set_tracer_provider(provider)The resource attributes identify the service that produced the telemetry.
The BatchSpanProcessor collects spans and exports them in batches rather than making a separate export request for every span.
The endpoint assumes the application runs inside Docker Compose and can resolve otel-collector as a service name.
Important: insecure=True is suitable only for a trusted local development network. For production deployments, configure the appropriate TLS and authentication settings for your telemetry pipeline.
Step 2: Instrument the FastAPI Application
Update the relevant parts of app/main.py:
from fastapi import FastAPI
from opentelemetry.instrumentation.fastapi import (
FastAPIInstrumentor,
)
from app.telemetry import configure_tracing
configure_tracing()
app = FastAPI(
title="FastAPI Monitoring Demo",
)
FastAPIInstrumentor.instrument_app(app)Keep the existing routes and Prometheus instrumentation in the same application.
OpenTelemetry's FastAPI instrumentation creates spans for incoming requests. Depending on the libraries you instrument, traces can also include database queries and outgoing HTTP requests.
For example, if the /api/products endpoint calls a database, tracing can show how much time was spent in the HTTP handler and how much time was spent waiting for the database.
To capture more detail, instrument supported database drivers and HTTP clients. Avoid adding sensitive request data or credentials to span attributes.
Step 3: Add a Custom Span
Automatic instrumentation is useful, but sometimes you want to measure a specific operation.
Add this example to a route or service function:
from opentelemetry import trace
tracer = trace.get_tracer(__name__)
async def calculate_product_recommendations():
with tracer.start_as_current_span(
"calculate_product_recommendations"
) as span:
span.set_attribute(
"recommendations.algorithm",
"popular_products",
)
# Replace this with your actual recommendation logic.
recommendations = [
"Laptop",
"Keyboard",
"Mouse",
]
return recommendationsThe custom span appears as a child operation within the active request trace when called inside an instrumented request context.
You can use custom spans to measure operations such as:
Recommendation generation.
Data transformation.
External API calls.
Search operations.
Report generation.
Avoid creating thousands of tiny spans for trivial operations. Trace volume has storage and processing costs, so instrument meaningful boundaries.
8. Configuring the OpenTelemetry Collector
The OpenTelemetry Collector acts as an intermediary between your application and telemetry backends.
It can receive, process, filter, batch, and export telemetry.
Create otel-collector/config.yml:
receivers:
otlp:
protocols:
grpc:
endpoint: 0.0.0.0:4317
http:
endpoint: 0.0.0.0:4318
processors:
batch:
exporters:
otlp/jaeger:
endpoint: jaeger:4317
tls:
insecure: true
service:
pipelines:
traces:
receivers: [otlp]
processors: [batch]
exporters: [otlp/jaeger]This configuration receives OTLP traces over gRPC or HTTP and exports them to Jaeger using OTLP over gRPC.
Both the collector and Jaeger must be connected to the same trusted Docker network for the example to work.
The Collector's receiver endpoints are bound to all interfaces within its container. In production, avoid exposing telemetry receiver ports publicly without suitable network controls and authentication.
9. Running the Stack with Docker Compose
Running all the monitoring components locally makes it easier to test the setup before deploying it.
Create a Dockerfile:
FROM python:3.12-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY app ./app
CMD [
"uvicorn",
"app.main:app",
"--host",
"0.0.0.0",
"--port",
"8000"
]Create requirements.txt with the dependencies used by the project:
fastapi
uvicorn[standard]
prometheus-client
prometheus-fastapi-instrumentator
opentelemetry-api
opentelemetry-sdk
opentelemetry-exporter-otlp
opentelemetry-instrumentation-fastapi
opentelemetry-instrumentation-loggingFor repeatable builds, pin tested package versions in your actual project rather than leaving every dependency unbounded.
Now create docker-compose.yml:
services:
app:
build: .
ports:
- "8000:8000"
depends_on:
- otel-collector
prometheus:
image: prom/prometheus
ports:
- "9090:9090"
volumes:
- ./prometheus/prometheus.yml:/etc/prometheus/prometheus.yml:ro
grafana:
image: grafana/grafana
ports:
- "3000:3000"
depends_on:
- prometheus
jaeger:
image: jaegertracing/jaeger
ports:
- "16686:16686"
- "4317:4317"
otel-collector:
image: otel/opentelemetry-collector-contrib
command: ["--config=/etc/otelcol-contrib/config.yaml"]
volumes:
- ./otel-collector/config.yml:/etc/otelcol-contrib/config.yaml:ro
depends_on:
- jaegerThe image tags are intentionally illustrative. For a reliable environment, pin compatible image versions and check the Collector and Jaeger configuration against those versions.
Start the stack:
docker compose up --buildOnce the services are running, you can access:
FastAPI:
http://localhost:8000Prometheus:
http://localhost:9090Grafana:
http://localhost:3000Jaeger:
http://localhost:16686
For a local demo, these ports are convenient. Don't expose Prometheus, Grafana, or Jaeger publicly in production without appropriate authentication and network restrictions.
10. Building a Useful Grafana Dashboard
A dashboard should help you make decisions quickly. Adding every available metric usually makes it harder to find the information that matters.
Start with four panels.
Panel 1: Request Rate
Use a PromQL query that calculates requests per second:
sum(rate(http_requests_total[5m]))This helps you understand traffic patterns.
If request volume suddenly drops to zero during a period when the application should be active, investigate service availability, routing, and scrape health.
Panel 2: Error Rate
Display the proportion of requests that return server errors.
100 *
sum(rate(http_requests_total{status=~"5.."}[5m]))
/
clamp_min(sum(rate(http_requests_total[5m])), 0.001)A rising error rate can indicate an application regression, database outage, dependency failure, or resource problem.
Remember that HTTP 4xx responses may be expected behavior. For example, a validation error is not necessarily an application failure.
Panel 3: Response Time
Use the 95th percentile query from the earlier section.
Averages alone can be misleading. Imagine most requests complete in 100 milliseconds, but a small percentage take five seconds. The average might still look acceptable while some users experience serious delays.
Tracking p95 and, where useful, p99 latency helps reveal those slow requests.
Panel 4: Prometheus Target Health
Prometheus exposes the up metric for each scrape target.
up{job="fastapi"}A value of 1 means the most recent scrape succeeded. A value of 0 means Prometheus could not successfully scrape that target.
This is a useful signal, but it isn't a complete application availability check. An endpoint might return metrics successfully even when a critical business operation is broken.
For production monitoring, combine scrape health with meaningful application metrics and external availability checks.
11. Creating Alerts for Production Issues
Dashboards are useful when someone is watching them. Alerts are necessary when a problem needs attention without someone continuously checking charts.
Prometheus supports alert rules that can be sent to an alerting system such as Alertmanager.
For example, create a file named prometheus/alerts.yml:
groups:
- name: fastapi-alerts
rules:
- alert: FastAPITargetDown
expr: up{job="fastapi"} == 0
for: 2m
labels:
severity: critical
annotations:
summary: "FastAPI metrics target is down"
description: "Prometheus has been unable to scrape FastAPI for two minutes."This rule fires when the FastAPI target remains down for two minutes.
To activate it, reference the alert file in your Prometheus configuration:
rule_files:
- "alerts.yml"Mount the alert file into the Prometheus container and ensure that Alertmanager is configured if you want notifications delivered to email, Slack, or another supported destination.
A second useful alert could detect sustained high latency. The exact expression depends on your application's histogram metric names and your service-level objectives.
Avoid setting alert thresholds without understanding normal traffic patterns. An alert that fires constantly will eventually be ignored.
12. How to Debug a Slow FastAPI Endpoint
Let's bring everything together with a practical example.
Suppose users report that your product search endpoint is taking two seconds to respond.
Here's how you can investigate.
Step 1: Check the metrics dashboard.
Look at request rate, error rate, and p95 latency. Determine whether the issue affects every endpoint or only product search.
Step 2: Inspect the request trace.
Open a slow trace in Jaeger. Check the duration of the individual spans.
You might find that the FastAPI handler takes two seconds overall, but the database query accounts for 1.7 seconds.
Step 3: Investigate the database query.
Use PostgreSQL query analysis to check whether the query is performing a sequential scan, joining too many rows, or sorting a large dataset.
Step 4: Fix the underlying problem.
Depending on the findings, you might add an appropriate index, rewrite the query, reduce unnecessary data retrieval, or implement pagination.
Step 5: Verify the improvement.
Compare the p95 latency before and after the change. Check that the improvement persists under realistic traffic and that the error rate hasn't increased.
This is the practical value of observability. Instead of guessing which component is responsible, you use evidence to locate the bottleneck and verify the fix.
13. Production Best Practices
A monitoring setup that works on a developer's laptop needs additional planning before it can support a production system.
Protect Monitoring Endpoints
The /metrics endpoint may reveal internal application behavior, route patterns, and operational information.
Avoid exposing it publicly unless you have a specific reason and appropriate controls. In production, you can restrict access through private networking, firewall rules, or a separate internal listener.
Use Sampling for High-Traffic Traces
Recording every trace can become expensive as traffic increases.
OpenTelemetry supports sampling strategies that control which traces are recorded. Head-based sampling makes the decision early in the request, while tail-based sampling can make decisions after collecting trace data, such as retaining traces that contain errors or unusually long durations.
Tail-based sampling requires additional Collector configuration and resources. Sampling should be designed around the investigation needs of your service.
Monitor Dependencies
Application-level metrics are only part of the picture.
If FastAPI depends on PostgreSQL, Redis, or an external API, monitor those dependencies as well.
Useful signals include database connection utilization, query latency, cache hit rate, Redis errors, external API latency, and connection failures.
Track Deployments
Include useful service attributes such as service name, environment, and version.
When response times increase after a deployment, being able to compare the previous version with the current one can significantly reduce debugging time.
Avoid Sensitive Telemetry
Never place passwords, access tokens, API keys, payment details, or unnecessary personal information in metric labels, span attributes, or logs.
Telemetry systems often retain data for extended periods and may be accessible to more people than the primary application database.
Apply access controls and retention policies appropriate to your environment.
Monitor the Monitoring System
Prometheus, Grafana, and the Collector are also services that can fail.
Track scrape failures, Collector export errors, queue pressure, dropped telemetry, storage capacity, and alert-delivery failures.
A monitoring stack that silently stops collecting data can give you a false sense of security.
Define Service-Level Objectives
Don't rely exclusively on arbitrary thresholds.
For example, a service-level objective might require that 99% of successful product-search requests complete within 500 milliseconds over a rolling 30-day period.
The appropriate target depends on your application's requirements and user expectations.
Use metrics and traces to measure performance against the target, and design alerts around meaningful degradation rather than every minor fluctuation.
Conclusion
Monitoring is an important part of running a FastAPI application in production. Knowing that your API is responding is useful, but understanding how quickly it responds, how often it fails, and which dependencies are causing delays is much more valuable.
Prometheus gives you a reliable way to collect and query application metrics. Grafana turns those metrics into dashboards that help you understand traffic, latency, and errors. OpenTelemetry adds standardized instrumentation and distributed tracing, making it easier to investigate what happens inside a request.
Start with a few useful signals: request rate, error rate, p95 latency, and application availability. Add tracing for important request paths, then expand your monitoring as your application grows.
You don't need an elaborate observability platform on day one. You need enough reliable information to answer a simple question when something breaks: What is happening, where is it happening, and what evidence tells me why?
Once your monitoring setup can answer that question, you're in a much better position to operate and improve your application confidently.
Technical author and software engineer at DevByte. Writing deep-dive tutorials on distributed systems, modern full-stack web architectures, and cloud deployments.


