Scrivio Interview library
ScenarioIntermediate7 min read · updated 12 November 2026

You must rotate the AES key used to encrypt customer data in a database with 500 million rows, without downtime. Describe the approach.

We store a key id with every ciphertext so the service always knows which key decrypts a value, add the new key and use it for all new writes while keeping the old key available for reading, and then move old rows in the background in batches, either by re-encrypting the data or, with envelope encryption, by only rewrapping the data keys, which is far cheaper. The old key is retired only when a count of rows per key id shows zero, and the background job is throttled to protect the database and is restartable from where it stopped.

Why this question is asked

Rotating an encryption key sounds simple until the data set is 500 million rows in a production database that cannot go offline. A naive approach, one big UPDATE that decrypts and re-encrypts everything, would lock tables, flood the write-ahead log and take hours, during which half the rows are under one key and half under the other with no way to tell which. Interviewers ask this scenario to see whether we can design for mixed states, zero downtime and safe completion. In this answer, we will see why the key id is the foundation, go through the phases of the rotation, compare re-encryption with rewrapping under envelope encryption, design the background job, and finish with verifying and retiring the old key.

1The Foundation: A Key Id With Every Ciphertext

During any rotation, some rows are encrypted with the old key and some with the new one, and that state lasts days or weeks. The only way to read both correctly is for each value to say which key it needs. So the stored format carries a key id, either as a separate column or as a prefix inside the value, such as v1:k2024:<base64 data>.

If the current design has no key id, the first step is to add one: every existing row gets the id of the current key, k2024, which is a cheap metadata update or a default on a new column. Without this, we would have to try each key in turn and guess from authentication failures, which is slow and fragile.

Java
-- Option A: separate column
ALTER TABLE customer ADD COLUMN pii_key_id text NOT NULL DEFAULT 'k2024';
CREATE INDEX CONCURRENTLY customer_pii_key_id_idx ON customer (pii_key_id);
-- Option B: prefix inside the stored value
-- 'v1:k2024:Gq3b...' -> decrypt with key k2024
-- 'v1:k2025:Hd8x...' -> decrypt with key k2025

Notice the index on the key id column. We will need it to find the rows still on the old key and to count them; with a prefix inside the value, a partial or expression index serves the same purpose.

2The Phases of the Rotation

The rotation runs in phases, each safe to stop at. In phase one, every instance of the service learns about the new key k2025 for reading, while still writing with k2024; this ensures that when writes switch, every instance can already read the new values. In phase two, all new writes and updates use k2025, so the number of old rows can only go down. In phase three, a background job moves the existing rows to k2025. In phase four, when no rows use k2024, we disable and later destroy it.

The order of the first two phases matters in a rolling deploy. If one pod writes k2025 rows before another pod knows k2025, the second pod fails to read them. Shipping read support first and switching writes in a later deploy avoids that.

Step throughZero-downtime key rotation
  1. Deploy: read k2024 and k2025writes still use k2024
  2. Deploy: write with k2025updates move rows naturally
  3. Background job re-encrypts or rewrapsbatches of 5,000, throttled
  4. Rows left on k2024?
    YesContinue the job from its checkpointNoDisable k2024
  5. Wait for backups to age outthen destroy k2024

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

3Re-Encrypting Rows Versus Rewrapping Data Keys

How heavy phase three is depends on the key design. If the AES key encrypts each field directly, every row must be read, decrypted with k2024, encrypted with k2025 and written back. For 500 million rows that is 500 million row updates, each creating a new row version in PostgreSQL, with matching write-ahead log, replica traffic and vacuum work. At a throttled 5,000 rows per second, it takes about 28 hours.

With envelope encryption, rows are encrypted with data encryption keys (DEKs), and only the DEKs are encrypted with the master key. Rotating the master key then means decrypting each wrapped DEK with the old master key and encrypting it with the new one. If there is one DEK per tenant or per month of data, that might be 10,000 small rewrap operations instead of 500 million row updates, finished in minutes. The data itself does not change, which is why envelope encryption is the usual recommendation for large data sets.

Two ways to move 500 million rows to the new key
AspectDirect key: re-encrypt rowsEnvelope: rewrap DEKs
Work items500,000,000 row updatesabout 10,000 DEK rewraps
Database loadHeavy: new row versions, WAL, vacuumTiny: one small table
Duration at safe speedAbout a day or moreMinutes
Data rows changedEvery rowNone
When to re-encrypt data anywayAlwaysOnly if a DEK itself is compromised

4Designing the Background Job

