The 30 second answer
I open distributed traces from an APM or OpenTelemetry for the slow requests and look at the spans. Each span shows where time went: the database, our own code, a downstream HTTP call, or waiting for a connection. That tells me which layer to fix first, instead of guessing. I focus on the longest span on the critical path, because shortening anything else barely changes total latency.
A distributed trace is a tree of spans. Each span times one step (HTTP handler, SQL query, outbound call), so you can see whether time goes to the database, your code, or another service. The OpenTelemetry Java agent instruments JDBC, Spring and HTTP clients with no code changes.
trace 7f3a... p99 request 820ms
span gateway 8ms
span app 12ms
span GET /payments 610ms # the slow hop
span SQL orders.find 40msAlternate interview scenarios
"One slow method contains a database call and a downstream HTTP call. Which is responsible?"
For an illustrative sequential 900 ms request, 180 ms acquiring a DB connection, 20 ms executing SQL, 650 ms in HTTP and 50 ms elsewhere points primarily to downstream waiting, with a separate pool-pressure issue. Check the HTTP server's own spans, connect/read timeouts, connection-pool waiting and retries before rewriting SQL. If SQL execution dominates instead, inspect query count, plan, rows and locks; a short individual query repeated hundreds of times suggests N+1. If acquiring a connection dominates while SQL is fast, inspect pool active/pending metrics and transaction duration rather than only adding an index. In particular, a transaction that holds its DB connection while waiting for HTTP can starve unrelated requests; move remote work outside the transaction where business atomicity permits, or redesign the workflow rather than silently weakening consistency.
Do not add parent duration to all its children: spans nest, and parallel DB/HTTP branches overlap. Optimize the longest necessary critical path. A large unexplained gap between known child spans calls for targeted custom spans and, when CPU is implicated, a profile; it does not prove that the database is slow. Apply one evidence-backed change, then compare latency percentiles, effective throughput and errors under the same load, keeping thread/connection counts and downstream saturation visible.
Sources (3)
- OpenTelemetry: Tracesopentelemetry.io
- OpenTelemetry Java agentopentelemetry.io
- Spring transaction propagation: Bound resources and connection-pool pressuredocs.spring.io