Skip to content

Troubleshooting guide

How to find slow database queries

Most slow endpoints are slow because of the database. Traces tell you which queries matter for which requests; the database tells you why they are slow.

3 min read10 sectionsUpdated

On this page

Key points

  • Start from the slow request, not from the database: traces show which queries users wait on.
  • Look for repetition: many identical queries in one request is an N+1 problem.
  • Confirm with EXPLAIN and fix with indexes, batching or less data.
  • Re-measure p95 for the route after the fix.

Step 1: Find slow requests and open their traces

In APM, sort endpoints by p95 latency or by total time (requests × average duration). Open a slow trace and look at the database spans:

  • One long span: a slow statement. Note its normalized SQL.
  • Many short spans in a row: an N+1 pattern. 40 queries × 30 ms = 1.2 s.
  • Long gaps between spans: time in your own code, or a connection pool wait.

The N+1 pattern

Fetching a list, then running one query per item, is the most common performance bug in web apps that use an ORM.

djangopython
# N+1: one query for orders, then one per order for its customer
orders = Order.objects.filter(status="open")[:50]
for o in orders:
    print(o.customer.name)          # a query each time

# Fixed: one join (or one extra IN query)
orders = Order.objects.filter(status="open").select_related("customer")[:50]
sql
-- What the fix sends instead of 50 separate lookups
SELECT * FROM customers WHERE id IN (12, 15, 18, 22 /* ... */);

Step 2: Ask the database

For PostgreSQL, pg_stat_statements ranks statements by total time across all calls:

sql
-- needs the pg_stat_statements extension
SELECT calls,
       round(total_exec_time::numeric, 0) AS total_ms,
       round(mean_exec_time::numeric, 1)  AS mean_ms,
       left(query, 120)                   AS query
FROM pg_stat_statements
ORDER BY total_exec_time DESC
LIMIT 15;

-- Then look at the plan for one of them
EXPLAIN (ANALYZE, BUFFERS)
SELECT * FROM order_items WHERE order_id = 8812;

Step 3: Read the plan

You seeIt meansTry
Seq Scan on a large tableNo usable indexAn index on the filtered or joined columns
Rows estimated 10, actual 100,000Stale statisticsANALYZE the table
Sort with external mergeNot enough work_mem, or sorting too muchAn index matching ORDER BY; fetch fewer rows
Nested Loop with many rowsJoin strategy strugglingIndexes on join keys; check estimates

Step 4: Fix and verify

  • Add the index that the plan needs, ideally concurrently in production (CREATE INDEX CONCURRENTLY in PostgreSQL).
  • Batch N+1 queries with joins or IN lists.
  • Select fewer columns and rows: paginate, avoid SELECT * on wide tables.
  • Cache results that change rarely.

Then compare the route's p95 and its database time per request before and after. In VitalRix APM, the database view shows call volume, p95 and slow calls over time, so you can confirm both the latency drop and the reduction in query count.

Frequently asked questions

Should I enable the slow query log?

Yes, with a threshold such as 500 ms. It catches individually slow statements. It will not catch N+1 problems, where each query is fast but there are many, which is why traces matter.

Are ORMs the problem?

Not inherently. ORMs make N+1 easy to write by accident. Eager-loading options (select_related, includes, Include, joinedload) fix most cases.

Check it now, free

  • MongoDB monitoring: metrics that matter: Monitor MongoDB: operation rates and latency, slow queries from the profiler, WiredTiger cache, connections, replication lag and oplog window.
  • MongoDB slow queries: how to find and fix them: Find and fix slow MongoDB queries: use the profiler and explain, spot COLLSCAN and in-memory sorts, and follow the ESR rule when designing compound indexes.
  • MySQL monitoring: key metrics and alerts: Monitor MySQL: connections and threads, query throughput, slow queries, InnoDB buffer pool, replication lag and disk, with the SQL for each check.
  • PostgreSQL high CPU usage: how to find the cause: Diagnose PostgreSQL high CPU: use pg_stat_statements to rank queries by total time, spot missing indexes and stale statistics, and read EXPLAIN properly.
  • How to monitor Supabase: How to monitor a Supabase backend: Postgres health and slow queries, auth and REST API availability, edge function errors, connection limits and alerts.
  • OpenTelemetry for Django: Trace a Django app with OpenTelemetry: auto-instrument views and the ORM, run under gunicorn safely, trace Celery tasks and export to VitalRix.

Watch your own site and services with VitalRix

Uptime checks, APM, logs, real-user monitoring, alerts and status pages in one place. Every product has a free tier and no credit card is needed.