Performance Troubleshooting & Incident Response Questions
Diagnosing and resolving performance problems in production, often under time pressure. Covers latency and slowdown investigation, reproducing and narrowing performance regressions, reading live diagnostic evidence (logs, thread dumps, resource and network captures), runbooks and automated remediation for recurring incidents, restoring healthy behavior while preserving reliability, and communicating status and escalation decisions mid-incident. Emphasizes systematic debugging of live systems over offline experimentation.
A customer-facing API's read latency keeps increasing as the underlying database grows, even though the right indexes exist. Lay out a systematic approach to determine whether the cause is index inefficiency, full table scans, cache eviction, or storage throughput, and describe what evidence you would gather at each layer to confirm which one it actually is.
Sample Answer
Direct answer: Having "the right indexes" only guarantees the query planner picks a good access path, not that reading through that index stays cheap as data grows. The actual cause is one of index bloat, the planner drifting away from the index, the working set no longer fitting in cache, or a physical storage throughput ceiling, and each has its own distinct evidence.
Structured elaboration, evidence at each layer:
- Index inefficiency or bloat: many databases (Postgres, for example) accumulate dead space in a b-tree index if maintenance (vacuum) can't keep up, growing the index's physical size and lookup cost disproportionately to row count. Check the index's actual size over time against row-count growth.
- Full table scans: run
EXPLAIN ANALYZE(a command that shows the actual query plan the database chose, along with real measured row counts and timing for each step, not just an estimate) on the slow query. If it shows a sequential scan instead of the expected index scan, check whether table statistics are stale, since a planner working from outdated row-count or selectivity estimates can silently switch away from the index it used to pick. - Cache eviction: check the database's buffer cache hit ratio (the fraction of reads served from memory rather than disk) over time with the same query pattern. A declining hit ratio as the table grows, with nothing else changing, means the working set no longer fits in the cache it used to fit in.
- Storage throughput: check IOPS (I/O operations per second) and throughput utilization plus latency at the storage-volume level. If utilization is pinned near the provisioned ceiling as data grows, that's a physical limit, unrelated to the query plan at all.
Worked example: A table grows from 5 million to 50 million rows over six months. The buffer cache hit ratio drops from 98% to 82% over the same period, with the query's WHERE-clause pattern unchanged. EXPLAIN ANALYZE still shows an index scan being used, ruling out a planner regression to a full scan, but its Buffers output (which reports actual hit versus read counts for that execution) shows a much higher proportion of disk reads relative to cache hits than before. Index size has grown roughly in line with row count, not disproportionately, ruling out bloat. Storage IOPS utilization sits around 40% of provisioned capacity, well below its ceiling. The conclusion: cache eviction is the actual cause, the working set no longer fits in the buffer cache as the table grew, forcing more physical reads per query even though the index itself is correctly chosen and structurally healthy. The fix is increasing the buffer cache size, partitioning or archiving old, rarely queried rows out of the hot table to shrink the effective working set, or adding a dedicated caching layer in front of the hottest lookups.
Trade-offs and pitfalls: assuming "the index exists, so it must be fast" ignores that even a correctly used index still costs a real disk read if its relevant pages aren't cached. Rebuilding indexes as a reflexive bloat fix, when the real cause is cache eviction, wastes a maintenance window for no benefit. Seeing acceptable IOPS utilization doesn't rule out storage as a problem either, since a device can have headroom on throughput but still show elevated per-request latency under a bursty access pattern, so check latency, not just utilization.
A search service is showing high tail latency under load. Walk through how you would figure out what's actually causing it and what you would change to bring it back down, and how you would prove your fix actually worked.
Sample Answer
When tail latency is high specifically under load, the goal is to find which resource is actually saturating (saturation meaning work is queuing up waiting to be served, not just busy) before touching any code, and then to validate the fix at the same load level that broke it.
Diagnose
- Compare p50 (median) against p99 (99th percentile) latency as load increases. If p50 stays flat while p99 balloons only past a certain QPS (queries per second), that's a saturation or queueing signature, not a uniform slowdown affecting every request equally.
- Apply the USE method systematically per resource: check Utilization (how busy), Saturation (how much work is queued beyond capacity), and Errors for each candidate resource, CPU, thread pool, connection pool (a shared, size-limited set of pre-opened connections to a downstream system that requests borrow and return instead of opening a new one each time), downstream call, disk IO, so you're sweeping possibilities instead of guessing.
- Check whether the slow requests share a shape: large result sets, cold cache lookups, or cross-shard fan-out calls (where one request touches many backend shards and waits on all of them) are common tail-latency culprits that don't show up in average-case metrics.
- Trace the slowest 1% of requests directly rather than reading aggregate dashboards, since an average hides which single stage of the request pipeline is actually slow.
Fix
- Mitigate immediately if customers are affected: shed excess load, add timeouts and circuit breakers (safeguards that stop sending requests to a struggling dependency once its failure rate crosses a threshold, giving it a chance to recover) to cap the worst case, or scale out horizontally if the bottleneck is genuinely per-node capacity.
- Fix the root cause once found: commonly this is an undersized thread or connection pool causing queueing past a load threshold, one slow shard dragging down every fan-out request that touches it, GC (garbage collection) pauses under memory pressure, or a lock serializing a hot path.
Proving the fix worked
- Reproduce the same load pattern (not just lighter production traffic) that originally triggered the regression, ideally in a load test, before and after the change.
- Confirm p99 (and ideally p99.9) returns to baseline at that SAME load level, since tail problems can hide entirely at low load and reappear the moment traffic climbs again.
- Watch it survive a full production traffic cycle including peak, and add an alert on the specific percentile that regressed so a recurrence pages automatically instead of waiting for another complaint.
Worked example: p50 stays flat at 40ms from 100 QPS up to about 1500 QPS while p99 rises from 90ms to 900ms across that same range; past roughly 1650 QPS p50 starts climbing too and the load test stops reaching a steady state at all. Tracing the slowest requests shows they all wait on a connection pool to a downstream ranking service capped at 50 connections. Size that pool analytically instead of reading a number off the graph. With a 30ms average call time each connection completes 1 / 0.030 = 33.3 calls per second, so 50 connections have a hard throughput ceiling of 50 / 0.030 = about 1670 QPS, while the concurrency actually demanded is Little's law: 1500 x 0.030 = 45 connections at 1500 QPS, and 60 at 2000 QPS. That one ceiling explains both breakpoints and why they are different breakpoints. At 1500 QPS the pool is at 45 of 50, about 90% utilized, which is far enough up the queueing curve to wreck p99 while the median request still finds a free connection immediately, and that is exactly the divergence between median and tail the diagnosis started from. At 2000 QPS demand exceeds the 1670 QPS ceiling outright, so the wait queue grows without bound, every request waits including the median, and no percentile is stable, which is why a tail-only story stops being the right description above the ceiling. Raising the pool to 150 lifts the ceiling to about 5000 QPS, putting 2000 QPS at 40% utilization with real room for the tail, and adding a 200ms client timeout with one retry to a second replica brings p99 back under 120ms at 2000 QPS in a repeat load test.
Trade-offs: raising a pool size blindly can just relocate the bottleneck downstream, if the ranking service itself is near its own capacity, sending it more concurrent connections saturates it instead. Hedged requests (sending a duplicate request to a second replica when the first is slow) fix tail latency but add real load to the downstream system, so cap how often they fire.
A production API's 95th percentile latency increased from 300ms to 1.2s after a recent feature rollout. The team suspects an N+1 database query regression. Describe how you would detect and verify the N+1 problem in production, propose a fix, estimate the complexity of the fix, and describe how you would test the fix before deploying to production.
Sample Answer
Direct answer: Detect an N+1 problem (a code pattern that issues one extra database query per row of an initial result set, instead of one batched query) by counting queries per request, either from an APM (application performance monitoring: a tool that traces where time goes inside a single request) trace showing many near-identical child spans under one request, or from a query-logging middleware; verify by correlating the query count with the size of the result set, since a true N+1 scales linearly with rows returned. The fix is to batch the follow-up lookups into a single query.
Structured elaboration:
- Detect: turn on query logging or APM tracing for the slow endpoint and look at one representative request. If you see the same query shape repeated dozens or hundreds of times in a single request trace, each differing only by an ID, that is the signature of an N+1.
- Verify: confirm the query count scales with the size of the collection being iterated (10 orders means roughly 10 extra queries, 500 orders means roughly 500), which rules out coincidence and confirms causation rather than just correlation.
- Fix: replace the per-row lookup with either an eager-load/join at the ORM level, or an explicit batched query (
WHERE id IN (...)) that fetches every needed row in one round trip. - Complexity estimate: the code change itself is usually small (a few lines swapping a loop-of-lookups for one batched call), so the engineering effort is low; the risk is behavioral, not size, since a batched IN-clause has to handle duplicate keys, missing keys, and very large ID lists (which may need chunking) correctly.
- Testing before deploy: unit-test that the batched fetch returns identical results to the old per-row approach for the same input, add a regression test asserting the query count stays flat (or grows sub-linearly) as the input size grows, and load-test the endpoint at production-like data volumes before shipping, since N+1 problems often only show up once table sizes exceed what a small staging dataset exercises.
Worked example (runnable):
query_count = 0
# Toy in-memory "database": 500 orders, each pointing at one of 50 customers.
orders = [{"id": i, "customer_id": i % 50} for i in range(500)]
customers_table = {cid: f"customer_{cid}" for cid in range(50)}
def get_customer(customer_id):
# Simulates one round trip to the DB for a single customer row.
global query_count
query_count += 1
return customers_table[customer_id]
def get_customers_batch(customer_ids):
# Simulates one round trip that fetches many customer rows at once
# (SELECT * FROM customers WHERE id IN (...)).
global query_count
query_count += 1
return {cid: customers_table[cid] for cid in customer_ids}
# Both versions start from the same single "SELECT * FROM orders". Count it in
# BOTH, otherwise the comparison is not like for like: the "+1" in "N+1" IS
# this query, and counting it in one column and not the other flatters the fix.
ORDERS_QUERY = 1
# Naive (N+1) version
query_count = 0
result_n1 = []
for order in orders:
customer_name = get_customer(order["customer_id"]) # one query per order
result_n1.append((order["id"], customer_name))
total_n1_queries = ORDERS_QUERY + query_count
print(f"N+1 version: {len(orders)} orders -> {ORDERS_QUERY} + {query_count} = {total_n1_queries} queries")
# Fixed (batched) version
query_count = 0
customer_ids = {o["customer_id"] for o in orders}
customer_map = get_customers_batch(customer_ids) # one query for all needed customers
result_fixed = [(o["id"], customer_map[o["customer_id"]]) for o in orders]
total_fixed_queries = ORDERS_QUERY + query_count
print(f"Fixed version: {len(orders)} orders, {len(customer_ids)} distinct customers -> {ORDERS_QUERY} + {query_count} = {total_fixed_queries} queries")
assert result_n1 == result_fixed
print("Results identical:", result_n1 == result_fixed)
# The claim is that one scales with the collection and the other does not.
# Demonstrate it at several sizes instead of asserting it in prose.
for n_orders in (10, 100, 1000):
sample = [{"id": i, "customer_id": i % 50} for i in range(n_orders)]
query_count = 0
for o in sample:
get_customer(o["customer_id"])
n1 = ORDERS_QUERY + query_count
query_count = 0
get_customers_batch({o["customer_id"] for o in sample})
fixed = ORDERS_QUERY + query_count
print(f" {n_orders:>4} orders -> N+1: {n1:>4} queries, batched: {fixed} queries")
Output:
N+1 version: 500 orders -> 1 + 500 = 501 queries
Fixed version: 500 orders, 50 distinct customers -> 1 + 1 = 2 queries
Results identical: True
10 orders -> N+1: 11 queries, batched: 2 queries
100 orders -> N+1: 101 queries, batched: 2 queries
1000 orders -> N+1: 1001 queries, batched: 2 queries
The naive version issues 1 + 500 = 501 queries (the one that fetches the orders, plus one per order, which is literally what the name "N+1" describes); the batched version issues 1 + 1 = 2 (one for the orders, one IN-clause fetch for the 50 distinct customers needed), while producing the identical output. The sweep is the part that matters as evidence: the naive count tracks the collection size exactly (11, 101, 1001) while the batched count stays at 2 regardless, and note that the batched count does not grow with the number of DISTINCT customers either, only the size of the IN list does. That constant-versus-linear shape, not the single 501-versus-2 figure, is what you assert in the regression test.
Trade-offs and pitfalls: a batched IN-clause can hit a parameter-count limit on very large ID lists, so real fixes usually chunk the batch (for example 500 IDs per query) rather than assuming unlimited batch size. Also verify the fix doesn't just move the N+1 one layer up: if the batched customer fetch itself triggers a further per-row lookup (for example customer addresses), you've moved the problem rather than solved it, so re-check query counts end to end after the change, not just at the layer you touched.
You observe that a service's p99 latency has increased from 200ms to 1200ms over the last hour. Describe a structured troubleshooting workflow (step-by-step) you would follow to identify and mitigate the root cause. Include quick mitigations and what you'd capture for a later post-incident review.
Sample Answer
Direct answer: Treat this as a live incident, not a puzzle to solve calmly. In the first minutes, establish scope and correlate the timing against recent changes (deploy, config, traffic), decide on a fast reversible mitigation, and run deeper diagnosis in parallel rather than waiting for a full root cause before acting.
Structured elaboration:
- Minute 0 to 5, confirm and scope. p99 (the 99th percentile latency: 99% of requests are faster than this number) rising while p50 (the median latency: half of all requests are faster than this) stays flat means a growing minority of requests are getting badly hit, not a uniform slowdown. Check if this is one endpoint, one host, one region, or everything, and check the error rate alongside latency, not latency alone.
- Minute 5 to 10, correlate with change. Pull the deploy log, config/feature-flag change log, and traffic graph for the last one to two hours. A step change in p99 that starts exactly at a deploy or config push is your strongest early signal.
- Minute 10 to 20, decide on mitigation. If a change correlates, roll it back, since rollback is usually fast and reversible. If nothing correlates but a resource looks saturated (CPU, DB connections, thread pool queue), scale up or shed load. If a downstream dependency is clearly the cause, trip a circuit breaker (automatically stop sending requests to that dependency for a cooldown period once its failure rate crosses a threshold, so it can recover instead of being hit harder) or fail over.
- In parallel, preserve evidence. Pull traces for the slowest requests before you touch anything that would erase them (an instance getting killed or scaled down loses its state).
- Set an explicit rollback threshold before you decide, not during. For example: "if p99 hasn't dropped within 5 minutes of the rollback completing, or the error rate is still climbing, treat this candidate as ruled out and move to the next hypothesis." Writing this down ahead of time stops the team from waiting indefinitely on a fix that isn't working.
Worked example: Service-wide p99 climbs from 200ms to 1200ms starting 55 minutes ago. The deploy log shows a release went out 58 minutes ago. Splitting the latency metric by version, the 95% of traffic still on the old build has p50 around 45ms and p99 around 210ms, while the 5% already on the new build has p50 around 700ms, p80 around 1200ms and p99 around 3000ms. Sanity-check that the two halves can actually produce the number on the dashboard before you act on them, because a mixture's p99 can never be worse than the worst of its parts: if the canary's own p99 were 1150ms, no mix of it with a 210ms version could ever show a service-wide p99 of 1200ms, and a pair of numbers like that means one of the two metrics is mislabelled or scoped wrong. Here the arithmetic works out: the aggregate p99 is the point where 1% of all requests are slower, the canary supplies 5% of traffic, and 0.05 x 0.20 = 0.01, so the service-wide p99 lands where the canary's slowest fifth begins, which is the canary's p80 of about 1200ms. Everything else is held constant (same infrastructure, same traffic mix, only the version differs), so that is a clean causal signal and you roll the deploy back immediately rather than spending the next 20 minutes profiling. The same arithmetic is worth running in reverse before a rollout: a 5% canary that is merely twice as slow as the old build barely moves the service-wide p99 at all, which is why you alert on canary-versus-baseline percentiles rather than waiting for the aggregate number to move.
Trade-offs and pitfalls: Rolling back the first thing that correlates without checking whether it's plausible wastes the recovery window if you're wrong. Restarting or scaling an unhealthy instance before pulling traces or a profile from it throws away the evidence you need for the post-incident review. For that review, capture the exact timeline (when it started, when you noticed, when you mitigated), the before and after metrics, the change you rolled back or the resource you scaled, and, once found, the actual root cause, packaged as a short runbook (a step-by-step reference for handling this specific type of incident) so the next person facing the same symptom has a checklist instead of starting from zero.
You need to quickly determine whether a database is the bottleneck for a slow API. Describe three lightweight checks you can perform without changing application code, and one safe, immediate mitigation if the DB is overloaded.
Sample Answer
Direct answer: Check the database's own health metrics, the fraction of request time its calls take up in a trace, and your application's own connection-pool wait time. If all three point the same direction, temporarily reducing the load hitting the database, for example by lowering a rate limit at the gateway, is a safe, immediately reversible mitigation that needs no code change.
Structured elaboration, three lightweight checks:
- Database-side metrics: look at the database's own dashboard for active connections, queries queued waiting for a connection slot, slow-query log entries, and host-level CPU/IO utilization. If the database's own connection pool is maxed and queries are queueing there, that's direct evidence.
- Trace-based time attribution: pull a handful of slow-request traces and look at what fraction of total request time is the database span versus everything else. If the database span dominates the trace, it's the bottleneck by definition, no code change needed to observe this.
- Application-side connection-pool wait time: check your app's own connection-pool metrics (checked-out connections, average wait time to acquire one). If the app is waiting to acquire a database connection before it even issues a query, that's evidence of database-side saturation (the database is at or near its capacity limit for that resource, so work queues instead of being served immediately) visible purely from metrics you already emit.
One safe immediate mitigation: temporarily lower the rate limit or traffic admission at the API gateway or load balancer for the affected endpoint. It's instantly reversible, requires no deploy, and directly relieves pressure on the database by reducing the query volume hitting it. If a healthy read replica already exists for read-only traffic, failing reads over to it is another safe option, but only for genuinely read-only paths, since routing writes there won't help and using it for read-after-write paths can surface replication lag as apparent data inconsistency.
Worked example: The database dashboard shows active connections pinned at the pool's configured maximum (100 of 100) with a query queue depth of 40, starting at the exact minute the API got slow. Traces on the slow endpoint show the database span accounts for about 85% of total request time. Application-side pool metrics show average wait-to-acquire-a-connection time jumped from about 2ms to about 180ms at the same moment. All three signals agree: database bound. The gateway's rate limit for that endpoint is dropped from 500 requests per second to 300 for 15 minutes to relieve the connection queue, then restored once the queue drains.
Trade-offs and pitfalls: shedding load has a real cost, some users get throttled or see errors, so it should be communicated as a deliberate, time-boxed mitigation, not applied silently. A read-replica failover only helps genuinely read-only traffic; routing write-dependent or read-after-write requests there won't fix the slowness and can introduce a separate correctness problem from replication lag.
Unlock Full Question Bank
Get access to all 10 Performance Troubleshooting & Incident Response interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.