Prompt
I need a way to see which database query slowed down a request
Latest observation
Yes — the usual way is to add query timing / tracing around your DB layer so each request logs the SQL statements and their durations, then correlate those logs with the slow request.
A practical approach:
1) Log every query with duration
Wrap your database calls so you record:
- SQL statement
- bind parameters
- start/end time
- total duration
- request id / trace id
Example log line:
request_id=abc123 db_query=245ms sql="SELECT ... WHERE id = ?"
Then when a request is slow, you can see which query took the longest.
2) Add request correlation
Generate or propagate a request_id per incoming request and include it in:
- app logs
- DB query logs
- tracing spans
This makes it much easier to link one slow request to the exact queries it executed.
3) Use APM / distributed tracing if possible
Tools like:
- OpenTelemetry
- Datadog APM
- New Relic
- Elastic APM
- Skylight
- Honeycomb
can automatically create spans for:
- request handling
- DB queries
- external HTTP calls
Then you can inspect a single request trace and immediately see the slow DB span.
4) Enable database-level slow query logging
Most databases support this:
- PostgreSQL:
log_min_duration_statement - MySQL: slow query log
- SQL Server: Extended Events / Query Store
- MongoDB: profiler / slow query log
This helps identify slow queries overall, though it may not directly tie them to a specific request unless you also log request context in the app.
5) Sample/trace only slow requests
If full query logging is too noisy, only turn on detailed query logging when:
- request latency exceeds a threshold
- an error occurs
- a specific route is flagged
This keeps logs manageable.
If you want, I can show you:
- how to do this in a specific language/framework, or
- how to set up request-scoped SQL logging with OpenTelemetry.