Scrivio Interview library
DesignAdvanced5 min read · updated 12 November 2026

How would you build a practice across 40 teams for finding and fixing slow database queries before they cause incidents?

I would collect query statistics centrally, for example from pg_stat_statements, and publish the top queries per service, with every query tagged by service and endpoint through the application name or SQL comments so it can be traced back to code. Slow-query and plan checks would run in load tests and code reviews for new queries on large tables, per-query latency percentiles would be part of every team's standard dashboard, and teams would have regular access to a DBA or performance guild instead of meeting experts only during incidents.

Why this question is asked

In an organisation with 40 teams, slow queries are not a knowledge problem in one team; they are a visibility and habit problem across all of them. Most incidents caused by a query were visible weeks earlier in some statistic nobody looked at. Interviewers ask this to see whether we can build a lightweight practice that finds problems early and fits into how teams already work. In this answer, we will set up central query statistics, make every query traceable to its owner, add checks before production, put database metrics on the standard dashboards, and give teams access to expertise.

1Collecting Query Statistics Centrally

The foundation is data about every query, not just the ones that time out. In PostgreSQL, the pg_stat_statements extension records, per normalised query (the SQL with literal values replaced by placeholders), how many times it ran, total and mean execution time, rows returned and buffer usage. Other databases have equivalents, such as the Performance Schema digest tables in MySQL. Managed cloud databases add query insight tools built on the same idea.

We scrape these statistics regularly into a central store, so we can see trends, not just the current state. The weekly view that matters is the top queries by total time, which shows where the database spends its effort, and by mean time, which shows the slowest individual queries. A query that runs 50 million times a day at 4 ms costs far more than a report that runs once at 30 seconds.

SQL
SELECT queryid, calls, round(total_exec_time) AS total_ms, round(mean_exec_time, 1) AS mean_ms, left(query, 60)
FROM pg_stat_statements ORDER BY total_exec_time DESC LIMIT 5;
-- 812331 | 51,204,118 | 211,503,002 | 4.1 | select ... from orders where customer_id = $1 ...
-- 104992 | 1,212 | 38,881,440 | 32,080.0 | select ... from audit order by created_at ...

2Tracing Each Query Back to Its Owner

A top-ten list is useless if nobody knows which team owns each line. So every connection identifies its service: the PostgreSQL JDBC driver accepts ApplicationName in the connection properties, which shows up in pg_stat_activity and logs, and separate database users per service make grouping even easier. For finer detail, SQL comments carry the endpoint or operation, in the style of sqlcommenter, for example /* service=orders,route=GET /orders/{id} */, so a slow query in a log or monitoring tool leads straight to the code. Note that pg_stat_statements normalises queries and may group differently commented queries depending on settings, so check how your tooling handles comments.

The platform's Spring Boot starter sets the application name from spring.application.name automatically, so teams get this without effort.

Step throughFrom query to owner
  1. Service codeSpring Data repository or JdbcTemplate
  2. Platform startersets ApplicationName, adds route comment
  3. Databasepg_stat_statements, slow query log, auto_explain
  4. Central query storetrends per service and query family
  5. Weekly report and dashboardstop queries routed to the owning team

5 layers, from the top down. Step through them one at a time.

3Catching Problems Before Production

Most slow queries are slow because of data volume, so they look fine in development with 1,000 rows. Two checks catch them earlier. In load tests against production-sized data, we enable the slow query log and auto_explain, which logs the plan of any query above a threshold, and fail the run when a query family's p95 latency or rows read jumps compared with the last release.

In code review, a new query on a large table gets a short extra step: the author attaches the EXPLAIN output from a realistic data set, and reviewers check for sequential scans, missing indexes, unbounded results and functions on indexed columns. A short checklist in the pull request template makes this routine rather than heroic.

4Making Database Performance Part of Every Dashboard

The standard service dashboard that every team already has gets a database section: latency percentiles per query family, calls per second, rows read per call, and pool metrics such as pending connection requests. Seeing p99 for the orders lookup next to the endpoint's latency makes the link obvious. Alerts fire when a query family's latency or rows read changes sharply, which catches plan regressions after a data load or deploy before users notice.

Step throughThe weekly loop
  1. Scrape query statisticspg_stat_statements per database
  2. Rank by total and mean timegroup by service and query family
  3. New or regressed query in the top list?
    YesOpen a ticket for the owning teamNoNo action
  4. Team fixes with guild help if neededindex, query rewrite, caching
  5. Verify in the next week's dataclose or escalate

5 steps in order. Play them, or step through them one at a time.

5Giving Teams Access to Expertise

Even with good tools, reading plans and designing indexes is a skill, and few teams have a database expert. Instead of meeting a DBA only during an incident, teams get scheduled access: office hours with a DBA or a performance guild, a channel where a plan can be reviewed within a day, and short internal workshops on reading EXPLAIN, indexing and paging. The guild also curates the shared knowledge, such as known anti-patterns and how-to guides, and reviews the weekly top-query report with the teams involved.

Finally, the practice needs a measure of success. I would track the number of incidents caused by queries, how many top queries were fixed before an incident, and the database time per business transaction over a few quarters.

6Follow-up questions

How do you prevent the weekly report from being ignored?

Keep it short, route each item to a named owning team as a ticket rather than a broadcast, and review progress in an existing operations meeting. A report with ten actionable items per week gets acted on; a dashboard with five hundred lines does not.

Is pg_stat_statements expensive to run in production?

Its overhead is small for most workloads and it is widely enabled in production, including on managed services. The main settings to watch are the number of distinct statements it tracks and whether query text storage grows large.

What do you do with queries owned by no team?

They are a finding in themselves. The platform team assigns an owner, often the team whose service uses the connection, and orphaned reporting queries are a common case to move to a replica or warehouse.

7Conclusion

In this answer, we built a practice for 40 teams: central query statistics from pg_stat_statements with top queries per service, every query tagged by service and endpoint so it reaches its owner, slow-query and plan checks in load tests and code reviews, per-query latency percentiles on the standard dashboards, and regular access to a DBA or performance guild, with a weekly loop and measures that show whether the practice works.

What to say in the interviewAbout 80 seconds aloud

Open with

I would build it around visibility and routine rather than heroics. First, collect query statistics centrally, for example by scraping pg_stat_statements from every database, and publish the top queries by total and mean time per service every week.

Then, if they want more

Second, make every query traceable: the platform starter sets the JDBC application name from the service name, each service has its own database user, and SQL comments in the sqlcommenter style carry the endpoint, so a line in the report points straight to code and a team.

Third, catch problems before production: load tests on production-sized data with the slow query log and auto_explain, failing when a query family regresses, and a code review step where new queries on large tables come with an EXPLAIN from realistic data.

Fourth, put latency percentiles, calls and rows read per query family on every team's standard dashboard with alerts on sudden changes. Fifth, give teams access to expertise, with DBA or guild office hours and plan reviews within a day, instead of meeting experts only in incidents.

The weekly loop routes each regressed query to its owner as a ticket, and I would measure success by fewer query-caused incidents and database time per business transaction.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "How would you build a practice across 40 teams for finding and fixing slow database...": https://scrivio-interview-library.netlify.app/databases/database-scaling/daac0fdc98/