If we must re-encrypt rows, the job is built for a long, interruptible run. It processes rows in keyset order by primary key, a fixed batch at a time, in short transactions, so locks are held briefly and a failure loses at most one batch. It records the last processed id as a checkpoint, so a restart continues where it stopped instead of starting over. It only touches rows still on the old key, which makes it idempotent: running a batch twice changes nothing the second time.

Throttling protects production. The job sleeps between batches, and it backs off automatically when replication lag, database CPU or request latency crosses a threshold, so the business traffic always wins. Running in off-peak hours and at a modest rate is worth the extra elapsed time.

Java
long lastId = checkpoints.load("pii-rotation"); // 0 on the first run
while (true) {
List<Customer> batch = repo.findBatchOnKey("k2024", lastId, 5_000); // WHERE pii_key_id = 'k2024' AND id > :lastId ORDER BY id
if (batch.isEmpty()) break;
tx.executeWithoutResult(s -> {
for (Customer c : batch) {
String plain = crypto.decrypt("k2024", c.getNationalIdCipher());
c.setNationalIdCipher(crypto.encrypt("k2025", plain));
c.setPiiKeyId("k2025");
}
}); // one short transaction per batch
lastId = batch.get(batch.size() - 1).getId();
checkpoints.save("pii-rotation", lastId);
throttle.pauseIfDatabaseBusy(); // sleeps longer when replica lag > 5 s
}

Notice the race with live traffic. A user may update a row while the job is processing it. Because the application already writes with k2025, the worst case is that the job overwrites a fresh k2025 value with its own k2025 value of older data. Using optimistic locking with a version column, or an UPDATE ... WHERE pii_key_id = 'k2024' condition, makes the job skip rows that changed under it.

5Verifying and Retiring the Old Key

We never retire a key because a job said it finished. We count.

SQL
SELECT pii_key_id, count(*) FROM customer GROUP BY pii_key_id;
-- k2025 | 500,000,000
-- (no k2024 row)
-- for prefixed values:
SELECT count(*) FROM customer WHERE national_id_cipher LIKE 'v1:k2024:%'; -- 0

Once the count is zero in every table and column that used the key, including archives and other services' copies, we disable k2024 in the KMS rather than deleting it, and watch for decryption errors for a while. Backups still contain old ciphertext, so the key is only destroyed after the backups encrypted with it have aged out of the retention period, or we accept that those backups become unreadable.

6Follow-up questions

Why not decrypt with every key until one works?

It is slow, multiplying decrypt attempts by the number of keys, and with authenticated encryption it relies on failures to decide, which hides real corruption. A key id makes the decision explicit and cheap.

Can we pause the job during a sales peak?

Yes, and the design should make that a non-event. Because new writes already use the new key and the job is checkpointed and idempotent, stopping it for a week only delays retiring the old key; nothing is inconsistent in the meantime.

7Conclusion

In this answer, we rotated the key for 500 million rows without downtime. A key id with every ciphertext lets old and new keys coexist; we deploy read support for the new key, switch all writes to it, and move old rows in the background in throttled, checkpointed batches, or with envelope encryption simply rewrap the data keys, which is far cheaper. The old key is retired only when counting rows per key id shows none left, and destroyed after backups that need it have expired.

What to say in the interviewAbout 100 seconds aloud

Open with

The key requirement is that every ciphertext says which key it needs, so I would store a key id with each value, as a column or a prefix, and if the table does not have one yet, adding it with the current key as default is the first step.

Then, if they want more

Then I rotate in phases. First, deploy all instances so they can read with both the old and new keys while still writing with the old one, so a rolling deploy never meets a value it cannot read. Second, switch all new writes to the new key, so the old set only shrinks.

Third, move the existing rows in the background.

If the key encrypts fields directly, that means re-encrypting 500 million rows, which at a safe five thousand rows per second is more than a day of work, so the job runs in batches by primary key in short transactions, saves a checkpoint after each batch, only touches rows still on the old key so it is idempotent, and backs off when replica lag or latency rises.

If we use envelope encryption, rotating the master key only means rewrapping the data keys, maybe ten thousand small operations, which takes minutes and does not touch the data, and that is why I would recommend envelope encryption for data sets this size.

Finally, I retire the old key only when a count per key id shows zero rows everywhere, disable it before destroying it, and keep it until backups encrypted with it have expired.

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
Spring Security reference
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 "You must rotate the AES key used to encrypt customer data in a database with 500 million...": https://scrivio-interview-library.netlify.app/spring-boot/secrets-and-crypto/8db20ce096/