Quick revision
The short answer
The new query lists orders and regions with commas but has no condition linking them, so PostgreSQL produced a cartesian product: every recent order paired with every active region, millions times thousands of rows. Sorting and hashing that result spilled to temporary files until the shared disk filled, which slowed and broke every other service on the same database. The guardrails are per-role limits such as statement_timeout and temp_file_limit, linting and review that reject comma joins, running reports on a replica, and alerts on temp file usage and long-running queries.
What to remember
In this answer, we saw that the comma join had no condition linking orders to regions, so it produced a cartesian product of billions of rows, whose sorts and hashes spilled to temporary files and filled the disk shared by every service. We restored the join condition with explicit JOIN syntax, then added guardrails: per-role statement_timeout, temp_file_limit and connection limits, linting and review for comma joins, reports on replicas, and alerts on temp files and long-running queries.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
The new query lists orders and regions with commas but has no condition linking them, so PostgreSQL produced a cartesian product: every recent order paired with every active region, millions times thousands of rows. Sorting and hashing that result spilled to temporary files until the shared disk filled, which slowed and broke every other service on the same database. The guardrails are per-role limits such as statement_timeout and temp_file_limit, linting and review that reject comma joins, running reports on a replica, and alerts on temp file usage and long-running queries.
Why this question is asked
Incidents like this are memorable because the change looked tiny: one filter in a reporting query, and minutes later the checkout service is timing out. Interviewers use this scenario to see whether we can read the SQL and find the cause quickly, explain why a report took down unrelated services, and then think beyond the one fix to the controls that stop the next one. In this answer, we will find the bug, follow the chain from the query to the full disk, repair the query, and then go through the guardrails layer by layer.
1Reading the Query
The query was FROM orders o, regions r WHERE o.created_at > :d AND r.active. In the comma syntax, the tables in FROM are combined as a cross product, every row of one with every row of the other, and the WHERE clause is supposed to contain the conditions that link them. Here both conditions are filters on one table each. There is nothing like o.region_id = r.id, so every order that passes the date filter is paired with every active region.
The numbers make the problem obvious. If 4 million orders are newer than :d and 2,500 regions are active, the join produces 10 billion rows. Most likely the filter the deploy added was the date filter, and someone removed or never had the region condition, or the query previously used a different join that was rewritten. Either way, the shape of the result changed from about 4 million rows to 10 billion.
2Why It Filled the Disk and Hurt Everyone Else
Producing 10 billion rows is slow, but on its own it would only waste CPU. The disk filled because reporting queries rarely stop at the join: they group, sort or count distinct values. Each sort or hash in PostgreSQL may use work_mem of memory, for example 64 MB. When its input does not fit, PostgreSQL writes the data to temporary files and works through them in batches. A sort over billions of wide rows writes hundreds of gigabytes of temp files.
Temporary files usually live on the same volume as the data, or on a shared temp tablespace. When it filled, every session that needed temp space failed, and writes that needed to extend tables or WAL slowed or failed too. Meanwhile, the runaway query held CPU and I/O bandwidth, and if it was retried by a scheduler or by an impatient user, several copies ran at once. The other services shared that database, so their simple queries queued behind the I/O, hit their own timeouts, and the incident looked like it was in checkout rather than in reporting.
- Comma join with no linking predicateorders x regions
- 4 million x 2,500 = 10 billion rows
- Sort or hash exceeds work_memspills to temp files
- Temp files fill the shared volume
- Other sessions fail or wait on I/Oservices time out
5 steps in order. Play them, or step through them one at a time.
3Fixing the Query
The immediate step is to cancel the query and stop whatever schedules it, then restore the missing condition. Writing the join explicitly puts the condition next to the table, where its absence is obvious.
Notice that the fixed query also returns a different and correct answer: before, every region showed the count of all recent orders, so the report was wrong as well as slow. That is worth saying in the incident review, because it means a test that checked the numbers would have caught it.
4Guardrail 1: Limits in the Database
The database should protect itself from any one session, because sooner or later a bad query will get through review. PostgreSQL lets us set limits per role, so the reporting user gets strict ones without affecting the application user.
With temp_file_limit, a session that tries to write more than 20 GB of temporary files gets an error and its files are removed, so one query can no longer fill the disk. statement_timeout stops long runs, and the connection limit stops a scheduler from starting ten copies. Other databases have their own tools, such as resource groups in MySQL 8.0 or resource governors and query limits in commercial databases; the principle is the same: a hard per-workload ceiling that does not depend on the query being right. Putting temp files on their own volume with temp_tablespaces also means that when they fill, data and WAL are unaffected.
5Guardrail 2: Process, Isolation and Monitoring
Next we make the bug less likely to ship. A SQL linter in CI can reject implicit comma joins so that every join has an explicit ON (SQLFluff, for example, has rules for join style; check the rule names for your version). Reporting SQL, which is often written quickly and outside the main code review path, should get the same review as application code, with the expected row count of each join written down. A test against a realistic data set that checks the totals would have failed here because every region showed the same count.
Then we isolate. Reporting queries that only read should run on a read replica, or in a separate analytics store, so the worst case is a slow replica, not a slow checkout. Finally we watch: alerts on temp_bytes growth in pg_stat_database, on temp_blks_written in pg_stat_statements, on any query in pg_stat_activity running longer than a few minutes, and on free disk space with enough lead time to act. In this incident, a temp-usage alert would have fired within the first minute.
- Lint and reviewexplicit JOIN ... ON, expected row counts
- Tests on realistic datacheck totals, not just that it runs
- Role limitsstatement_timeout, temp_file_limit, connection limit
- Isolationreports on a replica or analytics store
- Monitoringtemp bytes, long queries, disk space alerts
5 layers, from the top down. Step through them one at a time.
6Follow-up questions
Would raising work_mem have prevented the incident?
No. More memory per sort would only delay the spill slightly, because 10 billion rows do not fit in any reasonable work_mem. Raising work_mem globally is risky anyway, because each sort or hash in every session can use that much. The problem was the size of the result, so the fix is the join condition and the guardrails are limits, not bigger buffers.
Why use a per-role temp_file_limit instead of a global one?
Different workloads need different ceilings. A nightly batch that legitimately sorts large data may need 100 GB, while interactive reports should never need more than a few gigabytes. Setting it on the reporting role lets us be strict there without breaking the batch, and it also documents which workload is allowed to use what. Remember that the limit applies per session process, so parallel workers or many sessions can still add up, which is why the connection limit matters too.
How do you make sure the incident review leads to change?
We write down each guardrail as an owned action with a date, and we verify it the hard way: run a deliberately bad cross join as the reporting role in staging and confirm that it is cancelled by the timeout or the temp limit and that the alert fires. A guardrail that has never been triggered is only a belief.
7Conclusion
In this answer, we saw that the comma join had no condition linking orders to regions, so it produced a cartesian product of billions of rows, whose sorts and hashes spilled to temporary files and filled the disk shared by every service. We restored the join condition with explicit JOIN syntax, then added guardrails: per-role statement_timeout, temp_file_limit and connection limits, linting and review for comma joins, reports on replicas, and alerts on temp files and long-running queries.
Open with
The query has a cartesian product. With the comma syntax the join conditions have to be in WHERE, and here both conditions are filters, one on orders, one on regions, with nothing like o.region_id = r.id.
Then, if they want more
So every recent order is paired with every active region. If that is 4 million orders and 2,500 regions, it is 10 billion rows. The report then grouped or sorted that, each sort or hash went over work_mem and spilled to temp files, and the temp files filled the disk the whole database shares.
From then on, other sessions failed or waited on I/O, and other services timed out, which is why it looked like a checkout problem. I would cancel the query with pg_cancel_backend, stop its schedule, and fix it with an explicit JOIN regions ON r.id = o.region_id.
I would point out the old result was also wrong, since every region got the full count. For guardrails, first in the database: on the reporting role, a statement_timeout, a temp_file_limit, a connection limit, and log_temp_files so big spills are visible. Ideally temp files on their own volume.
Second, process: a SQL linter that rejects comma joins, review of reporting SQL with expected row counts, and tests that check totals. Third, isolation: run reports on a replica. And monitoring: alerts on temp bytes, long-running queries and free disk space.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- MySQL 8.0
- 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.
- Official documentation
- PostgreSQL documentation, The SQL Language
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 "A deploy added one filter to a reporting query, and the database ran out of temp space...": https://scrivio-interview-library.netlify.app/databases/sql-joins-and-subqueries/654baf0bb3/