Quick revision
The short answer
Idempotency records only need to live for the retry window, so the storage should make expiry free instead of deleting billions of rows one by one. In PostgreSQL that means partitioning the table by creation day and dropping old partitions, with the partition key included in the unique constraint; alternatively a store with native TTL such as Redis (SET key value NX EX) works if we accept that a failover can lose keys. Where the order lives in the same database, the record is written in the same transaction as the order, and it stores a compact reference rather than a full response body.
What to remember
In this answer, we saw why deleting billions of expired rows causes WAL volume, replica lag and bloat in PostgreSQL. We made expiry cheap with daily partitions that are dropped whole, keeping the partition key in the unique constraint and checking the previous day's partition on lookup. We compared that with Redis SET NX EX, which expires keys for free but can lose recent keys on failover, wrote the record in the same transaction as the order where possible, and stored a compact reference instead of the response body.
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.
Idempotency records only need to live for the retry window, so the storage should make expiry free instead of deleting billions of rows one by one. In PostgreSQL that means partitioning the table by creation day and dropping old partitions, with the partition key included in the unique constraint; alternatively a store with native TTL such as Redis (SET key value NX EX) works if we accept that a failover can lose keys. Where the order lives in the same database, the record is written in the same transaction as the order, and it stores a compact reference rather than a full response body.
Background to this question
Idempotency tables start small and quietly become one of the largest tables in the database, because every write request adds a row and nobody thinks about removing them until the cleanup job hurts. At 30,000 writes per second, a day adds about 2.6 billion rows, and the problems in this scenario, replica lag, bloat and slower orders, are the classic symptoms of deleting at that rate. In this answer, we will see why row-by-row deletes hurt PostgreSQL, redesign the table with daily partitions, compare it with a TTL store such as Redis, look at transactional writes and compact responses, and decide which option suits which kind of operation.
1Why Nightly DELETEs Hurt
PostgreSQL implements MVCC (multi-version concurrency control): a DELETE does not remove a row, it marks the row version as dead. VACUUM later reclaims the space. Deleting a day's worth of keys, about 2.6 billion rows at 30,000 per second, therefore writes a dead marker on every one of them, generates a huge volume of write-ahead log (WAL), and leaves a mountain of dead tuples for autovacuum to clean.
Each of those effects matches a symptom. The WAL has to be shipped and replayed on the replicas, so they fall behind: replica lag. VACUUM cannot keep up, so the table and its unique index swell with dead space: bloat. A bloated index on the key means more pages to read and cache for each insert and lookup, and the cleanup competes for I/O with live traffic: the order endpoint's p99 doubles. The deeper issue is that we pay per row to throw away data whose expiry we knew when we wrote it.
2Option 1: Partition by Day and Drop Old Partitions
PostgreSQL declarative partitioning lets us split one logical table into child tables by a range of a column. If we partition by the day the record was created, expiry becomes a metadata operation: once a partition is older than the retention window, for example 3 days, we DETACH and DROP it. Dropping a table removes its files at once, writes almost no WAL and leaves no dead tuples. A small job, or the pg_partman extension, creates tomorrow's partition in advance and drops expired ones.
There is a catch: on a partitioned table, a unique constraint must include the partition key. We cannot declare UNIQUE (client_id, key) alone; we must declare UNIQUE (client_id, key, created_day). That means the database no longer guarantees that a key is unique across days. We handle it by making the day part of the lookup: the client's key arrives with the request, and the server checks today's and yesterday's partitions (keys only matter within the retry window), or we encode the creation day in the key the server hands back. Another approach is to partition by a hash prefix of the key and expire by time inside each partition, but daily partitions are the simplest when retention is short.
Notice that the primary key includes created_day, as PostgreSQL requires. The insert path claims the key in today's partition and, before that, checks yesterday's partition for a record of the same key, which covers retries that cross midnight.
3Option 2: A Store With Native TTL
Redis, or a key-value store such as DynamoDB with item TTL, expires entries on its own. In Redis, SET idem:42:K value NX EX 86400 creates the key only if it does not exist (NX) and gives it a 24-hour lifetime (EX). It is one atomic command, so it also handles the race between concurrent retries. At 30,000 writes per second, a Redis cluster handles this comfortably.
The trade-off is durability. Redis replication is asynchronous, so if a primary fails, writes that had not reached the replica are lost, and AOF persistence with everysec fsync can lose about a second of writes on a crash. Losing an idempotency record reopens a window for duplicates: a retry that arrives after the failover finds no key and runs again. There is also a split between two systems: the order commits in PostgreSQL and the key lives in Redis, so a crash between the two writes leaves them disagreeing.
| Option | Expiry cost | Durability | Atomic with the order |
|---|---|---|---|
| Single PostgreSQL table + DELETE | per row, WAL and bloat | strong | yes |
| PostgreSQL, daily partitions | DROP of a partition, near zero | strong | yes |
| Redis SET NX EX | automatic TTL | can lose recent keys on failover | no, separate system |
| Key-value store with item TTL | automatic, background | strong per region | no, unless the order lives there too |
4Writing the Record in the Same Transaction as the Order
When the order and the idempotency record live in the same PostgreSQL database, we get a guarantee no external store can give: the record and the business change commit together or not at all. The handler inserts the record as in progress, creates the order, updates the record to completed with the order id, and commits once. If the process crashes halfway, the transaction rolls back and neither exists, so a retry starts cleanly. With an external store, we would have to handle the case where the order exists but the key does not, or the reverse.
The record stores status 201 and the order id. A replay rebuilds the response from the order, which keeps rows small: a few dozen bytes instead of several kilobytes of JSON per row, which at billions of rows is the difference between tens of gigabytes and terabytes.
5Follow-up questions
Which option would you choose for payments, and which for a like button?
For payments I would keep the records in PostgreSQL with daily partitions, written in the same transaction as the payment, because losing a key means charging someone twice and the cost of strong durability is worth it. For a like button, a duplicate is harmless and often idempotent anyway (a like is a set, not a counter), so Redis with SET NX EX, or no key at all and a unique constraint on (user, post), is fine; losing a few keys during a failover costs nothing.
How short can the retention be?
It must cover the longest realistic retry: client retries with backoff, app restarts, and offline mobile devices. 24 to 72 hours covers almost all of them. Measuring the age of keys when they are reused gives the real distribution, and the retention can be set from its 99.99th percentile plus a margin.
6Conclusion
In this answer, we saw why deleting billions of expired rows causes WAL volume, replica lag and bloat in PostgreSQL. We made expiry cheap with daily partitions that are dropped whole, keeping the partition key in the unique constraint and checking the previous day's partition on lookup. We compared that with Redis SET NX EX, which expires keys for free but can lose recent keys on failover, wrote the record in the same transaction as the order where possible, and stored a compact reference instead of the response body.
Open with
The root problem is that we pay per row to delete data whose expiry we knew when we wrote it. In PostgreSQL a DELETE leaves dead tuples and generates WAL for every row, so deleting a couple of billion rows a night causes replica lag, bloat in the table and its unique index, and slower inserts for orders.
Then, if they want more
Idempotency keys only need to live for the retry window, 24 to 72 hours, so I would make expiry free. The first option is to partition the table by creation day and drop old partitions, which is instant and writes almost no WAL.
The catch is that the unique constraint must include the partition key, so I make the day part of the lookup, checking today's and yesterday's partitions, or use a hash prefix scheme. The second option is a store with native TTL, like Redis with SET key value NX EX, which also gives an atomic claim.
But Redis replication is asynchronous, so a failover can lose recent keys and reopen a window for duplicates. When the order lives in the same database, I prefer to insert the idempotency record in the same transaction as the order, so they commit together. And I would store just the status and the order id rather than full response bodies.
For payments I would choose partitioned PostgreSQL; for something like a like button, Redis is fine.
About this answer
- Last updated
- 13 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 official documentation for the version you use. 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 redesign storage of idempotency records at this volume?": https://scrivio-interview-library.netlify.app/architecture/api-design-at-scale/7505e98ba7/