Python monitoring in production: how to monitor Django, FastAPI and Celery from gunicorn workers to task queues
WSGI and ASGI servers, the worker model and the GIL, request latency, ORM N+1 queries and connection pools, blocking calls in the event loop, Celery queues and retries, memory growth, and OpenTelemetry instrumentation that works with pre-fork servers.
Summary
- Python monitoring starts with the process model: gunicorn or uvicorn workers, threads versus processes and the GIL decide how saturation shows up, so measure busy workers, request duration percentiles and worker restarts, not only CPU.
- Most production problems in Django and FastAPI apps sit in the database layer and in the event loop: N+1 queries, exhausted connection pools and blocking calls inside async code. Traces with database spans make all three visible.
- Celery needs its own signals: queue length per queue, task runtime, retries, failures and worker concurrency. OpenTelemetry instruments Django, FastAPI and Celery with little code, as long as you initialise it after the fork.
Python monitoring in production is less about the language and more about the moving parts around it: an application server that forks workers, an ORM that turns one line of code into fifty queries, an event loop that stalls when one coroutine blocks, and a Celery cluster that quietly builds up a backlog. A Django or FastAPI service can look healthy on a CPU graph while users wait seconds for a response, because every worker is busy waiting on the database.
This guide walks through what to measure in a typical Python stack: the WSGI and ASGI server, the worker model and the GIL, request latency and errors, the database layer with N+1 queries and connection pools, async pitfalls, Celery queues and workers, memory growth, and how to instrument it all with OpenTelemetry. It ends with a metrics table, example alerts and a checklist. If you run other runtimes as well, our guides on Java and JVM monitoring and PHP monitoring follow the same structure.
WSGI vs ASGI: gunicorn, uvicorn and what they mean for monitoring
Python web frameworks do not serve HTTP themselves in production. They hand that job to an application server, and the server's model determines which metrics matter.
- WSGI is the synchronous interface used by classic Django and Flask. One worker handles one request at a time (or one per thread). gunicorn is the most common WSGI server: a master process forks a fixed number of workers and restarts them when they die or hang.
- ASGI is the asynchronous interface used by FastAPI, Starlette and Django's async views. uvicorn runs an event loop per process, so a single worker can hold many concurrent requests, as long as none of them blocks the loop. In production, uvicorn is often run with several worker processes, either through its own
--workersoption or as a worker class under gunicorn (provided, depending on the version, by uvicorn itself or by the separateuvicorn-workerpackage).
gunicorn offers several worker classes: sync (one request per process), gthread (a thread pool per process), and green-thread classes such as gevent and eventlet. Each saturates differently. A sync worker is busy for the whole request, including every database round trip, so the number of workers is your hard concurrency limit. A gthread worker can overlap I/O but still shares one interpreter lock. An async worker can overlap thousands of waits but collapses if CPU-bound or blocking code runs on the loop.
Two gunicorn settings show up directly in monitoring data. timeout (30 seconds by default) is the time after which the master kills a silent worker and logs WORKER TIMEOUT; for sync workers this effectively caps request duration. max_requests and max_requests_jitter recycle workers after a number of requests, which is a common mitigation for memory growth. Both produce worker restarts, and you want those restarts counted and correlated with latency.
The worker model and the GIL
CPython's global interpreter lock (GIL) allows only one thread per process to execute Python bytecode at a time. I/O releases the lock, so threads help with waiting on the database or an HTTP API, but CPU-bound work in threads does not run in parallel. For monitoring this has practical consequences:
- Process CPU near 100 % of one core means a worker is saturated, even if the host shows plenty of idle CPU. Look at CPU per worker process, not only per host or container.
- Adding threads does not fix CPU-bound endpoints. If latency rises with load and per-process CPU is pegged, you need more processes, less work per request, or work moved to a task queue.
- Latency that grows with concurrency while CPU stays low usually points to waiting: database, connection pool, external HTTP calls or lock contention.
Python 3.13 introduced an experimental free-threaded build (PEP 703) that can run without the GIL. It is a separate build, its support status evolves from release to release, and C extensions must explicitly support it. Treat it as something to evaluate, not as a default for production web workers, and check your dependencies before relying on it.
The key server-level metric is worker utilisation: how many workers or threads are busy, compared with how many exist. When all sync workers are busy, new connections wait in the listen backlog, and that wait time does not appear in your framework's request timing. Measuring request duration at the load balancer or ingress as well as inside the app shows the difference. This is classic saturation, and it appears before errors do.
Request latency, throughput and errors
For each service, track the RED signals: rate, errors and duration. With OpenTelemetry's HTTP semantic conventions, the server-side duration is the histogram http.server.request.duration (in seconds), with attributes such as http.request.method, http.route and http.response.status_code.
- Use the route template, not the raw URL.
/orders/{order_id}rather than/orders/48213, otherwise metric cardinality explodes. The Django and FastAPI instrumentations take the route from the resolver. - Watch percentiles, not averages. p95 and p99 show the requests that hit a cold cache, a slow query or a busy worker. See our glossary entry on tail latency.
- Separate 4xx from 5xx. A rise in 5xx is an incident. A rise in 4xx can be a broken client release or a scanner.
- Capture exceptions with stack traces. Unhandled exceptions in Django views and FastAPI endpoints are recorded as span events by the instrumentation, so an error rate alert can link straight to the failing trace.
Track the latency split as well: how much of a request was spent in Python, in the database, and in outbound HTTP calls. A distributed trace answers this per request; aggregated span durations answer it per endpoint.
Database layer: ORM N+1 queries and connection pools
In most Django and SQLAlchemy applications, the database is where the time goes. Two patterns cause a large share of production slowdowns.
N+1 queries. A list view loads 50 orders, then accesses order.customer in a template or serializer loop. The ORM lazily runs one extra query per row, so the request issues 51 queries instead of one or two. Each query is fast, which is why slow query logs often miss the pattern. In a trace it is obvious: a long ladder of nearly identical SELECT spans. The fix in Django is select_related for foreign keys and prefetch_related for many-to-many and reverse relations; in SQLAlchemy it is eager loading such as selectinload or joinedload. Our glossary explains the N+1 query problem in more detail.
# Django: N+1 (one query per order for the customer)
orders = Order.objects.filter(status="open")[:50]
names = [o.customer.name for o in orders]
# Fixed: one query with a JOIN
orders = Order.objects.select_related("customer").filter(status="open")[:50]
A useful metric is queries per request, per route. If a route usually runs 4 queries and a release raises that to 60, you have found the regression before users complain. Derive it from database spans per trace, or count queries in middleware and attach the count as a span attribute.
Connection pools. Every worker process needs database connections, and the totals add up quickly: 8 gunicorn workers times 4 threads times 3 pods is already 96 potential connections (example values). Watch both sides:
- Client side. SQLAlchemy's
QueuePoolhaspool_size,max_overflowandpool_timeout; when the pool is exhausted, requests wait and finally raise a timeout error. Measure checked-out connections and wait time. Django traditionally uses one connection per thread, kept open across requests withCONN_MAX_AGE; recent Django versions (5.1 and later) also offer a built-in pool for PostgreSQL with psycopg 3 via thepooloption. - Server side. Compare active connections against the database limit (for PostgreSQL,
max_connections). If you use PgBouncer, monitor its pools and waiting clients too.
Pool exhaustion looks like slow requests with little database time: the request waits for a connection, not for the query. Our connection pool glossary entry covers sizing, and the guide to database monitoring and slow queries covers the server side.
Async pitfalls: blocking calls in the event loop
FastAPI and async Django give high concurrency per process, but only if every awaited operation is really asynchronous. One blocking call inside an async def stops the whole event loop, and every other request in that worker waits.
Typical offenders:
- A synchronous HTTP client such as
requestsinside an async endpoint, instead of an async client time.sleep()instead ofawait asyncio.sleep()- A synchronous database driver or ORM call inside
async def - CPU-heavy work such as large JSON serialisation, image processing or encryption on the loop
- Synchronous file I/O on large files
FastAPI runs endpoints declared with plain def in a thread pool, so blocking code is safer there than inside async def. That thread pool has a limit, though, and once it is exhausted, sync endpoints queue up. If you must call blocking code from async code, offload it explicitly, for example with run_in_threadpool or asyncio.to_thread.
How to detect loop blocking in production:
- Event loop lag. Schedule a small task at a fixed interval and measure how late it runs. A lag that grows under load means something blocks the loop.
- asyncio debug mode (
PYTHONASYNCIODEBUG=1) logs callbacks that take longer thanloop.slow_callback_duration(100 ms by default). It adds overhead, so use it in staging or briefly in production. - Traces. When a request's span is long but contains no child spans for the time in question, the worker was busy with something uninstrumented, often a blocking call. Continuous profiling shows which function held the CPU.
# Blocks the event loop for every request in this worker
@app.get("/report")
async def report():
data = requests.get("https://api.example.com/data", timeout=5).json()
return data
# Non-blocking
@app.get("/report")
async def report():
async with httpx.AsyncClient(timeout=5) as client:
r = await client.get("https://api.example.com/data")
return r.json()
Celery monitoring: queues, tasks, retries and workers
Celery moves slow work out of the request path, which also moves it out of your HTTP dashboards. A failing Celery cluster often goes unnoticed until someone asks why emails were not sent. Celery monitoring needs four groups of signals.
Queue length. The number of messages waiting per queue is the most important Celery metric. A growing queue depth means producers outpace workers. How you read it depends on the broker: with Redis, each queue is a list (by default named celery) whose length you get with LLEN; with RabbitMQ, the management API and the Prometheus plugin expose ready and unacknowledged messages per queue. Also track the age of the oldest message where possible, because a short queue with an old head is worse than a long queue that drains quickly.
Task runtime and outcomes. Measure, per task name: duration, success, failure, retry and revoked counts. Celery signals such as task_prerun, task_postrun, task_failure and task_retry are the hooks most exporters and the OpenTelemetry instrumentation use. A task that suddenly retries a lot often indicates a downstream outage, and with exponential backoff the backlog builds silently.
Worker health and concurrency. The default prefork pool runs a number of child processes per worker, set with --concurrency. Track active tasks against concurrency (utilisation), workers online, and child restarts. celery -A proj inspect active and inspect reserved show what workers are doing right now; for continuous metrics, enable task events (-E or worker_send_task_events) and consume them with an exporter or a tool such as Flower.
Delivery semantics. A few settings decide what happens when things go wrong, and they explain many confusing graphs:
worker_prefetch_multiplier(default 4) lets each process reserve several messages. Long tasks plus a high prefetch can leave messages stuck on one busy worker while others are idle.task_acks_lateacknowledges after the task finishes, so a crashed worker's task is redelivered. That requires idempotent tasks.- With the Redis broker, unacknowledged messages are redelivered after the
visibility_timeout. Tasks that run longer than that can execute twice. worker_max_tasks_per_childandworker_max_memory_per_childrecycle child processes, the Celery counterpart to gunicorn'smax_requests.
Finally, watch the broker itself. If Redis is the broker, its memory, evictions and connected clients matter: an eviction policy other than noeviction on a broker instance can silently delete queued tasks. Our Kafka monitoring guide covers the same backlog logic for event streams, and queue monitoring in Obseria tracks it across brokers.
Memory: RSS growth, leaks and worker recycling
Long-running Python processes often grow in memory over time. Not all of that growth is a leak: CPython's allocator keeps freed memory in arenas for reuse, and fragmentation can prevent it from returning memory to the operating system. Still, a steady climb in resident set size (RSS) across hours, followed by an OOM kill or a container restart, is a common production pattern.
- Measure RSS per worker process, plus container memory against its limit. A sawtooth (growth, then a drop at each recycle) is normal with
max_requests. A staircase that never drops is not. - Correlate with traffic and releases. Growth that tracks request count points to per-request accumulation such as module-level caches, unbounded
lru_cacheor global lists. Growth that starts with a release points to new code. - Find the source with
tracemallocsnapshots compared over time, or with a memory profiler in staging. Watch out for objects kept alive by references in closures, signal handlers or logging handlers. - Mitigate with gunicorn's
max_requestsandmax_requests_jitter(jitter prevents all workers from restarting at once) and Celery'sworker_max_tasks_per_child. Treat this as a safety net, not a fix.
OpenTelemetry for Python: Django, FastAPI and Celery
OpenTelemetry's Python distribution supports zero-code instrumentation: a launcher wraps your process and patches supported libraries at startup. The basic setup:
pip install opentelemetry-distro opentelemetry-exporter-otlp
opentelemetry-bootstrap -a install # installs instrumentations for detected libraries
export OTEL_SERVICE_NAME=orders-api
export OTEL_EXPORTER_OTLP_ENDPOINT=http://otel-collector:4317
export OTEL_TRACES_EXPORTER=otlp
export OTEL_METRICS_EXPORTER=otlp
export OTEL_LOGS_EXPORTER=otlp
export OTEL_PYTHON_LOGGING_AUTO_INSTRUMENTATION_ENABLED=true
opentelemetry-instrument gunicorn myproject.wsgi:application
opentelemetry-bootstrap looks at the installed packages and installs matching instrumentation libraries, such as opentelemetry-instrumentation-django, -fastapi, -celery, -sqlalchemy, -psycopg2, -redis and -requests. Review the list rather than accepting it blindly, and pin versions together with the rest of your dependencies. Our glossary entry on zero-code instrumentation explains the approach.
A few details matter in practice:
- Pre-fork servers. gunicorn forks workers after the master has loaded, and the background threads of the batch span processor and metric reader do not survive a fork. The OpenTelemetry documentation recommends initialising the SDK in gunicorn's
post_forkhook when you use pre-fork workers. uvicorn's own multi-worker mode and--reloadhave similar limitations with auto-instrumentation; check the current docs for your version. - Django. The instrumentation needs
DJANGO_SETTINGS_MODULEto be set. It names spans by route and records exceptions. - FastAPI. Spans are named by route template. For manual setup,
FastAPIInstrumentor.instrument_app(app)does the same as the launcher. - Celery. Initialise instrumentation in each worker process, typically in the
worker_process_initsignal, so that prefork children export correctly. The instrumentation propagates trace context through task headers, so a task span links back to the HTTP request that enqueued it. - Logs. With logging instrumentation enabled, standard
loggingrecords carry trace and span IDs, which lets you jump from a log line to the trace.
Send everything to an OpenTelemetry Collector rather than directly to a backend, so that you can sample, filter and enrich centrally. The Python integration page lists the setup for Obseria.
Key Python metrics at a glance
| Area | Metric | What it tells you |
|---|---|---|
| HTTP | http.server.request.duration p50, p95, p99 per route | User-facing latency and tail latency |
| HTTP | Request rate and 5xx rate per route | Load and error rate |
| Server | Busy workers or threads versus total | Saturation of gunicorn or uvicorn |
| Server | Worker restarts and WORKER TIMEOUT log events | Hung or crashing workers |
| Process | CPU per worker process | CPU-bound workers limited by the GIL |
| Process | RSS per worker, container memory versus limit | Memory growth, OOM risk |
| Async | Event loop lag | Blocking calls on the loop |
| Database | Queries per request, query duration | N+1 patterns, slow queries |
| Database | Pool checked out, pool wait time, pool timeouts | Connection pool exhaustion |
| Celery | Queue length and oldest message age per queue | Backlog and processing delay |
| Celery | Task duration, failures, retries per task name | Broken or slow tasks, downstream issues |
| Celery | Active tasks versus concurrency, workers online | Worker capacity |
| Broker | Redis memory and evictions or RabbitMQ unacked messages | Broker health |
Example alerts for Python services
The thresholds below are example values. Calibrate them against your own baseline and your service level objectives before you page anyone.
- Latency SLO burn (example). p95 of
http.server.request.durationabove 800 ms for 10 minutes on a critical route, or better, an SLO burn-rate alert on the share of slow requests. - Error rate (example). 5xx share above 2 % for 5 minutes, per service.
- Worker saturation (example). More than 90 % of workers busy for 10 minutes, or any
WORKER TIMEOUTburst. - Pool exhaustion (example). Any pool timeout errors in 5 minutes, or pool wait time p95 above 100 ms.
- N+1 regression (example). Median queries per request on a route more than three times its 7-day baseline after a deployment.
- Celery backlog (example). Oldest message in a queue older than 5 minutes, or queue length growing for 15 minutes straight.
- Celery failures (example). Failure rate of a task above 5 % for 10 minutes, or retries more than twice the usual rate.
- Memory (example). Container memory above 90 % of the limit for 15 minutes, or RSS per worker rising for 6 hours without a drop.
Keep pages for symptoms users feel and send causes to tickets or dashboards. Our article on reducing alert fatigue explains how.
Common questions about Python monitoring
What should I monitor first in a Python application?
Request rate, error rate and latency percentiles per route, then worker saturation and database time. For Celery, queue length and task failures. Those cover most incidents.
How do I monitor Celery tasks?
Instrument the workers with OpenTelemetry or an exporter that consumes Celery events, read queue length from the broker, and alert on backlog age, failure rate and retries per task name.
Does OpenTelemetry slow down my Django or FastAPI app?
Instrumentation adds some overhead per span. For typical web workloads it is small compared with database and network time, but measure it in your own environment, and use sampling for high-volume services.
Why does my FastAPI app get slow under load although CPU is low?
Usually because something blocks the event loop or the thread pool is exhausted. Measure event loop lag and look for long spans without children.
Python monitoring checklist
Copy this checklist into your team backlog
- Server model documented: gunicorn worker class, number of workers and threads, uvicorn workers
- Request rate, 5xx rate and duration percentiles per route template, not per raw URL
- Busy workers versus total, worker restarts and
WORKER TIMEOUTevents tracked - CPU and RSS per worker process, container memory against the limit
- Database spans in every trace, queries per request tracked per route
- N+1 checks in code review and a baseline alert on queries per request
- Connection pool usage, wait time and timeouts measured on client and database side
- Event loop lag measured for async services; no blocking clients in
async def - Celery queue length and oldest message age per queue, from the broker
- Celery task duration, failures and retries per task name; workers online and utilisation
- Idempotent tasks where
task_acks_lateis used;visibility_timeoutabove the longest task runtime with Redis - Broker instance with
noevictionif Redis is the Celery broker max_requestswith jitter andworker_max_tasks_per_childas memory safety nets- OpenTelemetry initialised after fork (gunicorn
post_fork, Celeryworker_process_init) - Logs correlated with trace IDs; alerts labelled with example thresholds tuned to your baseline
How Obseria helps with Python monitoring
Obseria is an OpenTelemetry-native observability platform, so the Python, Django, FastAPI and Celery instrumentation described above sends data to Obseria without proprietary agents. Traces, metrics and logs of the same request arrive together: you can open a slow FastAPI endpoint, see the N+1 ladder of database spans, follow the Celery task it enqueued, and read the log lines that belong to it.
- Obseria Intelligence correlates latency spikes with deployments, database load and queue backlogs, and shows the evidence behind each suspected root cause.
- Continuous profiling shows which Python functions held the CPU or blocked the event loop.
- Obseria Pipeline samples high-volume traces and masks personal data before storage in the EU.
Start with the Python integration, or book a demo to see your own services in Obseria.