What the Architecture Covers
Metrics
Request rate, p95 and p99 latency, error rate, queue depth and job duration exposed for Prometheus.
Dashboards
Grafana dashboards per service, so the health of the API, workers, database and cache is clear at a glance.
SLO-based alerting
Alerts on user-facing symptoms such as error budgets and latency, routed to Slack or email, not on noise.
Structured logs
JSON logs with request IDs that tie an alert to the exact failing requests.
Health checks
Liveness and readiness checks that let the platform restart or drain unhealthy containers automatically.
Incident follow-up
Every incident ends with a fix and a new alert or test, so it does not happen twice.
This guide shows the code and configuration behind each piece of the overview, plus the failure modes the design is built to survive. The examples use FastAPI and the official Prometheus Python client, prometheus_client, but the same shape works for any HTTP service.
How the pieces fit
Each API container exposes a /metrics endpoint that Prometheus scrapes, writes JSON logs to stdout and answers two health endpoints. Prometheus stores the time series and evaluates alert rules. Alertmanager deduplicates firing alerts and routes them to Slack or email, and Grafana draws the dashboards. On AWS, container stdout lands in CloudWatch Logs, where the request ID connects a spike on a dashboard to the exact requests behind it, as described in the AWS deployment architecture blueprint. The load balancer and the orchestrator poll the health endpoints and act without waking anyone.
- 1A request arrives. Middleware takes
X-Request-IDfrom the caller or generates one, and stores it in a context variable. - 2The handler runs, and every log line it writes carries the request ID automatically.
- 3As the response leaves, the middleware records a counter increment and a latency observation, labelled by method, route template and status, and echoes
X-Request-IDback. - 4Prometheus scrapes
/metricsfrom every container on a fixed interval, such as every 15 seconds. - 5Alert rules evaluate the error ratio, p95 latency and error budget burn rate, and Alertmanager routes anything that fires.
- 6The engineer on call follows the alert to a dashboard, narrows down the route and time window, then reads the matching logs by request ID.
Metrics middleware
Every label value must come from a small, fixed set. Method, route template (/orders/{order_id}, not /orders/12345) and status code are bounded. Raw paths, user IDs and query strings are not, and each new value creates a new time series, so one crawler requesting random URLs can bloat Prometheus memory. Starlette stores the matched route in the request scope, so the template is available after the handler runs; unmatched paths collapse into a single unmatched value.
import logging
import time
import uuid
from fastapi import FastAPI, Request, Response
from prometheus_client import CONTENT_TYPE_LATEST, Counter, Histogram, generate_latest
from app.logs import request_id_var # defined in the logging section below
log = logging.getLogger("api.access")
REQUESTS = Counter("http_requests_total", "HTTP requests.", ["method", "route", "status"])
LATENCY = Histogram(
"http_request_duration_seconds", "HTTP request latency.", ["method", "route"],
buckets=(0.025, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0),
)
SKIP_ROUTES = {"/metrics", "/healthz", "/readyz"}
app = FastAPI()
@app.middleware("http")
async def observe_requests(request: Request, call_next):
incoming = request.headers.get("x-request-id", "")
request_id = incoming if 0 < len(incoming) <= 64 else uuid.uuid4().hex
token = request_id_var.set(request_id)
start = time.perf_counter()
status = 500 # stays 500 if the handler raises
try:
response = await call_next(request)
status = response.status_code
response.headers["X-Request-ID"] = request_id
return response
finally:
route = getattr(request.scope.get("route"), "path", "unmatched")
elapsed = time.perf_counter() - start
if route not in SKIP_ROUTES:
REQUESTS.labels(request.method, route, str(status)).inc()
LATENCY.labels(request.method, route).observe(elapsed)
log.info("request", extra={"route": route, "status": status,
"duration_ms": round(elapsed * 1000)})
request_id_var.reset(token)
@app.get("/metrics", include_in_schema=False)
def metrics() -> Response:
return Response(generate_latest(), media_type=CONTENT_TYPE_LATEST)Choose histogram buckets that bracket your latency target, because histogram_quantile interpolates inside a bucket. With several worker processes per container (Gunicorn with Uvicorn workers), each process keeps its own counters and a scrape sees only one of them: run one process per container, or enable the client's multiprocess mode with PROMETHEUS_MULTIPROC_DIR and a MultiProcessCollector.
Background workers expose their own metrics with start_http_server: job duration, failures, queue depth, and a Gauge set with set_to_current_time() after each successful run. That last one catches the scheduled job that silently stops, which a failure counter never will: alert on time() - job_last_success_timestamp_seconds > 7200. Call that label task, not job, because Prometheus already attaches job to every scraped series.
Alert rules
Alert on what users feel: errors and slowness. Each rule needs a for duration or a second window so one bad scrape never pages anyone.
groups:
- name: api-alerts
rules:
- alert: ApiHighErrorRatio
expr: |
sum by (job) (rate(http_requests_total{status=~"5.."}[5m]))
/ sum by (job) (rate(http_requests_total[5m])) > 0.05
for: 10m
labels:
severity: page
annotations:
summary: "5xx ratio is {{ $value | humanizePercentage }} on {{ $labels.job }}"
- alert: ApiSlowP95
expr: |
histogram_quantile(0.95,
sum by (job, route, le) (rate(http_request_duration_seconds_bucket[5m]))
) > 0.5
and on (job, route)
sum by (job, route) (rate(http_request_duration_seconds_count[5m])) > 0.1
for: 15m
labels:
severity: ticket
# SLO: 99.9% of requests succeed over 30 days, so the error budget is 0.1%.
- alert: ApiErrorBudgetFastBurn
expr: |
(
sum by (job) (rate(http_requests_total{status=~"5.."}[1h]))
/ sum by (job) (rate(http_requests_total[1h])) > (14.4 * 0.001)
)
and
(
sum by (job) (rate(http_requests_total{status=~"5.."}[5m]))
/ sum by (job) (rate(http_requests_total[5m])) > (14.4 * 0.001)
)
labels:
severity: pageThe p95 rule keeps le in the sum by clause, which histogram_quantile requires, and the and on (job, route) clause skips routes with under one request every ten seconds, where a single slow call would swing the percentile.
The burn-rate rule deserves a plain explanation. A 99.9 percent SLO leaves an error budget of 0.1 percent of requests over 30 days. Burn rate is how fast you spend that budget compared with the pace that would use it up exactly at the end of the window. A burn rate of 1 spends it in 30 days; 14.4 spends 2 percent of it in one hour, which is worth waking someone for. The 5-minute window confirms the problem is still happening, so the alert clears soon after the fix. A second pair (6x over 6 hours, confirmed over 30 minutes) catches slower leaks; the Google SRE Workbook chapter on alerting on SLOs has the full table. Rule files run through promtool check rules in the CI/CD pipeline, so a typo never silently disables an alert.
Structured logs with request IDs
import contextvars
import json
import logging
from datetime import datetime, timezone
request_id_var = contextvars.ContextVar("request_id", default="-")
EXTRA_FIELDS = ("route", "status", "duration_ms", "task")
class JsonFormatter(logging.Formatter):
def format(self, record: logging.LogRecord) -> str:
entry = {
"ts": datetime.fromtimestamp(record.created, timezone.utc).isoformat(),
"level": record.levelname,
"logger": record.name,
"msg": record.getMessage(),
"request_id": request_id_var.get(),
}
entry.update({k: getattr(record, k) for k in EXTRA_FIELDS if hasattr(record, k)})
if record.exc_info:
entry["exc"] = self.formatException(record.exc_info)
return json.dumps(entry, default=str)
def setup_logging(level: str = "INFO") -> None:
handler = logging.StreamHandler()
handler.setFormatter(JsonFormatter())
logging.basicConfig(level=level, handlers=[handler], force=True)Because the ID lives in a ContextVar, it follows the request through await calls without being passed around. Forward it as X-Request-ID on calls to other services, and put it in the payload of every job you enqueue so the worker can set the same variable. JSON encoding escapes newlines, so a user-supplied value cannot forge a log entry. Run Uvicorn with --no-access-log so each request is logged once.
Health and readiness
@app.get("/healthz", include_in_schema=False)
async def healthz() -> dict:
return {"status": "ok"} # the process is alive; no dependency checks here
@app.get("/readyz", include_in_schema=False)
async def readyz(response: Response) -> dict:
checks = {"database": await ping_database(), "cache": await ping_cache()}
if not all(checks.values()):
response.status_code = 503
return checksping_database and ping_cache are your own helpers that run SELECT 1 and a Redis PING with a short timeout. Liveness stays simple on purpose: if it checked the database, an outage would make the orchestrator restart every container in a loop. Readiness tells the load balancer to stop routing to a container that cannot serve.
Dashboards
Build one dashboard per service around the RED method: Rate, Errors and Duration.
# Rate: requests per second by route
sum by (route) (rate(http_requests_total[5m]))
# Errors: share of responses that are 5xx
sum(rate(http_requests_total{status=~"5.."}[5m])) / sum(rate(http_requests_total[5m]))
# Duration: p95 latency by route
histogram_quantile(0.95, sum by (route, le) (rate(http_request_duration_seconds_bucket[5m])))Below those, add rows for workers (queue depth, job duration, failures, time since last success), PostgreSQL (connections, slow queries) and the cache (hit ratio, memory). Mark deploys as annotations so a regression lines up with its release.
Failure modes and how the design handles them
- A dependency goes down: readiness drains traffic, liveness stays green so containers are not restarted in a loop, and the error alerts fire on the user-facing symptom.
- Cardinality explosion: route templates and an
unmatchedbucket stop scanners from creating new series. - A scheduled job stops running: the last-success alert fires even though no error was raised.
- A scrape target disappears: an
up == 0alert catches it, because rules over missing series return nothing. - Noisy alerts:
fordurations, a traffic floor and two-window burn rates keep pages rare. - Counters split across processes: one process per container, or multiprocess mode.
- The monitoring path breaks: an always-firing heartbeat alert feeds an external dead man's switch that notifies you when it stops.
- An incident repeats: every incident closes with a fix plus a new alert, test or panel.
Checklist
- Requests are measured with method, route template and status labels only.
- No label holds user IDs, raw paths or query strings.
- Histogram buckets bracket the latency target.
/metricsand health routes are excluded from request metrics.- One process per container, or multiprocess mode.
- Every log line is one JSON object with a request ID.
X-Request-IDis validated, echoed and forwarded to downstream calls and jobs.- Liveness checks the process; readiness checks dependencies.
- Alerts cover error ratio, p95 latency, budget burn, stale jobs and missing targets.
- Every page links to a dashboard and a runbook.
- Rule files pass
promtool check rulesin CI.
Tools & Stack
- Prometheus
- Grafana
- CloudWatch
- Structured logging
- FastAPI
- Docker
In Practice
Applied in the Mobileriz multi-marketplace backend: Prometheus monitoring watches the API, scheduled marketplace syncs and background jobs.
This blueprint is part of my Python backend & API development service. Tell me about your system on Upwork and I'll propose the right setup, timeline and cost.
Hire Me on Upwork


