Quick revision
The short answer
First stop new duplicates by fixing the producer or making inserts idempotent. Then delete the existing duplicates in small batches by primary key range, around 10,000 rows per transaction, throttled against replication lag and kept in an audit table. Finally build the unique index with CREATE UNIQUE INDEX CONCURRENTLY and attach it with ALTER TABLE ... ADD CONSTRAINT ... UNIQUE USING INDEX, letting autovacuum clean up the dead rows and checking downstream consumers.
What to remember
In this answer, we removed duplicates from a 300 million row table without an outage. We stopped new duplicates by fixing the producer and planned ON CONFLICT DO NOTHING on the natural key once a unique index exists. We built a helper index concurrently, deleted duplicates in batches of about 10,000 ids with ROW_NUMBER over the natural key, throttled by replication lag and copied into an audit table, then built the unique index with CREATE UNIQUE INDEX CONCURRENTLY and attached it with ADD CONSTRAINT ... UNIQUE USING INDEX, dropping any INVALID index from a failed build. Autovacuum reclaims the dead tuples, pg_repack or a rebuild helps when much more is removed, and downstream consumers are told what they counted twice.
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.
First stop new duplicates by fixing the producer or making inserts idempotent. Then delete the existing duplicates in small batches by primary key range, around 10,000 rows per transaction, throttled against replication lag and kept in an audit table. Finally build the unique index with CREATE UNIQUE INDEX CONCURRENTLY and attach it with ALTER TABLE ... ADD CONSTRAINT ... UNIQUE USING INDEX, letting autovacuum clean up the dead rows and checking downstream consumers.
Why this question is asked
A retry bug in a producer is ordinary; what makes this scenario hard is the table. With 300 million rows and 4,000 inserts every second, any statement that locks the table for a minute stops 240,000 events, and a single huge DELETE would hold locks, flood the WAL and leave replicas far behind. Interviewers ask this question to see whether we can plan a data repair as a sequence of small, safe, reversible steps on a system that never stops. In this answer, we will stop the bleeding, prepare an index to find duplicates fast, delete in batches, build and attach the unique constraint without blocking writes, deal with dead rows, and protect what was removed.
1Stopping New Duplicates First
If we start deleting while the producer still sends duplicates, we are emptying a bath with the tap running. So the first step is to fix the retry bug: usually the producer retries after a timeout without knowing the first attempt succeeded, so it must send the same event id on every retry, and the consumer must treat that id as an idempotency key, a value that makes repeating the same request harmless.
The database side of idempotency is INSERT ... ON CONFLICT DO NOTHING on the natural key, say (producer_id, event_id). But there is a catch: ON CONFLICT needs a unique index or constraint on those columns to detect the conflict, and we cannot build one while duplicates exist. So during the cleanup we rely on the producer fix, and once the unique constraint is in place, at the end of this plan, we switch the insert to ON CONFLICT DO NOTHING so a future retry bug cannot create duplicates again.
2Preparing an Index to Find Duplicates
To decide whether a row is a duplicate, we must find other rows with the same natural key. Without an index on that key, every check is a scan of 300 million rows. So we first build a normal, non-unique index on the key, without blocking inserts. CREATE INDEX CONCURRENTLY scans the table twice and waits for running transactions, so on this table it may take an hour or more, but writes continue the whole time.
Later we will turn exactly this kind of index into the unique one, but we cannot do that yet, because the duplicates would make a unique build fail.
3Deleting in Small Batches
Now the cleanup itself. We walk the table by primary key range, a slice of ids at a time. For each slice, we take the natural keys that appear in it, number all rows with those keys using ROW_NUMBER() ordered by id, and delete every row numbered above 1, moving it into an audit table in the same statement. Using the keys from the slice, rather than only the rows in it, matters: a duplicate's original might sit in an earlier slice.
- Pick the next id range10,000 ids
- Number rows per natural key
ROW_NUMBERover keys in the range - Delete rn > 1 into the audit tableone short transaction
- Replica lag over 30 seconds?YesPause until it catches upNoSleep briefly, next range
4 steps in order. Play them, or step through them one at a time.
Each batch is its own short transaction, holding row locks only on the few hundred rows it deletes, so inserts never wait. Between batches the job sleeps briefly and checks replication lag; if a replica falls more than, say, 30 seconds behind, it pauses until it catches up. At 10,000 ids per batch, 300 million rows is 30,000 batches; at a few per second, the cleanup finishes in a few hours, and it can stop and resume at any id.
4Building and Attaching the Unique Constraint
When the last batch is done and a final check finds no duplicate keys, we build a unique index concurrently, then attach it to the table as a constraint. Attaching is a quick catalog change, because the index already exists and is already verified.
Notice the failure case. If a concurrent build fails, PostgreSQL leaves the index behind marked INVALID. It is not used by queries but is still updated on every insert, so it costs write performance until we remove it with DROP INDEX CONCURRENTLY and try again. Once the constraint exists, we switch the producer's insert to ON CONFLICT DO NOTHING.
5Dead Rows, Bloat and Vacuum
PostgreSQL does not remove deleted rows immediately. Each delete leaves a dead tuple, a row version that no transaction can see any more, until vacuum reclaims the space for reuse. Two percent of 300 million is about 6 million dead tuples, which autovacuum handles comfortably if it is tuned for a busy table; we can also run VACUUM on the table after the cleanup. The space is reused by new inserts but not returned to the operating system, so the table stays the same size on disk.
If the duplicates had been a large fraction, say 30 percent, the bloat would be worth removing. pg_repack can rebuild the table online with only brief locks, or we could build a clean copy into a new table and swap, which is the follow-up question below.
6Protecting What Was Removed
Deleted events may matter to someone. The audit table keeps every removed row with the time it was removed, for a few weeks or as long as the data retention policy says, so we can restore a row if the duplicate rule turns out to be wrong for some producer. And we check downstream consumers: reports, billing or analytics that read events may have counted the duplicates, so their past numbers were too high. Those teams need to know which period was affected and by how much, which the audit table can tell them.
7Follow-up questions
When would you rebuild into a new table and swap instead of deleting in place?
When a large share of rows are duplicates, when the table is badly bloated anyway, or when we also want to change its structure, for example to partition it by time. We create the new table with the unique constraint, copy distinct rows in batches, capture ongoing writes with a trigger or dual writes, and swap the names in one short transaction. It needs more space and more care, but leaves a compact table.
Why not delete everything in one statement during a quiet hour?
There is no quiet hour at 4,000 inserts per second. One statement deleting 6 million rows holds its locks and snapshot for a long time, writes a huge burst of WAL that replicas must replay, and if it fails near the end, everything rolls back. Batches keep each step small and resumable.
How do you pick the batch size?
Start small, for example 10,000 ids, and measure: each batch should finish in well under a second and keep replica lag low. Increase it while those numbers stay healthy, and let the job reduce it automatically when lag grows.
8Conclusion
In this answer, we removed duplicates from a 300 million row table without an outage. We stopped new duplicates by fixing the producer and planned ON CONFLICT DO NOTHING on the natural key once a unique index exists. We built a helper index concurrently, deleted duplicates in batches of about 10,000 ids with ROW_NUMBER over the natural key, throttled by replication lag and copied into an audit table, then built the unique index with CREATE UNIQUE INDEX CONCURRENTLY and attached it with ADD CONSTRAINT ... UNIQUE USING INDEX, dropping any INVALID index from a failed build. Autovacuum reclaims the dead tuples, pg_repack or a rebuild helps when much more is removed, and downstream consumers are told what they counted twice.
Open with
First I stop new duplicates: fix the producer so retries reuse the same event id, because cleaning while duplicates keep arriving is pointless. I would also plan to make the insert idempotent with insert on conflict do nothing on the natural key, but that needs a unique index, so it comes at the end.
Then, if they want more
Next I build a non-unique index on the natural key concurrently, so finding duplicates is fast and inserts are not blocked.
Then I delete in small batches by primary key range, about 10,000 ids per transaction: for the keys in each range I number rows with ROW_NUMBER ordered by id and delete those above one, using delete returning into an audit table.
Each batch holds locks briefly, and the job sleeps between batches and pauses if replica lag grows, so the cleanup is slow but safe and resumable. When a check shows no duplicates, I run create unique index concurrently and attach it with alter table add constraint unique using index, which is just a catalog change.
If the concurrent build fails, it leaves an invalid index that I must drop before retrying. Then I switch the insert to on conflict do nothing. The deletes leave about six million dead tuples, which autovacuum can handle; if far more rows went, I would consider pg_repack or rebuilding into a new table.
Finally I keep the removed rows for a while and tell downstream consumers that counted the duplicates.
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 "A 300 million row events table in PostgreSQL has about 2 percent duplicate rows caused...": https://scrivio-interview-library.netlify.app/databases/sql-coding-problems/fd14201586/