Quick revision
The short answer
Truncating 120 tables one statement at a time is slow because each TRUNCATE pays a fixed cost and takes an exclusive lock, and running those locks in different orders from concurrent sessions causes deadlocks. I would first replace them with one TRUNCATE t1, t2, ... CASCADE statement, then remove most resets entirely with tests that roll back their transaction or own their data, use a template database when a full reset is unavoidable, truncate only the tables a test touched, and make sure parallel tests never share a schema.
What to remember
In this answer, we saw that truncating 120 tables one by one pays a fixed cost per table and takes exclusive locks in a varying order, which makes the suite slow and lets concurrent resets deadlock. Combining them into one TRUNCATE ... RESTART IDENTITY CASCADE statement is the quick win. The bigger wins come from not resetting at all, through rollback tests and tests that own their data, from copying a template database when a full state is needed, from truncating only touched tables, and from giving each parallel run its own schema.
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.
Truncating 120 tables one statement at a time is slow because each TRUNCATE pays a fixed cost and takes an exclusive lock, and running those locks in different orders from concurrent sessions causes deadlocks. I would first replace them with one TRUNCATE t1, t2, ... CASCADE statement, then remove most resets entirely with tests that roll back their transaction or own their data, use a template database when a full reset is unavoidable, truncate only the tables a test touched, and make sure parallel tests never share a schema.
Why this question is asked
Slow, flaky integration tests are a tax on every change a team makes. A suite that resets 120 tables before each of 2,000 tests spends more time cleaning than testing, and occasional deadlocks teach developers to rerun failures instead of trusting them. Interviewers like this scenario because the fix spans database knowledge, such as how TRUNCATE locks, and test design. In this answer, we will see why the current reset is slow and where the deadlocks come from, then go through the changes in order of impact: one combined statement, tests that need no reset, faster full resets with templates, targeted truncation, and isolation for parallel runs.
1Why the Current Reset Is Slow and Deadlocks
TRUNCATE is fast for a big table, but it has a fixed cost per table. In PostgreSQL each truncated table and each of its indexes gets new storage files, the old ones are scheduled for removal, and the change must be made durable at commit. For a table with ten rows, that fixed cost is far larger than simply deleting the rows. Multiply it by 120 tables, often with three indexes each, and by 2,000 tests, and the reset alone can take many minutes of the run.
The deadlocks come from locking. Each TRUNCATE takes an ACCESS EXCLUSIVE lock on its table, and with CASCADE, or with foreign keys, it locks related tables too. If two sessions reset at the same time, maybe because tests run in parallel, or because a background thread of the application under test is still writing, they can take locks in different orders: session A holds orders and waits for customers, session B holds customers and waits for orders. The database detects the cycle and kills one of them.
6 messages in order. Play them, or step through them one at a time.
2Fix 1: One TRUNCATE Statement for All Tables
The quickest change is to truncate every table in a single statement. PostgreSQL accepts a list of tables, takes all the locks within one command, and processes them together, which removes the per-statement round trips and the risk of two resets interleaving their lock order.
RESTART IDENTITY also resets sequences, which keeps generated ids predictable across tests. A list built once from the catalog, for example all tables in the schema except the migration history table, avoids forgetting new tables. In MySQL, TRUNCATE takes one table at a time and refuses referenced tables, so the equivalent is SET FOREIGN_KEY_CHECKS = 0, truncating each table, then turning checks back on, all in a single session; for small tables, DELETE is often faster there too.
3Fix 2: Tests That Need No Reset
The fastest reset is no reset. In Spring, a test class or method annotated with @Transactional runs inside a transaction that the test framework rolls back at the end, so nothing the test wrote survives and nothing needs cleaning. A rollback costs microseconds.
There is a catch: this only works when the code under test runs in the test's transaction. Code that starts its own transaction with REQUIRES_NEW, works on another thread, uses @Async, sends HTTP requests to the running server through a real port, or commits through a message listener writes outside the test transaction, and those writes are not rolled back. For those tests, a different design helps: each test creates its own data with unique keys, such as a random customer id or a per-test tenant, and asserts only on that data. Then leftovers from other tests do not matter, and no reset is needed.
4Fix 3: Recreate State From a Template When a Full Reset Is Needed
Some tests need a known full state, such as seeded reference data. Instead of truncating and reseeding, PostgreSQL can create a new database as a file-level copy of a template database that already holds the migrated schema and seed data.
The template must have no open connections while it is copied, and the cost grows with the size of the template, so this works best for small schemas with modest seed data. With Testcontainers, a similar effect comes from preparing one container image with the migrated schema baked in, or from reusable containers, so each run starts from a ready state instead of running all migrations again.
5Fix 4: Truncate Only What the Test Touched
Most tests touch three to five of the 120 tables. If the framework records which tables received writes, the reset can truncate just those. Simple ways to track it are a statement listener on the DataSource, through datasource-proxy or p6spy, that notes the target table of every INSERT, UPDATE and DELETE, or a check of PostgreSQL's per-table counters in pg_stat_xact_user_tables, which show inserts and updates done in the current transaction. The reset then becomes one TRUNCATE of a handful of tables, with CASCADE to cover dependent tables.
This pairs well with Fix 1: a single statement over a short list is both fast and deadlock-free.
6Fix 5: Isolate Parallel Runs
Finally, the deadlocks are a strong hint that two things are resetting the same schema at once. If JUnit runs test classes in parallel, or the build runs several forks, each must have its own database or schema, for example a schema name derived from the fork number, or a separate database cloned from the template. Background work from the application, such as scheduled jobs or message consumers, should be stopped or awaited before a reset. With isolation in place, the remaining resets cannot deadlock against each other, and the suite can safely use more parallelism to get faster still.
- Code runs in the test transaction?Yes@Transactional rollback, no resetNonext question
- Can the test own unique data keys?Yesno reset, assert on own dataNonext question
- Needs full seeded state?Yescopy from template databaseNotruncate touched tables
- Parallel forksone schema or database per fork
4 steps in order. Play them, or step through them one at a time.
7Follow-up questions
Is @Transactional rollback hiding bugs?
It can. Because the transaction never commits, deferred constraints, commit-time triggers and flush-at-commit behaviour are never exercised, and lazy loading may work in tests but fail in production where the transaction has ended. Keep a smaller set of tests that commit for real, and call flush() in rollback tests so SQL errors surface.
Why not just use an in-memory database such as H2?
It is fast, but it is a different database with different SQL, locking and type behaviour, so tests pass that would fail on PostgreSQL. Testcontainers with the real engine plus the techniques above gives speed without that gap.
How do I find which tests cause the deadlocks?
Enable log_lock_waits and deadlock logging in the test database. PostgreSQL logs both statements involved in a deadlock, and the application names or a test-name comment in the SQL point to the culprits.
8Conclusion
In this answer, we saw that truncating 120 tables one by one pays a fixed cost per table and takes exclusive locks in a varying order, which makes the suite slow and lets concurrent resets deadlock. Combining them into one TRUNCATE ... RESTART IDENTITY CASCADE statement is the quick win. The bigger wins come from not resetting at all, through rollback tests and tests that own their data, from copying a template database when a full state is needed, from truncating only touched tables, and from giving each parallel run its own schema.
Open with
First I would look at why it is slow and why it deadlocks. TRUNCATE is fast for large tables, but it has a fixed cost per table, new storage files and an exclusive lock, so 120 statements before every test adds up to minutes, and for tiny tables DELETE is often cheaper.
Then, if they want more
The deadlocks mean two sessions are resetting or writing at the same time and taking locks in different orders, often because tests run in parallel on one schema or a background job is still writing.
The quick fix is a single TRUNCATE statement listing all the tables with RESTART IDENTITY CASCADE, which takes the locks together and removes the ordering problem. Then I would reduce how often we reset at all. Tests whose code runs in the test transaction can use Spring's @Transactional and roll back, which costs almost nothing.
Tests that cannot, because the code uses its own transactions, async work or HTTP, should create their own data with unique keys and assert only on that, so leftovers do not matter. Where a full seeded state is unavoidable, I would copy a template database with CREATE DATABASE ... TEMPLATE, or bake the migrated schema into the Testcontainers image.
I would also track which tables a test wrote to and truncate only those. And I would make sure each parallel fork gets its own schema or database.
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.
- 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 "Integration tests reset the database between tests with TRUNCATE on 120 tables and the...": https://scrivio-interview-library.netlify.app/databases/sql-fundamentals/a6c5db25f5/