▚ The Software Engineer's Field Manual
Chapter E8 · Database operations

Databases in Production — The Operations Primer

"Every application is a thin wrapper around a database. Interviewers know it — that is why the database questions never stop."

4 primer chapters + 200 drill questions Engines: MySQL/InnoDB & PostgreSQL, differences called out Heavy on: isolation · repeatable read · indexes · 3am operations

01 · Why this primer existsYou Use a Database Daily — Nobody Ever Taught You Its Insides

Almost every slow query, deadlock and stale read comes from four things: what a transaction really guarantees, which anomalies your isolation level still allows, how an index is actually shaped, and who is holding a lock.

Nine years into a backend career you have written thousands of queries, and yet the senior interview keeps finding the gap: what exactly does repeatable read repeat? Why did the planner ignore your index? What would you actually do, in order, when the database "is slow" at 3am? These are not trick questions.

They probe whether you understand the machine your code leans on hardest — and they are answerable from a small set of ideas this primer teaches in plain words: the transaction log, snapshots and row versions, the B+tree, and the lock table.

The page has two halves. The primer (sections 02–05) teaches the internals honestly — transactions and ACID, isolation levels and MVCC with repeatable read given the deep treatment it deserves, indexes and how to read a query plan, then locks, connection pools, and replication.

Both engines you will actually meet are covered: MySQL's InnoDB and PostgreSQL, with their real differences called out instead of papered over.

The drill (sections 06–09) is 200 interview questions — direct questions and production scenarios, every answer collapsed behind a Reveal answer control so you commit before you check. Read the primer first; the drill assumes it.

The format and the say-it-aloud method are the same as the Java Interview Drill in Chapter E3, which covers the application side of the same story — pools, ORMs, and tuning from the Java end.

02 · The primerTransactions & ACID, In Plain Words

A transaction is a group of statements that either all happen or none do. The database keeps that promise by writing what it intends to do before it does it.

You have written @Transactional thousands of times. This section is what that annotation buys you, one layer down. A transaction is a group of statements the database treats as a single unit: either every statement takes effect, or none do. There is no third outcome. Keeping that promise while juggling hundreds of concurrent connections — on a server that might lose power at any millisecond — is most of what a database engine is.

The classic guarantee bundle is ACID. One concrete scenario makes each letter obvious: move $100 from Alice's checking account (balance $500) to her savings account (balance $200) — two UPDATE statements, subtract from one row, add to another.

How the database survives a crash mid-transaction

Here is the trick behind atomicity and durability. The database does not write your changes straight into the big table files — those pages live at scattered disk positions, and a crash mid-rewrite would corrupt them.

Instead, every engine keeps an append-only file called the write-ahead log, or WAL (MySQL calls its version the redo log). Before any change counts, the engine appends a short note to this log: "transaction 4812 changed row 77 of accounts from 500 to 400".

Appending to the end of one file is the fastest thing a disk can do.

When you say COMMIT, the engine forces your log entries onto the physical disk before replying "OK", using the operating-system call fsync — "do not return until this data is really on the disk, not just in a memory buffer". Once that returns, your transaction is durable, even though the table pages themselves may still be old on disk; the engine rewrites those lazily, whenever convenient.

The crash cases now fall out naturally. Server dies after commit, before the pages were rewritten: recovery replays the log — the redo pass ("the log says row 77 should be 400; the page says 500; fix it").

Server dies mid-transaction: recovery runs the undo pass — every change from a transaction that never logged a commit record is reversed. InnoDB keeps explicit undo records (the old values) for this.

PostgreSQL reaches the same place differently: it never overwrites a row — it writes a new version beside the old one — so "undoing" just means never treating the uncommitted versions as visible. That design choice returns twice more (MVCC, and VACUUM).

ROLLBACK is the same undo machinery invoked on purpose: reverse the changes, release the locks, and nobody ever saw a thing.

A transfer, spelled out

Step-by-step: what transfer.sql does, in plain English
  1. BEGIN opens a transaction, suspending autocommit until COMMIT or ROLLBACK.
  2. The first UPDATE subtracts 100 from checking: the engine writes an undo record (old value 500), a redo log entry (new value 400), and takes an exclusive lock on the row.
  3. The balance >= 100 condition makes the debit match zero rows if funds are short; the application checks the affected-row count and rolls back on 0 — avoiding a race between "read balance" and "write balance".
  4. The second UPDATE adds 100 to savings — same bookkeeping, second row lock.
  5. COMMIT forces the log to disk with fsync and releases both locks. Only now does anyone else see either change — and they see both together.
transfer.sql
BEGIN;

UPDATE accounts
   SET balance = balance - 100
 WHERE id = 1            -- Alice's checking
   AND balance >= 100;   -- refuse to go negative

-- application checks: did that update exactly 1 row?
-- if 0 rows: ROLLBACK and report "insufficient funds"

UPDATE accounts
   SET balance = balance + 100
 WHERE id = 2;           -- Alice's savings

COMMIT;

Autocommit — the setting that silently shapes everything

Here is the part many senior engineers have never been told: you are always in a transaction. If you never say BEGIN, the database wraps each statement in its own tiny transaction and commits it immediately. This mode is autocommit, and it is the default in MySQL, in PostgreSQL, and in JDBC. Every single-statement UPDATE you have ever run was a complete ACID transaction with its own fsync.

That default cuts both ways. Scenario one — death by 50,000 commits. A batch job inserts 50,000 rows in a loop, autocommit on: 50,000 separate transactions, each commit waiting on an fsync of 1 to 2 milliseconds.

The arithmetic: 50,000 × 1.5 ms ≈ 75 seconds spent doing nothing but forcing tiny log writes to disk.

Wrap the loop in one BEGIN…COMMIT and the job pays for one fsync at the end; the inserts stream into the log back to back and finish in seconds. A 10× to 50× speedup, and the first thing to check when "the nightly job is slow".

Scenario two — the opposite sin. Someone wraps a four-hour migration in one giant transaction. Now every lock it takes is held to the very end, blocking other writers for hours.

Undo information (or old row versions) must be preserved for every row touched — and in Postgres a long-open transaction pins old row versions across the whole database, because VACUUM cannot remove anything your snapshot might still need.

If the job fails at hour three, you roll back three hours of work. The professional answer is the middle: batch your commits — one COMMIT every 1,000 to 10,000 rows — so each transaction is short, restartable, and cheap, without paying an fsync per row.

One paragraph on savepoints: a savepoint is a named bookmark inside an open transaction. SAVEPOINT before_risky; marks the spot; if a later statement fails, ROLLBACK TO SAVEPOINT before_risky; undoes only the work after the bookmark, leaving the earlier part intact and still uncommitted. It is partial undo, never partial commit — nothing is durable until the final COMMIT. Frameworks build "nested" transactions on savepoints, and Postgres users need them for a quirk: after any error, a Postgres transaction refuses all further statements until you roll back — to a savepoint, or all the way.

03 · The primerIsolation Levels, Repeatable Read & MVCC

Isolation levels are a dial between correctness and concurrency. Each setting names exactly which anomalies it still permits — so the question is never “is this safe?” but “which anomaly can still happen here?”

This is the heart of the primer, and the topic that separates people who have used databases from people who understand them.

The question isolation answers: when two transactions run at the same time on the same data, what may each one see of the other's unfinished work? Perfect isolation — every transaction behaving as if it ran alone — is expensive.

So databases offer a dial with four positions, each permitting certain well-named glitches, called anomalies, in exchange for speed. Learn the anomalies first; the levels are just labels for which anomalies they forbid.

All walkthroughs use the same setup: an accounts table, one row with id = 1 and balance = 100, and two database sessions — two terminal windows, Session A and Session B — with statements interleaved in time from top to bottom.

Anomaly 1 — dirty read: seeing money that never existed

Step-by-step: what dirty-read.sql does, in plain English
  1. Session A changes the balance to 80 but does not commit — the change is A's private, unfinished work.
  2. Session B, at the weakest isolation level, reads the row and sees 80 — a value never committed.
  3. Session A rolls back. The 80 is erased; the committed balance was 100 all along.
  4. Session B has acted on a number that officially never existed. That is a dirty read.
dirty-read.sql
-- Session A                              -- Session B
BEGIN;
UPDATE accounts SET balance = 80
 WHERE id = 1;      -- NOT committed
                                          SET TRANSACTION ISOLATION LEVEL
                                            READ UNCOMMITTED;
                                          SELECT balance FROM accounts
                                           WHERE id = 1;   -- returns 80 (!)
ROLLBACK;           -- the 80 never happened
                                          -- B made a decision using
                                          -- a value that was never real

Read the interleaving slowly: B saw A's uncommitted write, and then that write was cancelled. Any decision B made was based on fiction. This only happens at READ UNCOMMITTED, and in practice you will almost never meet it: PostgreSQL refuses to do dirty reads even if you ask (it silently gives you READ COMMITTED instead), and nobody sane runs MySQL there.

Anomaly 2 — non-repeatable read: the answer changed mid-transaction

Step-by-step: what non-repeatable-read.sql does, in plain English
  1. Session A, at READ COMMITTED, reads the balance: 100.
  2. Session B updates it to 80 and commits — fully legal, committed data.
  3. Session A, inside the same transaction, reads again — and gets 80.
  4. Same question, same transaction, two answers. That is a non-repeatable read: no fiction, just a moving target.
non-repeatable-read.sql
-- Session A (READ COMMITTED)             -- Session B
BEGIN;
SELECT balance FROM accounts
 WHERE id = 1;      -- returns 100
                                          BEGIN;
                                          UPDATE accounts SET balance = 80
                                           WHERE id = 1;
                                          COMMIT;
SELECT balance FROM accounts
 WHERE id = 1;      -- returns 80 now
COMMIT;             -- same query, same txn,
                    -- two different answers

Why it matters: if A is a report reading the balance once for a header and once for a totals line, the two lines disagree — the report is internally inconsistent even though every value it printed was, at some instant, true. READ COMMITTED permits this: each statement sees the latest committed data as of that statement. REPEATABLE READ, as the name promises, forbids it.

Anomaly 3 — phantom read: rows that appear out of nowhere

Step-by-step: what phantom-read.sql does, in plain English
  1. Session A counts accounts with a balance over 50: 3.
  2. Session B inserts a new account with balance 500 and commits.
  3. Session A repeats the identical count in the same transaction: 4.
  4. No existing row changed — a new row appeared inside A's search condition. That new row is the "phantom".
phantom-read.sql
-- Session A                              -- Session B
BEGIN;
SELECT COUNT(*) FROM accounts
 WHERE balance > 50;   -- returns 3
                                          BEGIN;
                                          INSERT INTO accounts (id, balance)
                                          VALUES (99, 500);
                                          COMMIT;
SELECT COUNT(*) FROM accounts
 WHERE balance > 50;   -- returns 4: a
COMMIT;                -- "phantom" row appeared

The distinction from anomaly 2 sounds academic until you see why it is hard to fix: stopping a non-repeatable read only requires protecting rows you already touched. Stopping a phantom requires protecting rows that do not exist yet — locking the gap where a matching row could be inserted. Hold that thought; it explains a famous InnoDB behavior below.

The two anomalies the textbook table forgets

Lost update. Two transactions read the same value, both compute a new value from it in application code, and both write back. The second write silently overwrites the first — one update is simply gone, and no error is raised at the common levels, because the database saw two perfectly valid UPDATEs. This is the most common real-world concurrency bug, and it is the Brain Power below — try it before reading on.

🧠 Brain power

Before reading on: Sessions A and B both run this sequence on the same row, interleaved: read balance (both see 100), compute balance - 20 in application code, write 80 back, commit. Both commits succeed. What is the final balance, what should it be, and which tools in this section would have saved you — at which isolation level?

Reveal the answer

The final balance is 80. It should be 60 — two $20 deductions happened, but B's write of 80 lands on top of A's, and one deduction is lost. READ COMMITTED lets this through in every engine: each write was individually legal.

PostgreSQL REPEATABLE READ saves you — the second committer gets "could not serialize access due to concurrent update", and the retry re-reads 80 and correctly writes 60.

MySQL REPEATABLE READ does not: plain reads come from a snapshot, and the writes do not conflict in a way InnoDB rejects.

The application-level fixes work everywhere: SELECT … FOR UPDATE before reading (the second reader blocks, then sees 80), an optimistic version-column check (the second UPDATE matches 0 rows; retry), or best of all one atomic statement — UPDATE accounts SET balance = balance - 20 WHERE id = 1 — which reads and writes under one row lock and cannot lose anything.

Write skew — the on-call doctors. A hospital rule: at least one doctor must be on call. Tonight Alice and Bob both are, and each opens a transaction to sign off.

Each runs SELECT COUNT(*) … WHERE on_call = true, sees 2, concludes "someone else is still on call, I may leave", and sets its own row to on_call = false. Both commit. Zero doctors on call.

Notice why every cheap defense fails: the transactions wrote different rows, so there is no write-write conflict to detect, and each snapshot was genuinely consistent — the reads skewed the writes, hence the name.

Only full SERIALIZABLE isolation (or explicitly locking both rows, or a constraint the database can check) catches it. This is the standard interview probe for "do you know why snapshot isolation is not serializability" — keep it in your pocket.

The four ANSI levels — what each one forbids

The ANSI SQL standard (ANSI — the American National Standards Institute, whose SQL committee defined these levels in 1992) names four isolation levels by which anomalies they rule out:

Isolation levels × anomalies: what can still go wrong at each level.
LevelDirty readNon-repeatable readPhantom readLost updateWrite skew
READ UNCOMMITTEDpossiblepossiblepossiblepossiblepossible
READ COMMITTEDpreventedpossiblepossiblepossiblepossible
REPEATABLE READpreventedpreventedmostly prevented — engine detail belowPostgres: aborted with an error · MySQL: still possiblepossible
SERIALIZABLEpreventedpreventedpreventedpreventedprevented

Two honest notes. First, ANSI's REPEATABLE READ technically allows phantoms — but both engines you care about do better than the standard requires, in different ways, covered below. Second, the last two columns are the ones textbook tables omit, and they are where real bugs live: no level short of SERIALIZABLE fully protects a read-then-write-back pattern by itself.

MVCC — how readers stopped blocking writers

How does a database give every transaction a stable view without freezing all writes? The answer in both PostgreSQL and InnoDB is MVCC — multi-version concurrency control. In plain words: the database keeps multiple versions of each row.

An UPDATE does not destroy the old value; it creates a new version stamped with the id of the transaction that made it, and the old version sticks around.

(Postgres literally leaves the old row in the table file; InnoDB keeps the newest version in the table and rebuilds older ones from its undo log.)

Every transaction gets a snapshot — a note saying "these transactions had committed when you started; those had not". On every read, the engine walks the row's version history and serves the newest version visible to that snapshot, ignoring versions committed later or never. At READ COMMITTED the snapshot refreshes per statement; at REPEATABLE READ one snapshot holds for the whole transaction. That single sentence is the difference between the two levels.

The payoff: readers never block writers, and writers never block readers. A ten-minute analytics query can scan a table while thousands of updates land on it — it just keeps reading the versions its snapshot can see. Locks are only needed when two transactions want to write the same row.

10:00 v1 commits 10:02 A begins 10:05 v2 commits 10:07 B begins Version 1 · balance = 100 committed 10:00 Version 2 · balance = 80 committed 10:05 points to older version Transaction A snapshot taken 10:02 Transaction B snapshot taken 10:07 still reads 100 reads 80
Fig. E8.1 — MVCC keeps both versions of the row. Transaction A's snapshot predates version 2, so A keeps reading balance = 100 even after 10:05 — without blocking the writer. Transaction B, starting later, sees version 2.

REPEATABLE READ, honestly, in both engines

Interviewers love this level because the two big engines implement it differently, and the differences are where production bugs hide.

MySQL / InnoDB — the default level. A plain SELECT reads from a consistent snapshot taken at your first read, so anomalies 2 and 3 never appear in plain reads.

The honest part: UPDATE, DELETE, and SELECT … FOR UPDATE are "current reads" — they do not use your snapshot. They see, and lock, the latest committed rows.

So you can SELECT a row and see the old value, then UPDATE it and modify a newer value your SELECT never showed you — and rows inserted after your snapshot, invisible to your SELECTs, can still be caught by your UPDATE's WHERE clause.

It feels like gaslighting until you know the rule: reads see the snapshot; writes see the present.

For locking reads, InnoDB stops phantoms with next-key and gap locks — locks on the empty ranges between index entries that block other sessions from inserting there (the cost comes up in the next section).

PostgreSQL. The default is READ COMMITTED, not REPEATABLE READ — worth saying twice, because people assume the engines match.

Ask Postgres for REPEATABLE READ and you get what the literature calls snapshot isolation: one snapshot for the entire transaction, used by reads and writes, so phantoms cannot happen at all.

The price: updating a row that another transaction changed and committed after your snapshot aborts you with ERROR: could not serialize access due to concurrent update.

That is not a bug — it is the level working as designed, and your application must catch it and retry the transaction. Postgres SERIALIZABLE goes further (serializable snapshot isolation) and additionally aborts write-skew patterns like the doctors — again resolved by retrying.

Taking control: pessimistic vs optimistic locking

When read-then-write-back is unavoidable — load an entity, let a user edit it, save it — you choose one of two disciplines.

Pessimistic locking assumes conflict is likely and locks up front: SELECT … FOR UPDATE takes an exclusive row lock at read time, so any other transaction wanting the row waits until you commit.

Nobody loses an update; the cost is that waiters queue, and locks held across slow work (or, catastrophically, user think-time) throttle the system.

Optimistic locking assumes conflict is rare and verifies at write time: add a version column, read it with the data, and make your UPDATE conditional on the version being unchanged.

Step-by-step: what optimistic-lock.sql does, in plain English
  1. The read grabs the row plus its version number, 7. No locks held — the user can think for ten minutes.
  2. The write updates the row only if the version is still 7, bumping it to 8 in the same statement — check and change are atomic because a single UPDATE locks the row while it runs.
  3. The application inspects the affected-row count: 1 means success; 0 means someone committed version 8 first, so re-read and retry or report a conflict.
  4. This is exactly the SQL that JPA's @Version annotation generates for you.
optimistic-lock.sql
-- read (no lock held afterwards)
SELECT id, balance, version
  FROM accounts
 WHERE id = 1;              -- say it returns version = 7

-- ... application / user computes the new state ...

-- conditional write: succeeds only if nobody else won the race
UPDATE accounts
   SET balance = 80,
       version = version + 1
 WHERE id = 1
   AND version = 7;

-- affected rows = 1  -> success
-- affected rows = 0  -> conflict: re-read and retry

Read the outcome carefully — the affected-row count is the output here. 1 row means your view of the world was still current when you wrote. 0 rows is not a database error — it is your signal that a concurrent writer got there first, and the retry loop is your responsibility. The decision table at the end of this module summarizes when to reach for each discipline.

04 · The primerIndexes & Reading Query Plans

An index is a sorted structure that turns a full scan into a short walk down a tree. Reading the query plan is how you find out whether yours is being used at all.

The B+tree, with real numbers

Almost every index you have ever created is a B+tree. Strip the jargon and it is two ideas.

One: keep the keys sorted, packed into fixed-size pages (a page is the unit the database reads from disk in one go — 16 KB in InnoDB, 8 KB in Postgres).

Two: build a short path down to any page — a tree whose upper-level pages hold only boundary keys ("keys below 250 go left, 250 and above go right") and pointers one level down.

The bottom level, the leaf pages, holds the actual entries in order, each leaf linked to the next, so range scans just walk sideways.

Now the numbers, because they are the whole point. One 16 KB internal page holds on the order of 1,000 key-plus-pointer entries, so each level multiplies your reach by about 1,000 — the fanout. One level: 1,000 rows. Two: one million. Three: one billion.

Conclusion: finding one row among a billion takes about four page reads — root, two internals, one leaf. And since the root and internal levels are tiny, they live permanently in the buffer cache, so the real disk cost is typically one read: the leaf.

That is why point lookups stay fast as tables grow — capacity grows a thousandfold per level, so depth grows by one when the table grows a thousandfold.

250 | 620 root — read 1 80 | 170 310 | 470 read 2 80 · 120 · 170 200 · 210 · 240 310 · 327 · 410 470 · 480 · 610 leaf — read 3: key 327 found leaves linked in sorted order — range scans walk sideways 327 > 250 310 ≤ 327 < 470
Fig. E8.2 — Searching a B+tree for key 327: three page reads, root to leaf. Each level multiplies reach by the fanout, so even a billion keys sit only three or four levels deep.

Clustered vs secondary — where the row actually lives

What is in the leaf? Here the engines split. In InnoDB, the table is a B+tree — the one built on the primary key, with the entire rows in its leaves. This is a clustered index: data physically stored in primary-key order. Every other index — a secondary index — is a separate B+tree whose leaves store the indexed values plus the row's primary key. A secondary lookup is therefore a double lookup: descend the secondary tree to find the primary key, then descend the primary-key tree to find the row. Two interview-worthy consequences: a fat primary key (a 36-character UUID string, say) is copied into every secondary index and bloats them all; and random-order keys like UUIDs scatter inserts across the clustered tree instead of appending at the right edge, causing constant page splits.

Postgres has no clustered index. The table is a heap — rows sit wherever there is free space, in no order. Every index, the primary key's included, is a separate B+tree whose leaves store a physical row address (page number plus slot); every lookup is descend-the-tree, then jump to the heap page. Neither design simply wins: InnoDB makes primary-key lookups and ranges very cheap; Postgres makes all indexes equal citizens and never pays the double descent.

Composite indexes and the leftmost-prefix rule

An index on two columns — say (last_name, first_name) — is one B+tree sorted like a phone book: by last name, then by first name within the same last name. The analogy does all the work. Find everyone named Shah? Yes — the Shahs are contiguous.

Everyone named Shah, Priya? Yes — sorted within the Shahs. Everyone whose first name is Priya? No — Priyas are scattered across every surname; you would read the whole book.

That is the leftmost-prefix rule: a composite index serves queries that constrain its columns starting from the left, with no gaps.

Worked example against INDEX (last_name, first_name): WHERE last_name = 'Shah' — uses it. WHERE last_name = 'Shah' AND first_name = 'Priya' — uses both columns, best case. WHERE last_name = 'Shah' ORDER BY first_name — filter and free ordering, no sort.

WHERE first_name = 'Priya' — cannot use it at all.

One subtle case: WHERE last_name > 'S' AND first_name = 'Priya' descends for the range on last_name, but across many surnames the first_name condition can no longer navigate the tree — it degrades to a filter on each visited entry. The rule of thumb that follows: equality columns before range columns.

One more named trick: if the index leaves contain every column the query needs, the engine never visits the table at all. That is a covering index — the plan says Using index (MySQL) or Index Only Scan (Postgres) — and adding one column to make a hot query covering is often the cheapest optimization available.

Selectivity — why the planner ignores your index

An index is only worth using when it is selective — when the condition narrows the table to a small fraction. Concrete numbers: a status column over 10 million rows, 95% of them 'active'.

For WHERE status = 'active' the planner refuses the index and scans the table, and it is right: the index route means roughly 9.5 million random jumps between index and table pages, while a sequential scan reads in order — the pattern disks and read-ahead love.

An index matching more than a few percent of a table is often slower than scanning. The planner decides using statistics about your data distribution — which is why stale statistics (next section) produce insane plans.

The classic index killers — each defeats the tree for the same reason: the index is sorted on the raw column value:

Finally, the cost side of the ledger: every index is another B+tree updated on every INSERT, every DELETE, and every UPDATE touching its columns. Six indexes mean one logical row write fans out into up to seven tree modifications, plus occasional page splits. Indexes are not free reads — they are purchased with writes. So review real query patterns before adding one, and periodically drop the ones nothing uses.

Reading query plans — the same query, both engines

The query plan is the database explaining exactly how it intends to fetch the data, and reading plans is the debugging superpower of this module. Same example in both engines: orders has 2 million rows and a composite index idx_customer_status (customer_id, status).

explain-mysql.sql
EXPLAIN SELECT id, total_amount
          FROM orders
         WHERE customer_id = 42 AND status = 'PAID'\G

*************************** 1. row ***************************
           id: 1
  select_type: SIMPLE
        table: orders
   partitions: NULL
         type: ref
possible_keys: idx_customer_status
          key: idx_customer_status
      key_len: 51
          ref: const,const
         rows: 12
     filtered: 100.00
        Extra: NULL

Read the output, field by field. type: ref is the access method — check it first: ref means "descend an index for an equality match", which is good. The values to fear are ALL (full table scan) and index (scan the entire index); range is fine, const and eq_ref are excellent. key confirms which index won, out of the candidates in possible_keys. key_len: 51 encodes how many bytes of the composite key are usable — here both columns; a smaller number would be your clue that the leftmost-prefix rule cut you off. rows: 12 is the optimizer's estimate of rows to examine — 12 out of 2 million is what a healthy index lookup looks like. Extra is where warnings live: Using filesort (a sort the index did not provide) and Using temporary are the costly ones; Using index would be good news — the covering-index case.

explain-postgres.sql
EXPLAIN ANALYZE SELECT id, total_amount
                  FROM orders
                 WHERE customer_id = 42 AND status = 'PAID';

                              QUERY PLAN
------------------------------------------------------------------
 Index Scan using idx_customer_status on orders
   (cost=0.43..24.50 rows=12 width=14)
   (actual time=0.031..0.058 rows=11 loops=1)
   Index Cond: ((customer_id = 42) AND (status = 'PAID'::text))
 Planning Time: 0.180 ms
 Execution Time: 0.084 ms

Read the output. The node name, Index Scan, is the access method: descend the index, fetch each matching row from the heap. The alternatives: Seq Scan (read the whole table — correct for unselective queries, alarming for selective ones), Index Only Scan (covering — never touches the heap), and Bitmap Heap Scan (collect index matches first, then visit heap pages in physical order — the middle gear). Index Cond shows both columns used inside the descent — a condition appearing on a separate Filter: line instead would mean the index was not serving it. Because we used ANALYZE, the query really ran, and the parenthesized pairs are the crown jewels: rows=12 is the planner's estimate, actual … rows=11 is reality. Those agreeing is the health check — an estimate off by 100× means the planner chose its strategy from a wrong map, and the fix is usually refreshing statistics, not adding indexes. loops=1 says the node ran once; in a nested-loop join you might see loops=50000, and every per-loop number must be multiplied by it — the classic way a cheap-looking inner lookup turns out to be the whole query's cost. Execution Time is the measured ground truth.

05 · The primerLocks, Connection Pools & Replication

Three things decide whether a healthy query stays healthy under load: who holds which lock, how many connections you allow, and how far behind your replicas are.

Locks: the vocabulary in four sentences

A row lock protects one row; a table lock freezes the whole table — modern engines lock rows for normal writes and reserve table locks for schema changes and maintenance.

A shared lock ("read lock", S) says "I am reading this — you may read too, but nobody may change it"; many transactions can hold one on the same row.

An exclusive lock ("write lock", X) says "I am changing this — nobody else may lock or write it"; only one holder at a time.

Thanks to MVCC, plain reads take no row locks — locks are a conversation among writers, plus readers who opt in with FOR UPDATE or FOR SHARE.

When a transaction wants a lock another holds, it enters a lock wait: it queues until the holder commits or rolls back. InnoDB gives up after innodb_lock_wait_timeout (default 50 seconds); Postgres waits forever unless you set lock_timeout. Lock waits are normal in small doses — a spike of them is your first symptom that some transaction holds locks too long.

Deadlocks: a cycle, a detector, a victim

A deadlock is a different animal: two transactions each hold a lock the other needs — a cycle no amount of waiting can break. The classic interleaving, with our two account rows:

Step-by-step: what deadlock.sql does, in plain English
  1. Transaction 1 updates row 1, taking an exclusive lock on it.
  2. Transaction 2 updates row 2 — no conflict yet, different rows.
  3. Transaction 1 tries to update row 2 and blocks, waiting for Transaction 2's lock.
  4. Transaction 2 tries to update row 1 — each now waits for the other: a cycle.
  5. The deadlock detector spots the cycle (InnoDB immediately; Postgres after a one-second wait), picks the victim that has done the least work, and kills it with an error so the survivor proceeds. The victim's application must catch the error and retry.
deadlock.sql
-- Transaction 1                          -- Transaction 2
BEGIN;                                    BEGIN;
UPDATE accounts SET balance = balance-10
 WHERE id = 1;   -- locks row 1
                                          UPDATE accounts SET balance = balance-10
                                           WHERE id = 2;   -- locks row 2
UPDATE accounts SET balance = balance+10
 WHERE id = 2;   -- waits for T2 ...
                                          UPDATE accounts SET balance = balance+10
                                           WHERE id = 1;   -- waits for T1: CYCLE
-- one of them receives:
-- ERROR 1213 (40001): Deadlock found when trying to get lock;
--                     try restarting transaction

Read the outcome: the database is not broken — deadlock detection working is the system behaving correctly, and the error message names the remedy ("try restarting transaction"). Two interview-ready lessons. First, deadlocks cannot be fully prevented in a busy system, so every transaction-running code path needs retry logic. Second, they can be made rare by consistent lock ordering: if every transaction locks rows in the same order (say, ascending id — always row 1 before row 2), a cycle is geometrically impossible, because all the arrows point the same way. Short transactions are the other half of the medicine: locks held 10 milliseconds rarely collide; locks held 10 seconds collide constantly.

One honest paragraph on gap locks, which generate the deadlocks nobody understands.

Under REPEATABLE READ, a locking read or UPDATE/DELETE over a range makes InnoDB lock not just the matching index entries but the gaps between and around them (a next-key lock is "entry plus the gap before it").

Why: the phantom problem — the only way to stop new rows from materializing inside a locked range is to lock the empty space itself.

Consequence: inserts into a gap someone else has range-scanned will block, and two sessions holding overlapping gap locks while inserting is a famous deadlock recipe. This largely disappears at READ COMMITTED — one reason high-write MySQL shops deliberately run there.

Connection pools — the multiplication that takes sites down

A database connection is expensive to open: a TCP handshake, TLS negotiation, authentication, and — in Postgres — a whole operating-system process forked to serve it, with private working memory for sorting and joining. Milliseconds of setup and megabytes of memory per connection: that is why every serious application keeps a connection pool — connections opened once and lent to request threads, exactly what HikariCP does in your Java services. It is also why the database enforces a hard ceiling, max_connections — Postgres defaults to 100, and raising it is not free, because each allowed connection reserves server resources whether used or not.

Now the fleet math that has taken down real companies. Each app instance carries a modest pool of 20. You autoscale to 30 instances. 30 × 20 = 600 connections against a database configured for 100.

Deploys and spikes turn this into a connection storm: new instances fail to connect, health checks fail, the orchestrator starts more instances, and the multiplication worsens. Two fixes, usually combined.

Shrink per-instance pools ruthlessly — a database only truly executes about as many queries in parallel as it has CPU cores, so HikariCP's own guidance of roughly cores × 2 total means a pool of 10 or less per instance is often plenty; beyond that, extra connections just queue inside the database.

And put a shared pooler between fleet and database — PgBouncer or RDS Proxy for Postgres, ProxySQL for MySQL — so 600 application-side connections funnel into a few dozen real ones.

Replication — one primary, lagging copies

Replication means the primary server streams its write-ahead log to one or more replica servers, which replay it and hold a continuously-updated copy. Reads spread across replicas; all writes go to the primary. The default mode everywhere is asynchronous: the primary commits and answers the client without waiting for any replica. That keeps commits fast, and creates the gap you must design for: replication lag — the replica runs behind by milliseconds normally, but seconds or worse under heavy writes or replay stalls.

Scenario — the disappearing edit. A user renames their profile; the write commits on the primary. Their browser immediately refreshes; the load balancer routes that read to a replica lagging two seconds; the page shows the old name.

The user retries, files a bug — and nothing is broken. The violated property has a name: read-your-writes — a user should always see the effects of their own writes.

The routing fixes, ascending in sophistication: send any read that follows a user's write to the primary for a sticky window (5 to 10 seconds, tracked by a cookie or session flag); pin the session to the primary after writes; or record the primary's log position at commit and have the replica read wait until the replica has replayed past it.

The blunt instrument — all logged-in reads to the primary — sacrifices the scaling replicas exist for; the sticky window is the usual pragmatic answer.

One paragraph on the synchrony dial. Semi-synchronous (MySQL) or synchronous (Postgres) replication makes the primary wait at commit for at least one replica to confirm it has received (not necessarily applied) the transaction. The trade: every commit pays a network round trip, and a sick replica can stall commits — in exchange, a primary failure can no longer silently eat acknowledged transactions. Async buys latency; sync buys durability across machine loss; semi-sync with a small replica set is the common compromise for money-touching systems.

Failover, operationally: the primary dies, you promote the most caught-up replica, repoint the application (DNS, a proxy, or service discovery), and — critically — fence the old primary so it cannot accept writes if it comes back to life.

Two servers both believing they are primary is split-brain, and it produces divergent data no tool can automatically merge. Under async replication, failover also means accepting possible loss of the last few seconds of acknowledged writes — the lag window, exactly the risk semi-sync closes.

Interview-ready summary: failover is not a button, it is a rehearsed procedure with a data-loss budget.

Day-2 hygiene: VACUUM, statistics, and the slow-query log

Three maintenance realities keep production databases healthy, and all three trace back to MVCC. First, VACUUM. Postgres never overwrites or truly deletes a row in place — an UPDATE writes a new version, a DELETE just marks the row dead.

Those dead tuples (tuple is Postgres's word for a row version) pile up as invisible garbage in the table files. VACUUM is the garbage collector that reclaims the space; autovacuum is the daemon that runs it for you.

When it falls behind — often because a long-running transaction pins old versions — tables and indexes swell with garbage, a condition called bloat: a "10 GB" table occupying 40 GB, every scan reading 4× the pages it should.

InnoDB's analogous chore is purging old undo records, with the same enemy: long-lived transactions.

Second, ANALYZE and statistics. The planner chooses index-versus-scan and join strategies from stored statistics — row counts, common values, distribution histograms — and ANALYZE refreshes them (autovacuum does this too; MySQL updates statistics automatically). Stale statistics mean the planner navigates with an old map.

The classic incident: bulk-load 10 million rows into a table the statistics still describe as 1,000 rows, and the planner cheerfully picks a nested-loop plan that takes hours.

The estimated-versus-actual gap in EXPLAIN ANALYZE is how you catch it: when rows=1000 estimated meets actual rows=10000000, run ANALYZE before you touch a single index.

Third, the slow-query log — the first tool of every tuning effort, because it replaces guessing with a ranked list.

Postgres: set log_min_duration_statement = 500ms, or better, enable pg_stat_statements, which aggregates every query's total time, call count, and average — sort by total time and the top five entries are usually 80% of your load.

MySQL: enable slow_query_log and digest it with pt-query-digest. The discipline: measure first, then aim everything else in this module — an index here, a shortened transaction there — at the queries that actually matter.

Decision table — pessimistic locking, optimistic locking, or no explicit lock: choose when…
StrategyHow it worksChoose it when…The cost
Pessimistic — SELECT … FOR UPDATE Exclusive row lock at read time; competitors queue until you commit. Contention is genuinely high; the read-to-write span is short and server-side; a failed retry is unacceptable (inventory, seats, money). Waiters pile up behind slow holders; deadlocks still need retry logic; a lock held across user think-time stalls the system.
Optimistic — version column check Read freely with a version number; write conditionally (… AND version = ?); 0 affected rows means conflict — re-read and retry. Conflicts are rare; user think-time sits between read and write (edit forms, REST PUTs, JPA entities); an occasional retry is acceptable. Wasted work on each conflict; retry loops must be written and tested; unfair under heavy contention.
No explicit lock — one atomic statement Express the whole change as a single UPDATE (SET stock = stock - 1 WHERE stock > 0) and let its own row lock do the work. The new value derives from the current value in a way SQL can express; no decision sits between read and write. Always the first option to look for. Only fits changes expressible in one statement.

06 · DrillTransactions, Isolation & Locking — Q1–Q50

Transactions are where senior database rounds are won or lost, because the questions look bookish but the follow-ups are all production war stories.

These fifty questions drill the four guarantees, the exact anomaly each isolation level does and does not stop, the write patterns that survive concurrency, and the locking behavior that causes 2 a.m. pages.

MySQL's InnoDB engine and PostgreSQL disagree on many of these points, so every answer names the engine wherever they differ. Answer out loud before revealing — the reasoning is the answer.

Drill · ACID & durability

These questions test whether you can name, for each guarantee, the concrete failure it prevents and the machinery that delivers it — not just recite four words.

Q1. "Walk me through ACID — and for each letter, give me one concrete failure it prevents."

Reveal answer

The real test Whether each letter comes with a failure story, because reciting the acronym without one is a junior answer.

Strong answer A transaction — a group of statements the database applies as one unit — makes four promises. Atomicity: all of it happens or none of it does.

The failure it prevents: a transfer debits one account, the process crashes, and the credit never runs — atomicity undoes the debit, so money is never half-moved.

Consistency: every committed transaction takes the data from one valid state to another, where "valid" means the declared rules — constraints, foreign keys, checks — plus the application's own invariants. Prevented: an order row pointing at a customer that does not exist.

Isolation: concurrent transactions do not see each other's half-finished work. Prevented: a report reading a transfer mid-flight and counting the same money in both accounts. Durability: once commit returns success, the change survives a crash or power cut. Prevented: a confirmed order that is simply gone after a reboot.

Land it The senior point is that I and D are dials, not absolutes — isolation levels and flush settings let you trade each away, so always say what your system actually runs.

Likely follow-ups
"You said isolation and durability are dials. Which exact settings turn them?"

Isolation is set per session or per transaction. In MySQL I would run SET TRANSACTION ISOLATION LEVEL READ COMMITTED or set the server variable transaction_isolation; in Postgres it is SET default_transaction_isolation or BEGIN ISOLATION LEVEL REPEATABLE READ.

In a Spring service the same knob is @Transactional(isolation = Isolation.READ_COMMITTED). Durability is the flush policy. In InnoDB it is innodb_flush_log_at_trx_commit, where 1 means fsync on every commit and 2 means fsync roughly once a second, plus sync_binlog for the binary log.

In Postgres it is synchronous_commit, where off lets commit return before the write-ahead log reaches disk. Each relaxed value is a stated amount of acknowledged work you agree to lose on a crash, so I always name the current values before I discuss guarantees.

"Which of the four letters is the application partly responsible for, and why?"

Consistency. The database can only enforce the rules I declare: primary keys, foreign keys, unique and check constraints, not-null.

Any invariant I did not write as a constraint — "an order total equals the sum of its lines", "at least one doctor is on call" — lives in application code inside the transaction.

If that code has a bug, the database will happily commit an invalid state, because from its point of view every declared rule still holds.

That is why I push as many invariants as possible into the schema, and why I treat a transaction boundary as the unit where the remaining application rules must be re-checked. The other three letters are entirely the engine's job once configured.

"Give me a case where you would deliberately give up one of these guarantees."

Durability is the one most often traded on purpose.

For a metrics or clickstream table where losing the last second of rows on a crash is acceptable, I would set innodb_flush_log_at_trx_commit=2 or Postgres synchronous_commit=off for that session, and commit throughput can rise several-fold because the disk flush is no longer on every commit's critical path.

Isolation is the second one: running READ COMMITTED instead of REPEATABLE READ gives up repeatable reads in exchange for far fewer gap locks and deadlocks in InnoDB.

What I would never trade is atomicity, because a half-applied transaction is a corrupted business fact, and there is no setting that makes that acceptable.

"How would you prove to me that your database actually delivers durability?"

By testing it, not reading about it. I would run a load generator that inserts rows with sequential ids and records every acknowledged commit to a separate machine, then cut power to the database host — a real power pull, not a graceful shutdown.

After restart I compare the highest acknowledged id against what survived. Any acknowledged row that is missing means some layer lied: a relaxed flush setting, a disk with a volatile write cache, or a virtual machine hypervisor that buffers writes.

I would repeat it after each hardware or storage change. This is the only test that catches the storage stack, and it takes an afternoon, which is cheap compared with explaining lost orders to finance.

Q2. "What actually makes a commit durable? Explain the write-ahead log and what fsync buys you."

Reveal answer

The real test Whether you know durability is a specific disk-write protocol, not a vague property of databases.

Strong answer The write-ahead log (WAL) is an append-only file where the database records a description of every change before it touches the actual data pages.

At commit time the engine appends a commit record and calls fsync — the operating-system call that forces those bytes out of memory buffers onto the physical storage medium — and only then tells the client "committed".

The data pages themselves can be written lazily, minutes later, because after a crash the engine replays the log to redo anything that had not reached the data files.

This design works because appending to one sequential file is far cheaper than scattering random page writes, so you get durability at the price of one sequential write per commit.

In InnoDB this is the redo log, governed by innodb_flush_log_at_trx_commit; in PostgreSQL it is pg_wal, governed by synchronous_commit.

Land it Fsync buys exactly one thing — an acknowledged commit exists on stable storage — and every relaxed setting is a decision about how many seconds of acknowledged work you are willing to lose.

Likely follow-ups
"If every commit needs an fsync, how does the database get thousands of commits per second on a disk that does a few hundred fsyncs per second?"

Group commit. When several transactions reach commit at nearly the same time, the engine writes all their log records with a single fsync and then acknowledges all of them together. One disk flush pays for many commits.

InnoDB has done this since 5.6, and Postgres has the same behaviour built in, with commit_delay and commit_siblings to let the leader wait a few microseconds so more followers can join.

The effect is that commit throughput scales with concurrency: one client doing serial commits is limited by fsync latency, but a hundred concurrent clients might all be served by a few hundred fsyncs a second.

That is why a single-threaded import is so slow and a concurrent workload is not.

"What is a checkpoint, and why does it matter for recovery time?"

A checkpoint is the moment the engine writes all dirty data pages — pages changed in memory but not yet on disk — out to the data files and records in the log that everything before this point is safe.

On restart, recovery only needs to replay the log from the last checkpoint forward, so checkpoint frequency bounds recovery time. In Postgres the knobs are checkpoint_timeout, default five minutes, and max_wal_size, which forces a checkpoint when the log grows too large.

In InnoDB it is the redo log capacity, innodb_redo_log_capacity as of 8.0.30. The trade is that frequent checkpoints mean short recovery but more page writes and I/O spikes, which is why Postgres spreads them out with checkpoint_completion_target.

"What does relaxing the flush actually cost me in a crash? Give me the exact loss window for each setting."

With innodb_flush_log_at_trx_commit=1 the loss is zero committed transactions.

With value 2, the log is written to the operating system's file cache at every commit but fsynced about once a second, so a MySQL process crash loses nothing, but an operating system crash or power loss loses up to one second of acknowledged commits.

With value 0, the log is not even written at commit, so even a MySQL crash loses up to a second.

In Postgres, synchronous_commit=off means the commit returns before the WAL is flushed, and the background writer flushes within roughly three times wal_writer_delay, default 200 milliseconds, so the window is about 600 milliseconds.

Crucially, in both engines the data files are never corrupted; you lose whole recent transactions, never fractions of one.

"Why can data pages be written lazily but the log cannot?"

Because the log is the source of truth and the data pages are a cache of it. Once a change is durably in the log, the engine can reconstruct the data page from it after any crash, so there is no urgency in writing the page.

Deferring page writes also lets the engine coalesce many changes to the same page into one write, and write pages in batches at checkpoints instead of one random write per transaction.

The log, by contrast, is the only place the commit exists at the moment of acknowledgement, so it must hit stable storage before the client is told "committed".

That asymmetry is the entire design: one sequential, synchronous write per commit, and all the expensive random writes made asynchronous and batched.

Q3 · Scenario. "A server lost power. After restart, application logs show fifty orders it had confirmed to customers, but the database has only thirty. The DBA swears the database fsyncs every commit. What happened?"

Reveal answer

The real test Whether you know durability is a whole-stack property that hardware can silently break.

Strong answer I would diagnose in this order:

  1. First verify the database really is configured for strict durability: innodb_flush_log_at_trx_commit=1 and sync_binlog=1 in MySQL, or synchronous_commit=on in PostgreSQL. If someone relaxed these for speed — value 2, or off — the database was only flushing about once a second, and losing the last second of "committed" work on power loss is exactly the documented trade. Case closed without blaming hardware.
  2. If the settings are strict, the prime suspect is a lying disk cache: a drive or RAID controller with a volatile write-back cache that acknowledges the flush while the data still sits in cache memory. The database honestly called fsync; the storage stack answered "done" and was not. Power loss wipes the cache, and twenty acknowledged commits evaporate. Check the drive write-cache setting (hdparm -W on Linux), the RAID controller's cache policy, and whether its battery or capacitor backup is present and healthy.
  3. The fix is battery-backed or flash-backed controller cache, or enterprise disks with power-loss protection, or disabling the volatile write cache and paying the latency.
  4. Prevention: test it — run a write workload and pull the plug, then compare acknowledged commits against surviving rows. Storage that survives that test is telling the truth.

Land it The database can only be as honest as the storage below it — fsync is a request, and cheap hardware answers it with a lie.

Likely follow-ups
"The settings are strict and the disks have proper power-loss protection. You still lost twenty orders. What next?"

Then I stop looking at the database and look at the application's definition of "confirmed".

The most common cause is that the service logged "order confirmed" before commit returned — for example inside a Spring @Transactional method, where the log line runs but the commit happens after the method exits.

A crash between the log line and the commit produces exactly this gap. I would check whether the confirmation is emitted after the transaction boundary.

The second suspect is a relaxed durability setting on the connection rather than the server: Postgres allows SET synchronous_commit = off per session, and a pooled connection could carry it. Third, a virtualised disk: hypervisors and some cloud volumes acknowledge flushes into a host cache.

I would run the power-pull test on that exact host to settle it.

"How would you detect a lying disk before the outage, not after?"

Two ways. First, measure fsync latency with a tool like pg_test_fsync or fio with --fsync=1. A spinning disk honestly flushing does at most a few hundred fsyncs per second; an SSD with power-loss protection does a few thousand.

If a device reports fifty thousand fsyncs a second on commodity hardware, it is almost certainly acknowledging into a volatile cache. Second, run the actual crash test on a staging box with identical hardware: write, pull the plug, compare.

I would also inventory the stack: hdparm -I to see the write cache state, the RAID controller's cache policy and battery health, and for cloud volumes the vendor's documented durability. This goes into the runbook so it is rechecked after hardware changes.

"What about the replica — could you have recovered the missing orders from it?"

Only if the replica received them before the primary died, and with asynchronous replication that is not guaranteed.

In MySQL the binlog is what ships to replicas, and if sync_binlog was not 1, the primary may have acknowledged commits whose binlog events were still in memory, so the replica never saw them either.

If sync_binlog=1 and the replica had caught up, the replica might actually hold rows the restarted primary lost, which creates the opposite problem: primary and replica now diverge, and the safe move is to rebuild the primary from the replica.

This is why after any suspected durability loss I compare the replica's data to the primary's before letting writes resume, using GTID positions in MySQL or LSN positions in Postgres.

"If the business cannot afford any acknowledged loss, what does the full setup look like?"

Three layers, and each is a stated cost. On the node: innodb_flush_log_at_trx_commit=1 and sync_binlog=1, or Postgres synchronous_commit=on, on storage with verified power-loss protection.

Across nodes: synchronous replication so the commit is on at least two machines before acknowledgement — MySQL semi-synchronous replication with rpl_semi_sync_source_wait_for_replica_count=1, or Postgres synchronous_standby_names with synchronous_commit=on or remote_apply. And operationally: a tested failover procedure that never promotes a lagging replica, plus periodic crash testing.

The cost is a network round trip added to every commit, typically one to three milliseconds within a region, and availability coupling, because if the synchronous standby dies commits stall until someone reconfigures.

I would put those numbers in front of the business and let them choose.

Q4. "In plain words, how does the database undo half a transaction on rollback? And why is rollback cheap in Postgres but potentially very expensive in InnoDB?"

Reveal answer

Strong answer InnoDB keeps an undo log: before it changes a row, it records the row's old value in a separate structure. Rollback means walking that record backwards and putting every old value back — physically reversing each change.

That is why rolling back a transaction that updated ten million rows can take roughly as long as the update did: the work must be re-done in reverse, and killing a huge migration mid-flight leaves the database busy undoing it for a long time.

PostgreSQL takes the opposite approach: it never overwrites a row in place. An update writes a brand-new row version and leaves the old one where it was.

Rollback is then almost free — the engine just marks the transaction as aborted, and every version it wrote is ignored by all future readers, garbage to be collected later. Same atomicity guarantee, delivered by opposite mechanics with opposite cost profiles.

Land it The operational rule that falls out: in InnoDB, think twice before killing a giant transaction — the rollback bill is the same size as the work.

Likely follow-ups
"So if rollback is nearly free in Postgres, what is the catch?"

The catch is that nothing is undone, so everything the transaction wrote is still physically in the table as dead row versions.

A rolled-back update of ten million rows leaves ten million dead tuples that VACUUM must find and reclaim later, and until it does they bloat the table and its indexes and slow every scan.

So Postgres moves the cost from rollback time to cleanup time and spreads it out. InnoDB pays the full cost up front, synchronously, but leaves the table compact afterwards.

The practical rule I use: in Postgres, watch n_dead_tup in pg_stat_user_tables after any large abort and make sure autovacuum catches up; in InnoDB, budget rollback time before killing anything big.

"You killed a huge InnoDB transaction and now the database is crawling. How do you see rollback progress, and can you stop it?"

I can see it but not stop it. SHOW ENGINE INNODB STATUS lists the transaction with state ROLLING BACK and a count of undo log entries remaining, and information_schema.innodb_trx shows trx_rows_modified going down.

If I restart the server, InnoDB resumes the rollback during crash recovery, so a restart does not escape it; the transaction must be undone before the data can be consistent.

The only real lever is that rollback of a large transaction is often slower than the original because it walks the undo log backwards with less locality.

This is why for bulk changes I commit in chunks of a few thousand rows, so that a kill only ever undoes one chunk.

"Where does InnoDB's undo log physically live, and what happens if it grows without bound?"

In undo tablespaces, files named undo_001 and undo_002 by default as of MySQL 8.0, separate from the table data. Undo records accumulate for two reasons: active transactions that might roll back, and old row versions that some open snapshot might still need to read.

If a transaction stays open for hours, purge cannot trim anything newer than its snapshot, and the undo tablespaces grow.

Historically they never shrank; MySQL 8.0 can truncate them when innodb_undo_log_truncate is on and the tablespace exceeds innodb_max_undo_log_size, default one gigabyte, but only once no transaction needs those records.

The monitoring signal is the "History list length" line in SHOW ENGINE INNODB STATUS; a number in the millions means purge is far behind.

"Does Postgres ever undo anything, then?"

Not row data, no. Postgres records the transaction's status as aborted in the commit log, called pg_xact, and that single status bit is what makes all its row versions invisible.

Later, when a reader encounters one of those rows, it checks the creating transaction's status, sees "aborted", and skips it.

To avoid looking up the status every time, the reader sets hint bits on the tuple header saying "known aborted", which is why the first scan after a big rollback can be slower and can even generate writes.

The one place Postgres does have something like undo is for subtransactions: rolling back to a savepoint marks just that subtransaction's id as aborted, so the rows written after the savepoint disappear while the outer transaction's rows stay valid.

Q5. "Is the C in ACID the same 'consistency' as in 'eventual consistency'?"

Reveal answer

The real test Whether you can untangle a name collision that trips up half the industry.

Strong answer No — it is a name collision between two unrelated ideas. The C in ACID says each transaction preserves the data's declared rules: constraints, foreign keys, and the invariants the application enforces inside the transaction.

It is a property of transactions within a single database, and notably it is partly the application's job — the database can only enforce the rules you declared.

"Eventual consistency" is a distributed-systems property: replicas of the data may disagree for a while after a write, but converge to the same value if writes stop. One is about validity of state inside one system; the other is about agreement between copies across systems.

A single-node PostgreSQL can be perfectly ACID while its read replica serves stale data — those are two different C's coexisting.

Land it In an interview, always say which consistency you mean — conflating them is the fastest way to sound like you learned databases from headlines.

Likely follow-ups
"Give me a concrete example of an application-level consistency rule the database cannot enforce for you."

"A customer's total outstanding balance across all invoices may not exceed their credit limit." That rule spans many rows in one table plus one row in another, and there is no constraint syntax for it in either engine.

The application must read the current sum inside the transaction, compare, and then insert the new invoice, and to be safe under concurrency it must lock the customer row first with SELECT ... FOR UPDATE so two invoices cannot both pass the check.

Another example is "an order may move from SHIPPED to DELIVERED but never back to PENDING", which is a state machine; a check constraint can restrict the set of values but not the transitions. Those rules are the C that ACID leaves to me.

"Does a read replica break the ACID consistency of my Postgres database?"

No, and separating the two ideas answers it. The primary is fully ACID: every transaction that commits there leaves the data valid under all declared rules.

The replica is a physical copy that applies the same write-ahead log a little later, so at any instant it shows a valid state — just an older one.

What breaks is not ACID but the application's expectation of read-your-own-writes: a user creates an order on the primary, the next request reads from the replica, and the order is not there yet.

That is eventual consistency between copies, and the fix is a routing rule — read from the primary for a few seconds after a write, or pin a session to the primary — not an isolation setting.

"Is there a third 'consistency' I should be aware of in this space?"

Yes, the one from the CAP theorem, and it is different again. There, consistency means linearizability: every read returns the most recent write across the whole distributed system, as if there were a single copy.

That is a much stronger statement than eventual consistency and a different kind of statement from ACID's rule-preservation.

So I keep three definitions straight: ACID consistency is "the data obeys the declared rules after each transaction"; eventual consistency is "replicas converge if writes stop"; linearizable consistency is "every read sees the latest write, system-wide".

When an interviewer says "consistency" I ask which one, because a design decision that is right for one is often wrong for another.

Q6. "After a crash, how do redo and undo cooperate during recovery? Can you have atomicity without full durability?"

Reveal answer

Strong answer On restart the engine first replays the write-ahead log forward from the last checkpoint — a periodic marker recording that everything before this point is already safely in the data files.

This redo pass reconstructs every logged change, including changes made by transactions that never finished. Then the undo pass rolls back every transaction that has no commit record in the log, using the undo information, so half-finished work disappears.

Atomicity at crash time is therefore delivered by the same log machinery as durability.

And yes, you can keep atomicity while relaxing durability: with innodb_flush_log_at_trx_commit=2 or synchronous_commit=off, a crash may lose the last second of acknowledged commits entirely — but recovery still guarantees you never see half of any transaction. You lose whole recent transactions, never fractions of one.

Land it That distinction — losing whole transactions versus losing halves — is exactly why async-commit settings are survivable for some businesses and torn writes never are.

Likely follow-ups
"Why replay changes from unfinished transactions at all? Why not just skip them during redo?"

Because the log is physical and interleaved. Records from many transactions are mixed in log order, and a single data page may carry changes from a committed transaction and an uncommitted one that were applied in sequence.

If redo skipped the uncommitted ones, the page's later committed changes might not apply correctly, because they were logged relative to a page state that included the skipped change.

So the engine replays everything in order to reconstruct the exact pre-crash memory state, which is simple and deterministic, and then runs a separate logical undo pass that reverses whole transactions using the undo records.

This "repeat history, then undo losers" approach is the ARIES recovery algorithm, and it is what both InnoDB and, in its own variant, Postgres follow.

"How does the engine know which transactions had committed when the crash happened?"

By the commit record in the log. A transaction is committed if and only if its commit record is on disk before the crash; that is the definition.

During redo the engine builds a table of transactions it has seen and marks those whose commit record appeared. Any transaction with log records but no commit record is a loser and gets undone.

Postgres does this slightly differently: it does not undo rows, it just never marks the transaction as committed in pg_xact, so the rows written by an in-flight transaction at crash time are simply invisible forever and VACUUM cleans them.

In both engines the commit record is the atomic switch, which is why that one record is what fsync protects.

"How long can recovery take, and what controls it?"

Recovery time is roughly proportional to the amount of log written since the last checkpoint, because all of it must be replayed. With Postgres defaults, checkpoint_timeout of five minutes and max_wal_size of one gigabyte, recovery is typically well under a minute.

If someone raised max_wal_size to fifty gigabytes to smooth out I/O, recovery after a crash could take many minutes while the database is unavailable. In InnoDB the equivalent is the redo log capacity; a large innodb_redo_log_capacity gives smoother writes and longer recovery.

Then add undo: in InnoDB, rolling back a huge in-flight transaction happens during recovery, which can dominate. I set these knobs against a stated recovery-time objective, not just for throughput.

"Can a torn page — half written when power failed — be recovered?"

Yes, both engines specifically defend against it.

A torn page is a 16 kilobyte or 8 kilobyte page where only some of the underlying disk sectors were written before power loss, so the page is internally inconsistent and log replay on top of it would produce garbage.

InnoDB uses the doublewrite buffer: it writes each dirty page to a sequential doublewrite area first, then to its real location; on recovery it finds torn pages by checksum and restores them from the doublewrite copy.

Postgres uses full-page writes, controlled by full_page_writes: the first change to a page after each checkpoint logs the entire page image to the WAL, so replay starts from a known-good copy.

Both cost extra write bandwidth, and both are left on unless the storage guarantees atomic page writes.

Drill · Isolation levels & read anomalies

This group tests whether you know which anomaly each level actually forbids in the engine you run — not the textbook table, the real behavior.

Q7. "Name the four standard isolation levels and, precisely, which anomaly each one rules out."

Reveal answer

Strong answer The levels are a ladder of forbidden anomalies. READ UNCOMMITTED forbids nothing interesting — it permits dirty reads, meaning you can see data another transaction has written but not yet committed.

READ COMMITTED forbids dirty reads: you only ever see committed data, but the same row can change between two of your reads.

REPEATABLE READ additionally forbids the non-repeatable read — a row you read once cannot show a different value when you read it again — though the SQL standard still permits phantoms, meaning new rows appearing that match your query.

SERIALIZABLE forbids everything: the outcome must equal some serial, one-at-a-time ordering of the transactions.

Two facts a senior should attach: the defaults differ — InnoDB defaults to REPEATABLE READ, PostgreSQL to READ COMMITTED — and the classic ladder says nothing about lost updates or write skew, which need their own discussion.

Land it The standard defines levels by anomalies, not mechanisms — so the same level name behaves differently in InnoDB and Postgres, and naming the engine is part of a correct answer.

Likely follow-ups
"You said the ladder says nothing about lost updates. Where does the lost update sit on it, then?"

Nowhere in the SQL standard, which is a known gap. The standard's ladder was written for lock-based engines and lists dirty read, non-repeatable read, and phantom.

A lost update — two transactions read a value, both compute from it, and the second write overwrites the first — is not one of those three, so an engine can be standard-compliant at REPEATABLE READ and still lose updates. InnoDB does exactly that.

Postgres's REPEATABLE READ goes further than the standard requires and aborts the second writer, which prevents it.

So when someone says "we run REPEATABLE READ so we are safe from lost updates", the answer depends on the engine, and on MySQL it is simply false; you need SELECT ... FOR UPDATE, an atomic SET x = x + 1, or a version column.

"Why did the standard define levels by anomalies rather than by mechanism?"

To leave implementations free. In 1992 the obvious mechanism was two-phase locking, and the levels mapped to how long read locks were held: not at all, per statement, per transaction, or per predicate.

But defining them that way would have forbidden multi-version designs, which achieve the same anomaly guarantees without read locks. So the standard says what you must not observe, not how to prevent it.

The side effect is that two engines can both call a level REPEATABLE READ while behaving differently on everything the standard did not mention: InnoDB blocks phantoms with gap locks and allows lost updates; Postgres uses snapshots, forbids lost updates, and never takes gap locks.

Naming the engine is part of any correct answer for that reason.

"Which level would you pick as the default for a new Java service on each engine, and why?"

READ COMMITTED on both, and I would set it explicitly in the connection pool so it does not depend on server defaults. On Postgres that is already the default and it gives per-statement snapshots with no serialization retries, which suits short OLTP transactions.

On MySQL it is a deliberate change from the REPEATABLE READ default, and the reason is gap locking: at READ COMMITTED InnoDB stops taking gap locks on ordinary statements, so insert-heavy workloads see far fewer deadlocks and lock waits.

The price is that a multi-statement read that must be internally consistent has to ask for REPEATABLE READ per transaction, and every read-modify-write must use an explicit lock or version check. I would rather pay that per transaction than pay gap locks everywhere.

"Is there anything above SERIALIZABLE?"

Within a single node, no; SERIALIZABLE is the top, meaning the result equals some serial order of the transactions. But it does not say which serial order, and that matters in distributed systems.

Strict serializability adds that the serial order must respect real time: if transaction A committed before B started, A must come before B in the equivalent order. A single-node Postgres SERIALIZABLE is effectively strict serializable because it has one clock and one log.

Distributed databases like Spanner or CockroachDB advertise strict serializability as a feature precisely because with many nodes it costs coordination. For a conventional MySQL or Postgres deployment the distinction does not arise, but it is worth knowing when someone asks about consistency across regions.

Q8 · Scenario. "Give me a concrete sequence where a dirty read actually burns you, and tell me which engines even allow it."

Reveal answer

Strong answer Session A begins a transaction and subtracts 5,000 from a customer's balance as step one of a transfer.

Session B, running at READ UNCOMMITTED, reads that balance mid-transaction, sees it 5,000 lower, and fires a "balance below threshold" alert — or worse, declines the customer's next purchase. Session A then hits an error and rolls back.

B acted on a state of the world that never existed: the money was never really gone. That is a dirty read — reading uncommitted work that may vanish.

Only READ UNCOMMITTED permits it, and in practice only MySQL will actually do it; PostgreSQL accepts the syntax but silently runs READ COMMITTED instead.

The fix is simply to run at READ COMMITTED or above, which costs almost nothing in either engine because multi-version concurrency control (MVCC) — the design where the engine keeps old committed copies of rows so readers never need to peek at in-flight changes — gives you clean reads without any read locks.

Land it With MVCC engines there is no performance excuse left for dirty reads — the anomaly survives only as a legacy of lock-based databases.

Likely follow-ups
"Is there any legitimate use for READ UNCOMMITTED in MySQL?"

One narrow one: a rough progress estimate on a huge running transaction. If a migration is updating fifty million rows in one transaction and I want to know how far it has got, a READ UNCOMMITTED SELECT COUNT(*) ... WHERE migrated = 1 shows the in-flight rows without waiting and without pinning a snapshot.

Some people also use it for approximate counts on tables under heavy write load, though in MVCC that gains nothing over READ COMMITTED. Both uses are read-only, tolerate a wrong answer, and never feed a decision.

Anything that makes a decision — alerting, billing, a UI count a user trusts — must not run there. And it is a MySQL-only conversation, because Postgres silently promotes the level to READ COMMITTED.

"What is the closest thing to a dirty-read bug you can still get at READ COMMITTED?"

Reading a committed-but-logically-incomplete state. Suppose a transfer is written as two separate transactions by mistake: one commits the debit, a second commits the credit.

Between them, a READ COMMITTED reader sees the debit without the credit; that is a fully committed state, so it is not a dirty read, yet it is just as wrong for the reader.

The fix is not an isolation level, it is transaction scope: both writes belong in one transaction. The other near-miss is the non-repeatable read, where a report sums accounts in one statement and lists them in the next, and a commit lands between the two.

Both look like "I saw garbage" in a bug report, and the first question I ask is whether the writer's transaction boundary was right.

"How would you verify what level a MySQL session is actually running, given the ORM and pool in between?"

I would ask the server from inside the application's own connection path. In MySQL, SELECT @@transaction_isolation, @@global.transaction_isolation shows the session and the server default; the session value is what matters and can be changed by the pool or by Spring.

In Postgres it is SHOW transaction_isolation inside the transaction. I would run that through a debug endpoint or a startup log line that executes it on a pooled connection, because a hand-opened console connection goes through none of the layers that might override it.

Hikari's transactionIsolation property, JDBC's Connection.setTransactionIsolation, and @Transactional(isolation=...) can each change it, and only the server can tell me the final result.

Q9 · Scenario. "A reconciliation job runs the same SELECT twice inside one transaction and gets different totals. Name the anomaly, say which levels allow it, and when it actually matters."

Reveal answer

Strong answer That is a non-repeatable read: between the two SELECTs, another transaction committed an update to rows the job had already read, so the second read returns a different answer.

It is allowed at READ COMMITTED — by design, since each statement there sees the latest committed data — and forbidden at REPEATABLE READ and SERIALIZABLE, where the whole transaction reads from one frozen snapshot.

It matters whenever a transaction makes several reads that must describe the same instant: a reconciliation that sums accounts, then lists them, and finds the list disagreeing with the sum; a report whose header totals do not match its detail rows; any read-then-decide logic where the decision assumes the first read still holds.

The fixes, in order of preference: do it in one statement if possible, since a single statement is always internally consistent; otherwise run the transaction at REPEATABLE READ so every read shares one snapshot.

Land it READ COMMITTED is not broken here — it is doing exactly what it promises — the bug is asking a per-statement level to answer a multi-statement question.

Likely follow-ups
"You switched the job to REPEATABLE READ and now on Postgres it occasionally fails with a serialization error. It is a read-only job — why?"

It should not, if it is truly read-only, so my first question is whether it writes anywhere: a status row, an audit log, a progress table.

At Postgres REPEATABLE READ the error could not serialize access due to concurrent update fires only when the job tries to UPDATE or DELETE a row that another transaction changed after the job's snapshot.

A reconciliation job that updates a "last reconciled at" row shared with another process is the usual culprit.

The fixes are to move that write into a separate short transaction after the reads, or to declare the job BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY, which makes any accidental write fail loudly and guarantees the snapshot read cannot hit that error. If it still fails, it is not read-only.

"What does holding one snapshot for a long reconciliation job cost the rest of the system?"

It pins cleanup. Every row version that was live when the snapshot was taken must be kept until the job commits, because the job might still read it.

In Postgres that means VACUUM cannot remove any dead tuple newer than the job's snapshot, so tables the job never touches still bloat if they are updated heavily during the run.

In InnoDB it means the purge threads cannot trim undo records, and the history list length grows, which slows every reader that has to walk longer version chains. For a job that runs ten minutes this is fine.

For one that runs three hours on a busy system it is a real cost, and I would break it into phases that each hold a snapshot briefly, or run it on a replica where the pinned snapshot hurts less.

"Can you get a consistent multi-statement read without changing the isolation level at all?"

Often, by making it one statement. Common table expressions let me compute the total and the detail rows in a single SELECT: WITH t AS (SELECT ...) SELECT ... FROM t, and a single statement always runs against one snapshot at any level, in both engines.

If the two results must go to different destinations, I can still fetch them in one statement and split them in application code.

Another option on Postgres is to export the snapshot: SELECT pg_export_snapshot() in one session and SET TRANSACTION SNAPSHOT in others, which lets several parallel workers all read the same instant, which is how pg_dump --jobs works.

But the honest answer is that REPEATABLE READ per transaction is cheap and explicit, so I would use it rather than contort the query.

"How would you show a sceptical colleague that this really is a non-repeatable read and not a bug in the job?"

With two sessions and a script. In session one I would BEGIN, run the job's SELECT, and note the total. In session two I would update one of the summed rows and commit.

Back in session one, running the same SELECT at READ COMMITTED now shows a different total; at REPEATABLE READ it shows the original. That five-minute demonstration proves the anomaly exists, proves the level controls it, and settles the argument.

Then I would look for it in production evidence: the job's logs should show the two totals and their timestamps, and pg_stat_activity or the binlog would show a committing writer in that interval. Reproducing it deliberately is far more convincing than reasoning about it.

Q10. "Phantom read versus non-repeatable read — what exactly is the difference, and why does the distinction exist at all?"

Reveal answer

The real test Whether you know these need different machinery to prevent — that is the only reason the standard separates them.

Strong answer A non-repeatable read is about rows you already read changing: you read a row, someone else updates or deletes it and commits, you read it again and it differs or is gone.

A phantom is about new rows: your query "all orders over 1,000" runs twice, and the second run returns rows that did not exist the first time, because someone inserted and committed in between.

The membership of the result set changed rather than the contents of known rows. The distinction exists because preventing them requires different machinery. A row you have read is a concrete thing you can lock or version.

A phantom comes from a row that did not exist yet — to prevent it you must lock the range or the predicate, meaning empty space where matching rows could appear. That is exactly what InnoDB's gap locks and Postgres's serializable predicate tracking are for.

Land it Say it as "changed rows versus new rows, and new rows force you to lock what doesn't exist yet" — that one sentence shows you understand why the levels ladder has a rung between them.

Likely follow-ups
"Can Postgres REPEATABLE READ produce a phantom, given the standard permits it at that level?"

No. The standard permits it but Postgres does not produce it, because its REPEATABLE READ is snapshot isolation: every read in the transaction sees the same snapshot, so a row inserted and committed by someone else after the snapshot is not in it, no matter how many times I rerun the query.

The same holds for plain SELECTs in InnoDB at REPEATABLE READ. Where the engines diverge is on locking reads and writes. In InnoDB, SELECT ... FOR UPDATE reads current data, so it could see new rows, and gap locks exist precisely to stop that.

In Postgres, FOR UPDATE also reads current row versions, so a second locking read can find a row the first did not; Postgres accepts that at REPEATABLE READ and only SERIALIZABLE closes it.

"Why is preventing phantoms with locks so much more expensive than preventing non-repeatable reads?"

Because you must lock what does not exist. To stop a row from changing under me I lock that row, which is one lock on one thing.

To stop a row from appearing that would match WHERE amount > 1000, I must lock the entire space where such a row could be inserted — every gap in the index between existing entries in that range — and hold it until I commit.

Any insert anywhere in that range by anyone now waits for me.

On a hot table with wide scanned ranges, that turns concurrent inserts into a queue, and because gap locks are compatible with each other but conflict with inserts, they generate deadlocks that look inexplicable in the lock report.

Snapshot-based prevention avoids all of this for plain reads, which is why MVCC engines only pay it for locking reads.

"Give me a real business bug caused by a phantom rather than a non-repeatable read."

Overbooking with a capacity check. A transaction counts bookings for a flight, sees 199 of 200 seats taken, and inserts one more. A concurrent transaction does the same count, also sees 199, and inserts too.

Neither updated a row the other read, so there is no non-repeatable read; each simply failed to see the other's new row — a phantom in the count. The result is 201 bookings. At READ COMMITTED or snapshot isolation this passes silently in both engines.

The fixes are the same as for write skew: lock the parent row with SELECT ... FOR UPDATE on the flight so the counts serialize, enforce it with a constraint where possible, or run SERIALIZABLE in Postgres, whose predicate tracking would detect this dependency and abort one.

"Does a DELETE by another transaction count as a phantom or a non-repeatable read?"

Strictly, a non-repeatable read, because it changes a row I already read — the standard's definition says a row I read is modified or deleted by another committed transaction.

Some texts classify a vanishing row as a phantom because the result set membership changed, so I would state which definition I am using.

What matters in practice is the mechanism: a deleted row is a concrete thing I could have locked with FOR SHARE or FOR UPDATE, so it is preventable with row locks, and it is invisible under a snapshot. Only inserts need gap or predicate locking.

That is the clean way to split the two: "things I could have locked" versus "things that did not exist yet".

Q11 · Scenario. "MySQL, REPEATABLE READ. Inside one transaction, a SELECT says the row does not exist — but the very next UPDATE on that id reports one row affected. Explain."

Reveal answer

The real test Whether you know InnoDB runs two different kinds of read inside the same transaction.

Strong answer InnoDB's REPEATABLE READ takes a snapshot — a fixed view of what was committed at a point in time — at the transaction's first read, and plain SELECTs answer from that snapshot for the rest of the transaction. But UPDATE, DELETE, and SELECT ...

FOR UPDATE are current reads: they operate on the latest committed data, because you cannot safely modify a stale copy of a row — and they lock what they touch. In this scenario another session inserted the row and committed after my snapshot was taken.

My SELECT reads the snapshot, where the row does not exist. My UPDATE reads the current data, finds the committed row, locks it, and modifies it — one row affected.

Stranger still, a SELECT after the UPDATE now shows the row, because a transaction always sees its own writes layered over the snapshot.

two-sessions-repeatable-read.sql
-- Session A (REPEATABLE READ)          -- Session B
START TRANSACTION;
SELECT * FROM users WHERE id = 42;
-- Empty set. Snapshot taken now.
                                        INSERT INTO users VALUES (42, 'eve');
                                        COMMIT;
SELECT * FROM users WHERE id = 42;
-- Still empty: same snapshot.
UPDATE users SET name = 'x' WHERE id = 42;
-- Query OK, 1 row affected  (current read sees B's commit)
SELECT * FROM users WHERE id = 42;
-- Returns (42, 'x'): own write is now visible.

Land it InnoDB's REPEATABLE READ is really two consistency models stitched together — snapshot for plain reads, latest-committed for writes — and every "impossible" behavior at this level dissolves once you say which read ran.

Likely follow-ups
"Is this a bug in InnoDB, or a design choice?"

A design choice, and a defensible one. If UPDATE worked from the snapshot, it would silently overwrite a newer committed version of the row with a change computed from a stale copy — a lost update built into the engine.

So writes must operate on the latest committed data. The alternative Postgres chose is to detect the situation and abort with a serialization error, which is safer but pushes retry logic onto every application at that level.

InnoDB chose convenience: no retries, but the snapshot and the write can disagree. The important consequence is that at InnoDB REPEATABLE READ you cannot use "I read it, so it is still true" as reasoning before a write.

Any read whose result feeds a write should be a locking read, SELECT ... FOR UPDATE, which is a current read.

"Would this happen at READ COMMITTED as well?"

The visible surprise would not, because at READ COMMITTED every statement takes a fresh snapshot, so the second SELECT would have shown the row once session B committed. The underlying rule is unchanged, though: UPDATE still reads current data and locks what it touches.

The difference is only that at READ COMMITTED there is no long-lived snapshot for the write to disagree with. What you gain in fewer surprises you pay for in weaker guarantees for multi-statement reads.

Also at READ COMMITTED InnoDB drops gap locks on ordinary statements, so the UPDATE here would lock just the one row. If a team is repeatedly bitten by this snapshot-versus-current split, moving to READ COMMITTED is often the pragmatic fix.

"How does Postgres behave in the identical two-session script?"

At Postgres REPEATABLE READ, the first SELECT is empty and takes the snapshot. Session B inserts id 42 and commits. The second SELECT is still empty.

Now the UPDATE: Postgres evaluates it against the snapshot, finds no row with id 42 that it can see, and reports zero rows affected.

No error, because there was no row in my snapshot to conflict on — the serialization error only fires when I try to change a row I could see that someone else changed since.

So Postgres stays internally consistent with the snapshot, and InnoDB stays consistent with the latest data. Neither is wrong, but the code that "checks then updates" behaves differently on each, which is the kind of divergence that surfaces during a migration between engines.

"What is the safe pattern when you need to read a row and then update it inside one transaction?"

Make the read a locking read, so that the read and the write see the same reality. SELECT ... FROM users WHERE id = 42 FOR UPDATE is a current read in both engines: it returns the latest committed version, takes an exclusive lock, and holds it until commit, so nobody can change or delete the row between my read and my write.

If the row does not exist yet and I want to insert it, in InnoDB that locking read also takes a gap lock, which prevents someone else inserting id 42 first — although it can also deadlock if two sessions do it, so for insert-or-update I prefer an INSERT ... ON DUPLICATE KEY UPDATE or a plain insert catching error 1062.

The rule is: never decide based on a snapshot read and then write.

Q12. "How does InnoDB prevent phantoms at REPEATABLE READ without going all the way to SERIALIZABLE?"

Reveal answer

Strong answer With two separate mechanisms, one per kind of read. Plain SELECTs cannot see phantoms because they read the transaction's snapshot — a row inserted after the snapshot simply is not in the picture. Locking reads — UPDATE, DELETE, SELECT ...

FOR UPDATE — are protected differently: InnoDB takes next-key locks, which are a lock on an index record plus the gap before it, where a gap means the empty space between two index entries where new rows would land.

Holding the gap blocks other sessions from inserting into the scanned range, so re-running the locking read cannot find new rows.

The price is real: inserts into a range someone else has scanned must wait, concurrency drops on hot ranges, and gap locks are the raw material of a whole family of deadlocks.

At READ COMMITTED, InnoDB switches gap locking off for ordinary statements, which is one big reason teams choose that level.

Land it The trade in one line: InnoDB buys phantom-free REPEATABLE READ by locking empty space, and locking empty space is exactly what makes concurrent inserts suffer.

Likely follow-ups
"Show me exactly what a next-key lock covers for WHERE id BETWEEN 10 AND 20 FOR UPDATE when rows 10, 15, and 20 exist."

A next-key lock is a record lock plus the gap immediately before that record.

Scanning that range, InnoDB locks the record 10 with the gap below it from the previous key, the record 15 with the gap between 10 and 15, the record 20 with the gap between 15 and 20, and then, because it has to check that no row beyond 20 matches, it locks the gap after 20 up to the next existing key — say 30 — as a pure gap lock.

So inserts of 11, 17, or 25 all block until I commit.

If a unique index is used with an exact equality match, InnoDB downgrades to a plain record lock with no gap, which is why lookups by primary key rarely cause gap contention while range scans and non-unique index lookups often do.

"Which setting would you change to get rid of gap locks, and what do you lose?"

Run the session or the server at READ COMMITTED: SET transaction_isolation = 'READ-COMMITTED'. At that level InnoDB uses only record locks for searches and index scans, so inserts into a scanned range no longer wait and a whole class of deadlocks disappears.

The exceptions are foreign-key checks and duplicate-key checks, which still take gap locks even at READ COMMITTED. What I lose is the per-transaction snapshot, so a multi-statement read is no longer internally consistent, and phantoms and non-repeatable reads become possible for plain SELECTs.

A related requirement is row-based binary logging, binlog_format=ROW, because statement-based replication is unsafe at READ COMMITTED. As of Aug 2026 ROW has been the default since MySQL 5.7.7, so that is usually already true.

"How would you see gap locks in a live system?"

In MySQL 8.0 the table performance_schema.data_locks lists every lock currently held or waited for, with a LOCK_MODE column. X means a next-key lock, X,REC_NOT_GAP means a record-only lock, X,GAP means a gap-only lock, and X,INSERT_INTENTION means an insert waiting on a gap.

data_lock_waits shows who is waiting on whom. The LOCK_DATA column shows the key value, and the special value supremum pseudo-record means the gap after the last key in the index, which is the classic sign of a range scan that ran off the end.

In the deadlock section of SHOW ENGINE INNODB STATUS the same modes appear as lock_mode X locks gap before rec.

"Does Postgres have anything equivalent, and how does it stop phantoms at SERIALIZABLE without gap locks?"

Postgres has no gap locks and no blocking mechanism for phantoms.

At SERIALIZABLE it uses predicate locks, which are not blocking locks at all but bookkeeping: when my transaction reads a range through an index, Postgres records a SIReadLock on the index pages or the relation, visible in pg_locks with mode SIReadLock.

If another transaction later inserts a row that falls under that predicate and both transactions form a dangerous dependency pattern, one of them is aborted with SQLSTATE 40001 at commit time. Nobody waits; someone retries.

So InnoDB prevents phantoms by making the insert wait, Postgres prevents them by letting the insert happen and cancelling the transaction whose assumption it broke. The retry loop is the price Postgres charges instead of the queue.

Q13 · Scenario. "Your Postgres app runs at REPEATABLE READ and has started throwing ERROR: could not serialize access due to concurrent update. What does it mean, and what is the correct fix?"

Reveal answer

Strong answer Postgres's REPEATABLE READ is snapshot isolation: the whole transaction reads from one snapshot taken at its first statement. The error appears when my transaction tries to UPDATE or DELETE a row that another transaction modified and committed after my snapshot.

Postgres cannot both honor my frozen snapshot and let me overwrite newer data it never showed me — that would silently discard the other writer's work. So it applies first-updater-wins: the second writer's transaction is aborted with SQLSTATE 40001 instead of losing an update.

Notice this is Postgres being more honest than InnoDB, whose REPEATABLE READ would just apply my update on top of the newer version. The fix is a retry loop:

  1. Catch SQLSTATE 40001 specifically — not all exceptions.
  2. Roll back, then rerun the entire transaction from the top, so all reads happen against a fresh snapshot. Never catch the error and continue mid-transaction; the transaction is already dead and its earlier reads are stale.
  3. Bound it — three to five attempts with a short backoff — and log the retry rate, because a climbing rate means growing contention.
  4. Shrink the window: the shorter the transaction, the less likely a concurrent commit lands inside it.

Land it At snapshot isolation, serialization errors are not failures to eliminate but a contract to honor — code that runs at this level without a retry loop is incomplete.

Likely follow-ups
"You added the retry loop, but the error rate is still climbing and some requests exhaust all five attempts. What next?"

Then contention itself is the problem, and retrying just burns capacity. I would find which rows are the hot spot, usually from the failing statement's WHERE clause and from pg_stat_statements, and change the access pattern.

Options in order: shrink the transaction so the window between snapshot and write is milliseconds, moving any remote calls or heavy reads outside it; replace read-then-write with a single atomic statement like UPDATE ... SET count = count + 1, which at REPEATABLE READ still conflicts but retries succeed immediately; take the row lock first with SELECT ... FOR UPDATE so writers queue instead of aborting; or run that specific transaction at READ COMMITTED, where the concurrent update is simply waited for and re-evaluated with no error. For a true hot counter, shard it across several rows.

"Where exactly in a Spring service does the retry go, and what goes wrong if it is in the wrong place?"

Outside the transactional boundary. If the @Transactional method catches the exception and loops internally, it is retrying inside a transaction that Postgres has already marked aborted, so every subsequent statement fails with "current transaction is aborted".

The retry must wrap the whole call so a new transaction and a new snapshot begin each attempt.

Concretely, a separate bean calls the transactional service inside a loop; Spring Retry's @Retryable(retryFor = CannotAcquireLockException.class) on the caller works, and Spring translates SQLSTATE 40001 into CannotAcquireLockException or, in some driver versions, PessimisticLockingFailureException, so I would test which one my stack throws.

Also, self-invocation within the same class bypasses the proxy, so the retrying method and the transactional method must live in different beans.

"How do you monitor this in production so you know when retries have become a problem?"

Three signals. First, a counter metric on the retry wrapper, tagged by operation, so I can graph retries per second and attempts-until-success per endpoint; a rising trend is contention growing.

Second, on the database, pg_stat_database.conflicts covers replica conflicts only, so I rely on the application counter plus log grepping for SQLSTATE 40001 in the Postgres log if log_min_error_statement captures it. Third, an alert on the exhausted-retry rate, because that is the user-visible failure.

I would also record the elapsed time inside each attempt, since long attempts at snapshot isolation are the root cause. A healthy service has retries in the low fractions of a percent; above a percent or two I treat it as a design problem.

"Why not just switch the whole application to READ COMMITTED and make the error disappear?"

That is a legitimate option and often the right one, but I would say what it changes. At READ COMMITTED, the same collision does not error: my UPDATE waits for the concurrent transaction, then re-evaluates its WHERE against the new row version and applies on top.

That silently allows lost updates for read-then-write code, so every place that computes a new value in Java from a value it read must be audited and converted to atomic SQL, FOR UPDATE, or a version column.

It also removes the per-transaction snapshot, so multi-statement reads that need one instant must request REPEATABLE READ explicitly. If the codebase already follows those disciplines, READ COMMITTED is simpler and faster. If it relies on snapshot isolation for correctness, switching trades loud errors for silent ones.

Q14. "What does READ COMMITTED actually guarantee in Postgres, and what happens when my UPDATE collides with a concurrent one?"

Reveal answer

Strong answer At READ COMMITTED, every statement gets its own fresh snapshot of everything committed before that statement began.

You never see uncommitted data, but two statements in one transaction can see two different worlds — that is the per-statement snapshot, and it is why non-repeatable reads and phantoms are both possible here.

The collision behavior is the interesting part: if my UPDATE reaches a row that a concurrent transaction has already modified but not committed, I wait for that transaction. If it aborts, I proceed on the original row.

If it commits, Postgres re-evaluates my WHERE clause against the new version of the row — if it still matches, my update applies on top; if not, the row is skipped.

No error is raised, which is precisely why lost updates from read-then-write logic in the application sail through unnoticed at this level.

Land it READ COMMITTED trades multi-statement consistency for zero retry burden — the right default for OLTP, as Postgres itself decided, as long as every multi-step invariant is protected by something else.

Likely follow-ups
"What does the re-evaluation of the WHERE clause mean in practice? Give me a case where it produces a surprising result."

Take UPDATE accounts SET balance = balance - 100 WHERE id = 1 AND balance >= 100. Transaction A runs it and waits to commit. Transaction B runs the same statement and blocks on the row. A commits, taking the balance from 150 to 50.

B wakes up, re-reads the newest version of the row, re-checks balance >= 100 against 50, finds it false, and skips the row with zero rows affected. That is correct and safe.

The surprising case is a join or subquery: only the target row is re-fetched, while other tables referenced in the statement are still read from the original snapshot, so a condition that depends on another table can be evaluated against a mixed picture. Postgres documents this as a known limitation of READ COMMITTED.

"How does a plain SELECT under READ COMMITTED interact with a long statement — can it see a commit that happened mid-statement?"

No. The snapshot is taken at the start of the statement, not continuously, so a SELECT that runs for thirty seconds sees the world as it was when it started, even if a thousand commits land during those thirty seconds.

This is why a single statement is always internally consistent at any isolation level in both engines. The per-statement snapshot only refreshes between statements.

There is one nuance: functions marked VOLATILE that run inside the statement each take their own snapshot, so a query calling such a function can see newer data through the function than through the outer query.

Declaring functions STABLE where accurate avoids that and also lets the planner optimise them.

"When is READ COMMITTED the wrong choice for a transaction?"

Whenever the transaction reads more than one thing and needs them to describe the same instant, or reads something and then writes based on it without a lock.

Examples: a report that sums a table and then lists its rows; a check-then-act like "count active sessions, if under limit insert one"; a batch that copies rows to another table and then deletes them by the same predicate.

For the first, I use REPEATABLE READ per transaction. For the second, I lock the parent row with FOR UPDATE or use SERIALIZABLE with a retry. For the third, I use a single statement with a CTE, WITH moved AS (DELETE ... RETURNING *) INSERT .... READ COMMITTED remains the default; these are the deliberate exceptions.

"How does InnoDB's READ COMMITTED differ from Postgres's on the same collision?"

The visible behaviour is the same — the second UPDATE waits, then applies to the newest row — but the mechanics differ in two ways worth knowing.

InnoDB does not re-evaluate the WHERE clause against the new version; it uses a "semi-consistent read", where it reads the latest committed version for rows the statement scans, and if the row does not match, it does not lock it, which reduces lock waits.

Second, at READ COMMITTED InnoDB releases locks on non-matching rows immediately after examining them and takes no gap locks, whereas at REPEATABLE READ it keeps every scanned record locked until commit. Postgres never locks non-matching rows in the first place.

So on a full-scan UPDATE, InnoDB READ COMMITTED behaves more like Postgres, which is one reason to choose it.

Q15. "Give me an honest assessment of SERIALIZABLE — how Postgres implements it, what it costs, and when it is actually justified."

Reveal answer

Strong answer Postgres implements it as SSI — serializable snapshot isolation.

Transactions still run on snapshots without blocking each other; the engine additionally tracks read-write dependencies between concurrent transactions, and when it detects a pattern that could not occur in any one-at-a-time ordering, it aborts one participant with SQLSTATE 40001.

So it is optimistic: no extra blocking, but you must build the same retry loop as at REPEATABLE READ, and expect a higher abort rate under contention.

The costs are the bookkeeping — predicate lock tracking in memory, roughly a few percent to tens of percent overhead depending on workload — the retries themselves, and a subtlety: the guarantee only fully holds among transactions that all run SERIALIZABLE. InnoDB's SERIALIZABLE is a different animal — it turns plain SELECTs into shared locking reads, so readers block writers again, which is usually a worse deal.

It is justified when an invariant spans rows that no single UPDATE touches — the write-skew family — and you would rather retry occasionally than hand-place explicit locks correctly everywhere.

Land it SERIALIZABLE in Postgres is "correctness by retry" and in MySQL "correctness by blocking" — pick it per transaction that needs it, not as a global default.

Likely follow-ups
"You said the guarantee only holds among transactions that all run SERIALIZABLE. What happens if one transaction in the mix runs READ COMMITTED?"

Then the serializable transactions are only guaranteed serializable with respect to each other.

A READ COMMITTED transaction takes no predicate locks and is not tracked in the dependency graph, so it can read a state that no serial ordering of the serializable transactions would have produced, and its writes are not checked against their reads.

Practically, if two SERIALIZABLE transactions guard the on-call invariant and a third READ COMMITTED batch job also removes doctors, the invariant can still break through the batch job.

So SERIALIZABLE must be applied to every transaction that touches the invariant, which usually means every writer of those tables. A trick to enforce that is default_transaction_isolation = serializable for the application role, so nothing can forget.

"Why does SSI sometimes abort a transaction that would actually have been fine?"

Because it detects a pattern, not a proof. SSI looks for a "dangerous structure": two consecutive read-write dependencies between three concurrent transactions, and when it sees one it aborts a participant.

That structure is necessary for a serialization anomaly but not sufficient, so some aborts are false positives — the actual outcome would have been serializable. Postgres tolerates that because checking for a true cycle would be far more expensive.

The false-positive rate rises when predicate locks get coarse: if max_pred_locks_per_transaction is exceeded, page-level locks are promoted to relation-level, and then two transactions touching the same table at all look like a conflict.

Raising that setting, keeping transactions short, and using indexes so reads cover narrow ranges all cut needless aborts.

"What is the 'read-only deferrable' option and when would you use it?"

BEGIN ISOLATION LEVEL SERIALIZABLE READ ONLY DEFERRABLE is for long reports that need a serializable view without ever being aborted and without slowing writers.

Postgres waits at the start of such a transaction until it can obtain a snapshot that is guaranteed not to conflict with any running serializable transaction — it may wait a while — and from then on the transaction takes no predicate locks and can never be cancelled by SSI. It is perfect for a nightly backup or a large reconciliation read: pg_dump --serializable-deferrable uses exactly this.

The cost is the initial wait, which can be long on a busy system, and it only applies to read-only work. Any write in such a transaction fails.

"How would you measure the real overhead of SERIALIZABLE on your workload before committing to it?"

Run the same load test twice, once at REPEATABLE READ and once at SERIALIZABLE, with the retry loop in place both times, and compare four numbers: throughput, p99 latency, the rate of SQLSTATE 40001 aborts, and memory used for predicate locks, which shows up in pg_locks as SIReadLock rows and is bounded by max_pred_locks_per_transaction times connections.

On typical OLTP with short transactions and good indexes, the overhead is a few percent and aborts are rare. On workloads with wide range scans or long transactions, aborts can climb to several percent and throughput drops noticeably.

I would also test the worst case: a long-running SERIALIZABLE report alongside writers, because that is where the abort storms come from.

Q16. "Why is READ UNCOMMITTED nearly pointless in InnoDB and literally ignored in Postgres?"

Reveal answer

Strong answer READ UNCOMMITTED existed for lock-based engines, where a reader had to either wait for writers' locks or cheat and read past them — dirty reads were the price of not blocking.

MVCC engines removed the dilemma: readers get a clean committed snapshot without taking locks at all, so there is nothing left to buy with a dirty read.

In InnoDB the level only changes plain SELECTs to read the newest, possibly uncommitted row versions — you can observe half of a multi-row update that later rolls back, while gaining essentially no concurrency, because plain reads were not blocking anyway.

Postgres does not even implement it: request READ UNCOMMITTED and you get READ COMMITTED, which the SQL standard explicitly allows, since a level may always be stricter than asked. The idea survives mainly as SQL Server's NOLOCK folklore imported by habit.

Land it If someone proposes READ UNCOMMITTED "for performance" on InnoDB or Postgres, the correct response is that they are paying in correctness for a discount that MVCC already gave them for free.

Likely follow-ups
"Then why does InnoDB still implement READ UNCOMMITTED at all?"

Compatibility and one narrow diagnostic use. MySQL predates InnoDB being the default engine, and the level existed for MyISAM-era applications; removing it would break those.

The diagnostic use is peeking at a large in-flight transaction's progress without waiting and without pinning a snapshot — counting migrated rows in a running migration, for instance.

There is also a small cost difference: a READ UNCOMMITTED read does not need to walk the undo chain to reconstruct an old version, so on a row being hammered by a long transaction it avoids that reconstruction cost.

That is a micro-optimisation nobody should plan around. For anything that feeds a decision, the answer remains READ COMMITTED, and I would put a lint rule against the level in application code.

"Someone migrating from SQL Server wants to use NOLOCK-style reads on Postgres to avoid blocking. What do you tell them?"

That the problem NOLOCK solves does not exist on Postgres. In SQL Server's default READ COMMITTED with locking, readers block behind writers, so NOLOCK was a way to skip the wait at the cost of dirty reads.

In Postgres, and in InnoDB, a plain SELECT never takes row locks and never waits for a writer; it reads the last committed version from the snapshot. So a plain SELECT at READ COMMITTED already gives them the non-blocking behaviour they wanted, with clean data.

The only places a Postgres reader waits are on table-level locks from DDL, such as an ALTER TABLE queued behind a long transaction, and no isolation level bypasses that. I would show them pg_stat_activity during a write-heavy test to prove the readers are not waiting.

"Does the SQL standard really allow an engine to silently upgrade the level? Is that not a violation?"

It explicitly allows it. The standard defines each level by the anomalies it must forbid, and says an implementation may provide a stricter level than requested, since forbidding more anomalies never breaks a program that tolerated them.

What it does not allow is providing a weaker level. So Postgres running READ UNCOMMITTED as READ COMMITTED is compliant.

The place people sometimes claim a violation is the other direction: InnoDB's REPEATABLE READ permits lost updates, which the standard's anomaly list does not mention, so it is technically compliant while surprising.

The lesson I draw is that "compliant with the standard" tells you the floor, not the behaviour, and the engine documentation is the real contract.

Q17 · Scenario. "The finance team requires strictly sequential, gapless invoice numbers. What isolation level do you choose?"

Reveal answer

The real test Spotting that this is a trick question — the answer is a locking pattern, not a level.

Strong answer I would walk the options to show why the question is a trap:

  1. SELECT max(number)+1 at READ COMMITTED: two concurrent transactions read the same max and issue duplicate numbers. Broken.
  2. The same at REPEATABLE READ: both still read the same max from their snapshots; in Postgres one dies with a serialization error, in InnoDB you get duplicates unless a unique index saves you. SERIALIZABLE makes it correct but only by aborting and retrying — you have serialized invoice creation anyway, chaotically.
  3. AUTO_INCREMENT or a sequence: concurrency-safe and fast, but sequences deliberately do not roll back — an aborted transaction burns a number and leaves a gap. Fails "gapless".
  4. The correct tool: a counter row, locked explicitly. Inside the same transaction that inserts the invoice, run SELECT next_no FROM invoice_counter FOR UPDATE, increment it, and use the value. FOR UPDATE takes an exclusive lock, so invoice-creating transactions queue on that one row; if any of them rolls back, its increment rolls back too, so no gap is possible.

The cost is deliberate: that counter row is a global choke point and invoice creation becomes serial. That is not a flaw — "strictly sequential and gapless" is a serialization requirement, and the honest design admits it and keeps that transaction tiny.

Going deeper One precision point on the REPEATABLE READ bullet: in Postgres, two transactions that each read max(number) and then INSERT different rows do not collide on any row, so snapshot isolation raises no serialization error — both inserts succeed unless a unique index on number rejects the second, which is the only thing that saves you there.

Only SERIALIZABLE would detect the read-write dependency and abort one. That makes the unique index a required part of the design regardless of the locking approach: it is the backstop that turns a silent duplicate into a loud failure.

The complete pattern is therefore three parts — a counter row locked with FOR UPDATE in the same transaction as the invoice insert, a unique constraint on the invoice number, and a transaction kept to a few milliseconds so the choke point stays cheap.

In Postgres a useful variant is UPDATE invoice_counter SET next_no = next_no + 1 RETURNING next_no, which locks, increments, and returns in one statement.

Land it Gapless numbering cannot be bought with an isolation level — it is a business rule demanding serial execution, so serialize the smallest possible thing on purpose.

Likely follow-ups
"Invoice creation is now serialized on that counter row. At what volume does that break, and what do you do then?"

The counter transaction, if it holds the lock for around two milliseconds including commit, allows roughly five hundred invoices per second through one row, and in practice a few hundred with contention overhead. Most businesses never approach that.

If one does, the honest options are to relax the rule or narrow its scope.

Finance often accepts gapless numbering per series — per country, per branch, per year — so I would use one counter row per series and the choke point splits by that many.

If they insist on a single global gapless sequence, I would separate number assignment from creation: create invoices in a PENDING_NUMBER state at full speed, and a single-threaded process assigns numbers in commit order.

Either way, the requirement is what forces the serialization, and that should be said to the requester.

"The counter transaction deadlocked in production. How, and what is the fix?"

The usual cause is lock ordering. Transaction A inserts the invoice first, then locks the counter; transaction B locks the counter first, then inserts an invoice whose unique index or foreign-key check collides with A's uncommitted row. Each waits for the other.

The fix is to make the counter lock the very first statement of the transaction, before any other row is touched, so all invoice transactions acquire locks in the same order and cycles cannot form.

A second cause on InnoDB is a gap lock: if the counter table is looked up by a non-unique key, the FOR UPDATE takes a next-key lock. Looking it up by primary key with an exact match gives a record lock only.

I would confirm from the deadlock section of SHOW ENGINE INNODB STATUS.

"Why not just use a sequence and fill gaps afterwards?"

Because most gapless requirements come from tax law, and renumbering after the fact usually violates the spirit of them: the number must be assigned at issue time and never change.

Also, filling gaps later means an invoice issued today could get a number lower than one issued yesterday, which breaks the "sequential" half of the rule.

And it requires a background process to find gaps and renumber, which touches rows that may already have been sent to customers or exported to an accounting system.

The FOR UPDATE counter is simpler, correct at issue time, and its only cost is serialization, which the requirement demands anyway. If the rule is merely "no duplicates, mostly ascending", then a sequence is fine and I would ask finance which they actually need.

"What would you do differently on a greenfield design where this requirement is known up front?"

I would separate the business identifier from the primary key from day one: a BIGINT surrogate primary key generated by the sequence for joins and references, and a separate invoice_number column with a unique constraint that is assigned by the counter mechanism, possibly nullable until the invoice is finalised.

That keeps the hot path — creating drafts, adding lines — free of the serialized step, and only the finalise action takes the counter lock.

I would also create the counter table with one row per numbering series and put the series key in the primary key so the lock is a record lock.

And I would write the finalise step as one small transaction, documented as the deliberate serialization point, with a metric on its lock wait time so we see it approaching its ceiling long before it is a problem.

Q18 · Scenario. "The same code behaves differently on MySQL and Postgres 'at the same isolation level'. The team says they never set one — 'it's whatever the default is'. What do you check, and what's the lesson?"

Reveal answer

Strong answer This is the "we assumed the default" bug, and I would check three layers:

  1. The defaults themselves differ: InnoDB defaults to REPEATABLE READ, Postgres to READ COMMITTED. The same code is running under two different anomaly contracts — snapshot-per-transaction on one, snapshot-per-statement on the other — so different behavior is expected, not mysterious.
  2. Verify what a session actually runs at rather than trusting documentation: on MySQL, SELECT @@transaction_isolation; — on Postgres, SHOW transaction_isolation;. Run it through the application's own connection path, not a hand-opened console, because the path is where surprises live.
  3. Audit everything between the code and the database that can override the level: Connection.setTransactionIsolation in JDBC — the Java database access API — the pool's configuration such as Hikari's transactionIsolation property, Spring's @Transactional(isolation = ...), and server-side settings like transaction_isolation in my.cnf or default_transaction_isolation in postgresql.conf, which a DBA may have changed globally.

The fix is to choose a level deliberately and set it explicitly in exactly one place — the pool or the transaction annotations — so every environment agrees.

Land it Isolation is configuration, not fate — a senior engineer can state their system's level and prove it with one query.

Likely follow-ups
"Give me a concrete piece of code that behaves differently on the two defaults."

A balance update written as read-then-write. Inside one @Transactional method: SELECT balance FROM accounts WHERE id = 1, compute the new value in Java, UPDATE accounts SET balance = ? WHERE id = 1. Run two of these concurrently.

On MySQL's default REPEATABLE READ, both succeed and one increment is lost. On Postgres's default READ COMMITTED, both also succeed and one increment is lost, so far the same.

But if the team "fixed" it by setting REPEATABLE READ explicitly on both, Postgres now aborts the second writer with a serialization error while MySQL still loses the update silently. So the same annotation produces an exception on one engine and silent corruption on the other.

The only portable fix is SELECT ... FOR UPDATE, atomic SQL arithmetic, or a version column.

"Which single place would you set the isolation level, and why not the server config?"

The connection pool, because it is owned by the application, deployed with it, and identical in every environment. In Hikari that is spring.datasource.hikari.transaction-isolation=TRANSACTION_READ_COMMITTED, which makes the pool issue the SET on every connection it opens.

Server configuration is the wrong place because it is owned by a different team, differs between staging and production by accident, and can be changed without a deploy or a code review.

Per-method @Transactional(isolation = ...) is for exceptions — the one report that needs REPEATABLE READ — and I would grep for those in review.

The combination is: one pool-level default, explicit per-transaction overrides, and a startup check that logs the effective level from the server so drift is visible in the logs.

"You set it in the pool, but a production session still shows a different level. What are the remaining ways that happens?"

Several. Spring's @Transactional(isolation = ...) changes the level for that transaction and the pool resets it afterwards, but a bug in reset handling or a custom DataSource wrapper can leave it changed on the returned connection.

A proxy like ProxySQL or PgBouncer in transaction pooling mode can hand the same server connection to different clients, so a session-level SET made by one client leaks to another; on PgBouncer that is why session-level settings are unsafe in transaction mode.

A stored procedure or trigger can run SET TRANSACTION. And MySQL has both transaction_isolation and the older tx_isolation name, so a config may set one that the version ignores.

I would test the level from inside a real request and from a pooled connection under load, not once at startup.

Drill · Lost updates, write patterns & MVCC

These questions test whether you can make concurrent writes safe with the right pattern — and whether you understand the version machinery underneath well enough to predict its operational failure modes.

Q19 · Scenario. "Two sessions both read a balance of 100. One writes 110, the other writes 130. The +10 has vanished. Name the anomaly, and tell me which isolation levels do and do not save you."

Reveal answer

Strong answer That is a lost update: both sessions did read-modify-write from the application, and the second write silently overwrote the first, because 130 was computed from a balance that was no longer true.

Level by level: READ COMMITTED allows it in both engines — each session honestly read committed data and honestly wrote.

InnoDB's REPEATABLE READ also allows it, which surprises people: the second UPDATE is a current read, applies to the latest committed row, and writes 130 over 110 without complaint.

Postgres's REPEATABLE READ prevents it — the second writer gets "could not serialize access due to concurrent update" and must retry, at which point it re-reads 110 and computes 120 correctly. SERIALIZABLE prevents it in both engines.

The application-level fixes are better than escalating the level: compute in SQL with SET balance = balance + 10, or lock the row first with SELECT ... FOR UPDATE, or use an optimistic version column.

Land it The deep point is that the database never saw a conflict — two valid reads, two valid writes — so the cure is making the conflict visible to it: in the statement, in a lock, or in a version check.

Likely follow-ups
"Rank the three application-level fixes. Which do you reach for first and why?"

First, arithmetic in SQL: UPDATE accounts SET balance = balance + 10 WHERE id = 1. It is one statement, atomic under the row lock in both engines, needs no transaction management and no retry, and cannot lose an update.

It only works when the new value is a pure function of the old value that SQL can express.

Second, the version column, when a human or a service reads, thinks, and writes back a whole record: it never blocks, and a conflict is surfaced as a zero-row update that the caller handles. Third, SELECT ... FOR UPDATE, when the decision logic is complex, must not fail, and the transaction is short; it serializes writers on that row.

I avoid escalating the isolation level as a fix because it changes behaviour for everything, not just this write.

"If both sessions used SET balance = balance + 10, walk me through what the engine actually does under the lock."

Session one's UPDATE finds the row through the index, takes an exclusive record lock, reads the current committed value 100, computes 110, writes the new version, and holds the lock until commit. Session two's UPDATE arrives, tries to take the same lock, and waits.

Session one commits; the lock is released. Session two now acquires the lock and, crucially, reads the row's newest committed version, 110, not the value from any earlier snapshot, computes 120, and writes it.

The read inside a locking write is always a current read in both engines. The wait is microseconds under normal load. The result is 120, correct, with no application code involved.

This is also why a single UPDATE needs no explicit transaction: the statement is its own atomic unit.

"How do you find lost updates that are already happening in production?"

They leave no error, so I look for invariant violations and code shapes. For money, a reconciliation that compares each balance with the sum of its ledger entries finds the drift; every lost increment shows up as a discrepancy.

For counters, compare the counter with a count of the underlying events.

In code, I grep for the pattern: an entity loaded, a field computed in Java from its own previous value, and a save, with no @Version, no @Lock(PESSIMISTIC_WRITE), and no atomic SQL. Hibernate's @DynamicUpdate plus @Version makes the conflict visible as OptimisticLockException, so turning that on for the suspect entity in a canary deployment turns silent loss into a logged exception that quantifies the problem.

"Does InnoDB's SERIALIZABLE really prevent this, and how?"

Yes, by turning the first read into a locking read. At InnoDB SERIALIZABLE, a plain SELECT is silently converted to SELECT ... FOR SHARE, so both sessions take a shared lock when they read the balance of 100.

When the first tries to UPDATE it needs an exclusive lock, which conflicts with the other's shared lock, so it waits; the second tries the same, and now each waits on the other — a deadlock, which InnoDB detects and resolves by rolling back one.

The survivor commits 110, and the victim retries, reads 110, and writes 120. So it prevents the lost update but through a deadlock and a retry, which is why I would rather write FOR UPDATE explicitly on the read and avoid the shared-then-upgrade deadlock entirely.

Q20. "Explain optimistic locking with a version column — the exact UPDATE pattern, what you do when it reports zero rows, and how JPA's @Version maps onto it."

Reveal answer

Strong answer Optimistic locking means: do not lock on read; detect the conflict at write time. Each row carries a version number. You read the row and remember its version, then write with both the id and the remembered version in the WHERE clause, incrementing the version as you go:

optimistic-lock.sql
UPDATE account
   SET balance = 130,
       version = version + 1
 WHERE id = 42
   AND version = 7;   -- the version I read

-- affected rows = 1 : I won; nobody changed the row since my read.
-- affected rows = 0 : someone committed version 8 first. Reload, retry.

Zero rows affected is not an error from the database's point of view — it is the signal. The only correct responses are to reload the row and reapply the change against fresh data, or to surface a conflict to the user ("this record was modified by someone else"). JPA — the Java Persistence API — automates exactly this: annotate a field with @Version and Hibernate appends the version check to every UPDATE, throwing OptimisticLockException on zero rows. It shines with low contention and human-paced edits; under heavy contention the retry rate makes pessimistic locking cheaper.

Land it The pattern's whole safety lives in one atomic statement — the check and the write happen under the same row lock, so there is no window between them.

Likely follow-ups
"The version check is in the WHERE clause. Why can two transactions not both pass it at the same time?"

Because the check and the write happen under the same row lock, as part of one statement. When my UPDATE reaches the row, the engine takes an exclusive lock, and only then evaluates version = 7 against the current committed version.

If another transaction is mid-way through its own UPDATE on that row, I wait for its lock; when it commits with version 8, I re-read the newest version, my predicate fails, and I get zero rows.

Postgres re-evaluates the WHERE on the new version at READ COMMITTED; InnoDB reads the latest version for the write in the first place. There is no instant between "check passed" and "row written" where another transaction can act, because both happen while I hold the lock. That is why the pattern is safe at every isolation level.

"What should the application do on zero rows: retry automatically or tell the user?"

It depends on who computed the change. If the change is a pure function of the record — recalculating a derived field, applying a delta — the application can reload and reapply automatically, in a bounded loop of a few attempts.

If a human edited a form based on what they saw, silently retrying would overwrite the other person's edit with a stale one, which is precisely the lost update we were preventing; the right response is a conflict message showing the current values and asking them to merge.

In an API, that is HTTP 409 Conflict with the current representation. In JPA the signal is OptimisticLockException, which Spring translates to ObjectOptimisticLockingFailureException, and I would catch it at the service boundary, never inside the transactional method.

"What does @Version look like at the SQL level, and what are its gotchas in Hibernate?"

Hibernate adds AND version = ? to the UPDATE and increments the column, then checks the JDBC row count and throws StaleObjectStateException on zero.

Gotchas: the version only guards changes made through the entity, so a native UPDATE or a JPQL bulk update that does not bump the version breaks the contract, and I would make bulk updates increment it explicitly.

Detached entities carry their version across requests, which is the correct way to do a long edit in a web form, but only if the form round-trips the version field; if the controller reloads the entity fresh before applying changes, the check is meaningless.

Use an integer or a timestamp; timestamps with millisecond precision can collide. And the version increments on any flush of a dirty entity, including changes to collections, which can surprise people.

"At what point does optimistic locking become the wrong choice?"

When conflicts stop being rare. Optimistic locking assumes most writers do not collide, so the cost of an occasional retry is lower than the cost of locking every read.

Once a specific row is contested — a shared counter, an account many services update, a popular inventory item during a sale — the retry rate climbs, each retry costs a full read and write, and throughput on that row can collapse under a storm of failed attempts.

At that point a pessimistic SELECT ... FOR UPDATE queues writers in order with no wasted work, or better, the operation is rewritten as atomic SQL that needs neither.

The signal is measurable: I would count optimistic failures per entity, and above a few percent of writes on a given row type it is time to switch that path.

Q21. "When do you reach for SELECT ... FOR UPDATE instead of optimistic locking, and what exactly does it lock?"

Reveal answer

Strong answer SELECT ... FOR UPDATE is pessimistic locking: it takes exclusive row locks at read time, so anyone else wanting those rows waits until I commit or roll back.

I prefer it over a version column when contention is high enough that optimistic retries would thrash, when the operation must not fail and be retried — a payment capture mid-flow — or when the work between read and write is short and always ends in a write anyway.

What it locks: the rows the query matches, held until the end of the transaction.

In InnoDB at REPEATABLE READ it also takes gap locks on the scanned index ranges, and with no usable index it locks every row the scan examined, which can be the whole table. Postgres locks only the matched rows.

Two modifiers matter in practice: NOWAIT fails immediately instead of queueing, and SKIP LOCKED skips rows others hold.

Land it The discipline that makes it safe is holding those locks for milliseconds — a FOR UPDATE followed by a remote call is a lock held for someone else's latency.

Likely follow-ups
"What is the difference between FOR UPDATE and FOR SHARE, and when is FOR SHARE the right one?"

FOR UPDATE takes an exclusive lock: nobody else can lock, update, or delete the row until I commit. FOR SHARE takes a shared lock: other readers can also take shared locks, but no one can update or delete the row while any shared lock is held.

FOR SHARE is right when I need a row to stay unchanged as a precondition but I will not write it myself — checking that a parent account is still active before inserting a child transaction, for instance.

Postgres adds two finer modes: FOR NO KEY UPDATE, which is what a normal UPDATE takes, and FOR KEY SHARE, which foreign-key checks take, and those two do not conflict with each other.

The trap with FOR SHARE is taking it and then updating: two sessions doing that deadlock.

"How long can a FOR UPDATE lock legitimately be held, and what would you set as a limit?"

Milliseconds, and I would enforce it. The lock lives until the transaction ends, so it is held for the duration of everything after the SELECT: computation, further statements, and the commit.

My rule is that no remote call, no user interaction, and no unbounded loop occurs inside.

As limits, on Postgres I set lock_timeout to a second or two for the application role so a waiter gives up rather than queueing forever, and idle_in_transaction_session_timeout to something like thirty seconds so a holder that stalls is killed.

On MySQL innodb_lock_wait_timeout is the waiter's limit and I lower it from the default fifty seconds to a few seconds for OLTP. Then I alert on lock wait time per statement, which shows holders that have grown slow.

"You said InnoDB with no usable index locks every row the scan examined. What does that look like and how do you catch it before it ships?"

It looks like a SELECT ... FOR UPDATE on a non-indexed column that takes next-key locks on the whole table at REPEATABLE READ, so every concurrent write to the table blocks, even though the query returned three rows.

I catch it with EXPLAIN in review: any type: ALL or type: index on a locking statement is a red flag.

In a test environment I can prove it by running the statement in one session and querying performance_schema.data_locks in another; the lock count equals the number of rows scanned, not matched.

The fix is an index on the WHERE column or switching that session to READ COMMITTED, where InnoDB releases the locks on non-matching rows. Postgres only locks matched rows, so the same query there is slow but not a table lock.

"What happens with FOR UPDATE on a row that a concurrent transaction has already deleted?"

It depends on timing and engine. If the delete is uncommitted, my FOR UPDATE waits for that transaction.

If it then commits, in Postgres at READ COMMITTED the row is simply not returned; at REPEATABLE READ I get the serialization error, because a row I could see in my snapshot was changed by someone else.

In InnoDB, the locking read is a current read, so it finds no row and returns nothing; if I was at REPEATABLE READ and a plain SELECT earlier showed the row, I now have the snapshot-versus-current split.

The design consequence: code after a FOR UPDATE must handle the empty result rather than assuming the row exists because an earlier read found it, and on Postgres REPEATABLE READ it needs the retry loop.

Q22 · Scenario. "Build me a job queue in plain SQL that ten workers can poll without ever grabbing the same job twice."

Reveal answer

Strong answer The primitive is FOR UPDATE SKIP LOCKED, supported by both Postgres and MySQL 8.0.

  1. Table: jobs(id, status, payload, locked_at, ...) with an index on (status, id).
  2. Each worker, in a transaction: SELECT id, payload FROM jobs WHERE status = 'ready' ORDER BY id LIMIT 10 FOR UPDATE SKIP LOCKED; then UPDATE ... SET status = 'running' for those ids, and commit quickly.
  3. Why the naive versions fail: without FOR UPDATE, two workers select the same rows before either updates — a classic race. With plain FOR UPDATE, every worker queues behind whoever locked the first matching rows, so ten workers perform like one. SKIP LOCKED changes the semantics: rows currently locked by another transaction are simply skipped instead of waited for, so each worker walks past its colleagues' claims and locks the next free jobs. Contention becomes parallelism.
  4. Handle worker death: a crashed worker's transaction rolls back and its row locks vanish, so unclaimed work returns automatically if you claim inside one transaction. If workers claim-then-commit and process outside the transaction, add a lease — locked_at plus a sweeper that returns jobs to 'ready' after a timeout.

The honest caveat: SKIP LOCKED deliberately gives a non-repeatable view — you are reading around locked rows — which is exactly right for a queue and wrong for almost anything else.

Land it SKIP LOCKED turns row locks from a queueing mechanism into a work-distribution mechanism — it is the difference between a database-backed queue that scales and one that serializes.

Likely follow-ups
"A worker claimed ten jobs, processed five, and crashed. What happens to each of the ten, and how do you make that recoverable?"

If the worker claimed and processed inside one transaction, the crash rolls all ten back, including the five completed ones, so their side effects are repeated on the next attempt; that is acceptable only if processing is idempotent.

If the worker committed the claim first and processed outside the transaction, all ten stay in RUNNING forever with no lock protecting them, and the five unprocessed ones are lost.

The recoverable design is claim-then-commit with a lease: set locked_at = now() and locked_by = worker_id at claim, and mark each job DONE in its own small transaction as it finishes.

A sweeper resets rows where status = 'running' AND locked_at < now() - interval '5 minutes' back to READY, incrementing an attempts counter so poison jobs go to a dead-letter state after a few tries.

"The queue table has grown to fifty million completed rows and the poll query is slowing down. What is going on?"

Two things.

First, the index on (status, id) is being scanned from the start of the READY range, and if DONE rows dominate, the READY range itself is small, so the index scan should still be fast — but in Postgres, dead tuples from the constant status flips bloat that index, and each poll walks past dead entries until vacuum cleans them; pgstatindex would show low leaf density.

Second, table size itself hurts vacuum and cache.

The fixes: delete or archive DONE rows promptly, ideally moving them to a history table in batches; use a partial index WHERE status = 'ready' on Postgres so completed rows never enter the polled index; tune autovacuum aggressively on this table; and on MySQL, keep the polled range compact and consider partitioning by status or date.

"Why ORDER BY id, and what happens to fairness if you drop it?"

The ORDER BY gives approximate first-in-first-out and, more importantly, makes each worker walk the index in the same direction, so SKIP LOCKED skips its colleagues' claims and takes the next free rows in order.

Without an ORDER BY, the planner may choose any access path, and on Postgres a sequential scan could return rows in physical order, which after updates and vacuum is effectively random; old jobs could starve while new ones get processed.

The order also makes the index on (status, id) serve the query without a sort, which is what keeps polling cheap. If strict priority is needed, order by (priority DESC, id) and index the same way.

What SKIP LOCKED can never give is strict global ordering across workers, and the design should say so.

"When would you not use the database as a queue, and what would you cut under time pressure?"

I would move to a real broker — Kafka, RabbitMQ, SQS — when throughput passes a few thousand jobs per second sustained, when consumers are in different services that should not share a database, when fan-out to many consumers is needed, or when the polling load starts hurting the transactional workload on the same instance. Below that, the database queue wins on simplicity: exactly-once claim via row locks, transactional enqueue alongside business writes, and no new infrastructure. Under time pressure I would cut the lease sweeper and priority ordering, and ship claim-inside-transaction with idempotent processing plus a manual reset script for stuck jobs, because the SKIP LOCKED core is what makes it correct and the rest is operability I can add in the next sprint.

Q23 · Scenario. "Hospital rule: at least one doctor must be on call. Two doctors each open a transaction, each sees two doctors on call, and each takes themselves off. Both commit. Zero doctors on call. Which anomaly is this, and why didn't REPEATABLE READ stop it?"

Reveal answer

The real test Write skew is the standard question for separating people who understand snapshot isolation from people who memorized the levels table.

Strong answer This is write skew: two transactions read overlapping data, made a decision based on it, and then wrote to different rows — Alice updated Alice's row, Bob updated Bob's.

Snapshot isolation, which is what REPEATABLE READ gives you in Postgres and effectively in InnoDB, only detects conflicts when two transactions write the same row.

Here there is no write-write overlap for first-updater-wins to catch, and each snapshot honestly showed two doctors on call at the moment it was taken. Each transaction was individually correct; their combination broke an invariant that lives across rows, which no single row's history can witness.

The fixes: run these transactions at SERIALIZABLE in Postgres, whose SSI tracks exactly this read-write dependency cycle and aborts one; or materialize the conflict — SELECT ...

FOR UPDATE the rows the decision depends on, meaning both doctors' rows or a single on-call summary row, so the second transaction blocks and then re-reads reality; or enforce the invariant with a constraint or trigger where the schema allows it.

Land it The one-liner worth memorizing: snapshot isolation protects the rows you write, not the assumptions you read — write skew lives in that gap.

Likely follow-ups
"Show me the SELECT ... FOR UPDATE version and explain why it prevents the skew."

Each doctor's transaction runs SELECT * FROM doctors WHERE on_call = true AND shift_id = ? FOR UPDATE first, then counts the result, and only then updates their own row.

Because both transactions lock the same set of on-call rows, the second one blocks until the first commits. When it proceeds, its locking read is a current read, so it sees only one doctor on call, fails the check, and rolls back.

The trick is that the lock is taken on the rows the decision depends on, not on the row being written, which converts an invisible read-write dependency into a visible write-write conflict the engine can serialize.

On InnoDB this also takes gap locks on the scanned range, which additionally blocks a third doctor from being inserted as on-call mid-check.

"Can a constraint express 'at least one doctor on call'?"

Not directly, because a check constraint sees one row and this rule spans many. Two schema designs get there.

One is a summary row: a table shift_cover(shift_id, on_call_count) with CHECK (on_call_count >= 1), and every transaction that changes on-call status also does UPDATE shift_cover SET on_call_count = on_call_count - 1 WHERE shift_id = ?.

That update takes the row lock, serializes the writers, and the check fires when the count would hit zero.

The other is a trigger that counts after each update and raises an exception, but a trigger runs against the transaction's snapshot, so it has the same write skew unless it locks the shift row first.

The summary-row approach is the one I would ship: the invariant becomes one row's constraint.

"You chose SERIALIZABLE on Postgres. Now the on-call system sees aborts under load. What next?"

First check whether the aborts are true conflicts or false positives from coarse predicate locks. If the query WHERE shift_id = ? is not using an index, SSI takes a relation-level predicate lock, and every on-call change for any shift conflicts with every other.

An index on shift_id narrows the predicate lock to a few index pages and the false-positive rate drops sharply. Second, ensure the retry wrapper is outside the transaction and bounded.

Third, if aborts remain high because many doctors genuinely toggle the same shift, switch that path to explicit locking with FOR UPDATE on the shift row; queueing a few milliseconds beats retrying.

I would keep SERIALIZABLE for the rare complex invariants and use explicit locks for the hot ones.

"Name two other everyday features that are write skew in disguise."

Username or booking uniqueness done as check-then-insert, when there is no unique constraint: two registrations both check that "alice" is free, both insert, and now there are two.

And any quota or limit: "a user may have at most five active API keys" checked by counting and then inserting; two concurrent requests both count four and both insert. The pattern is always read a set, decide, write something not in the set.

The cures are the same three: a unique constraint or summary-row constraint where the schema can express it, a lock on the row the decision depends on, or SERIALIZABLE with retry.

I look for this shape in code review whenever a count or an existence check precedes an insert.

Q24 · Scenario. "Users double-click submit and you get duplicate orders — occasionally two charges. Fix it properly at the database layer."

Reveal answer

Strong answer The fix is an idempotency key backed by a unique constraint — idempotent meaning the operation can be applied twice with the effect of once.

  1. The client generates a key per logical order — a UUID created when the form renders, sent with every submit and retry of that order.
  2. The orders table gets a unique index on idempotency_key.
  3. The service inserts the order. If the insert fails with a duplicate-key error — MySQL error 1062, Postgres SQLSTATE 23505 — it does not fail the request: it fetches the existing order by the key and returns it, so both clicks receive the same order id and there is exactly one charge.
  4. Why the check-then-insert version everyone writes first is broken: "SELECT to see if it exists, then INSERT" leaves a window between the check and the insert, and two concurrent requests both pass the check. Only the unique index is race-free, because uniqueness is enforced atomically inside the index structure itself, under its own locks, at the moment of insert.

The same pattern protects you from retries you did not plan — load balancer replays, queue redeliveries, impatient users on slow Wi-Fi. Application-level deduplication, caches, and frontend button-disabling are all optimizations; the constraint is the guarantee.

Land it Uniqueness enforced anywhere except the database is a suggestion — the unique constraint is the last line of defense precisely because it is the only line that cannot be raced.

Likely follow-ups
"The client sends the same idempotency key but with a different request body the second time. What should happen?"

Reject it, and say so. An idempotency key promises "this is the same operation", so a different body under the same key is a client bug or an attack, and returning the first order would hide it.

The pattern I use is to store a hash of the canonical request body alongside the key in the idempotency table; on a duplicate-key hit, compare hashes, and if they differ return HTTP 422 with a message that the key was reused with different parameters.

Stripe's API behaves this way. That table also needs a retention policy — twenty-four hours is common — because keys accumulate forever otherwise, and the unique index only needs to cover the retention window.

"The double-click is fixed, but now you see duplicate charges from payment-provider retries. Is that the same problem?"

The same principle applied at a different boundary. Our order is unique, but the call to the payment provider is a remote side effect that can be retried by our code after a timeout, and a timed-out call may have succeeded.

The fix is to pass our own idempotency key to the provider — Stripe, Razorpay and similar all accept an Idempotency-Key header — so their side deduplicates.

Internally, I record the payment attempt in a row with a unique constraint on (order_id, attempt_key) before making the call, so a crash after the call but before recording is detectable on restart by querying the provider.

Idempotency has to be carried across every system boundary, not just into the first database.

"Where should the idempotency key be generated, and why not just use a hash of the request?"

On the client, at the moment the user starts the operation — when the checkout form renders, or when a mobile app creates a local order draft — and reused for every submit and every retry of that same intent.

A hash of the request body is a fallback when clients cannot be changed, but it has a real flaw: two legitimately different orders with identical content, say the same user buying the same item twice on purpose, hash identically and the second is wrongly treated as a duplicate.

Adding a timestamp to the hash defeats retries. A client-generated UUID captures intent rather than content, which is what idempotency is about. For server-to-server callers I require the header and reject requests without it.

"What does the transaction look like on the insert-fails path in Postgres specifically?"

In Postgres a unique violation aborts the whole transaction, so the catch-and-fetch cannot happen in the same transaction unless there is a savepoint. The clean shape is INSERT INTO orders (...) VALUES (...) ON CONFLICT (idempotency_key) DO NOTHING RETURNING id; if RETURNING is empty, the row already existed, and a follow-up SELECT ... WHERE idempotency_key = ? fetches it — all in one healthy transaction.

The DO NOTHING path still takes a lock that waits for a concurrent inserter to commit, so the second click blocks briefly until the first commits and then sees the row.

On MySQL the equivalent is INSERT IGNORE or catching error 1062, and MySQL does not abort the transaction on a duplicate, so the plain catch works there.

Q25. "What do INSERT ... ON DUPLICATE KEY UPDATE and INSERT ... ON CONFLICT guarantee, and why is an UPSERT race-free when SELECT-then-INSERT is not?"

Reveal answer

Strong answer An UPSERT is insert-or-update as one atomic statement. It is race-free because the decision "does this key exist?

" is made inside the index operation, under the index's own locks — there is no instant where another session can slip between the check and the write, unlike SELECT-then-INSERT, which always has that window. Postgres: INSERT ... ON CONFLICT (col) DO UPDATE SET ... or DO NOTHING — you name the exact unique constraint that arbitrates, which is good discipline.

MySQL: INSERT ... ON DUPLICATE KEY UPDATE fires on a collision with any unique index, which becomes ambiguous when a table has several.

The gotchas worth naming: MySQL reports two affected rows when the update path runs; both engines burn auto-increment values on the conflict path; and under heavy concurrency InnoDB's implementation can deadlock via gap locks, so UPSERT-heavy hot tables still need retry handling.

Land it Reach for UPSERT wherever the business rule is "one row per key, latest wins" — and keep the explicit duplicate-error path for cases like idempotency keys where the first write must win.

Likely follow-ups
"Explain the gap-lock deadlock with InnoDB UPSERTs step by step."

Two sessions each run INSERT ... ON DUPLICATE KEY UPDATE for keys that do not exist yet but fall in the same gap, say keys 15 and 17 with existing rows 10 and 20.

Session A's insert first checks for duplicates, which at REPEATABLE READ takes a shared next-key lock on the gap between 10 and 20. Session B does the same and gets a compatible shared gap lock on the same gap.

Now A needs an insert-intention lock to actually place key 15, and that must wait for B's gap lock. B needs the same for key 17 and waits for A's gap lock. Cycle: deadlock, error 1213, one is rolled back.

Mitigations are READ COMMITTED for the session, which removes the gap locks on the duplicate check, or serializing hot-key upserts, or retrying on 1213.

"Why does MySQL report two affected rows on the update path, and how does that break code?"

By MySQL's convention, an INSERT ... ON DUPLICATE KEY UPDATE returns 1 if a new row was inserted, 2 if an existing row was updated, and 0 if the update changed nothing because the values were identical.

It breaks code that asserts "exactly one row affected" as a success check — a common JDBC pattern — and code that sums affected rows to count inserts.

The JDBC flag useAffectedRows=true changes the driver to return the number of rows actually changed instead of rows matched, which is what most people expect.

I would document which convention the connection uses, because switching it silently alters the meaning of every executeUpdate return value in the service.

"When should the first write win instead of the latest, and how do you express that?"

Whenever the row represents a fact that must not be silently overwritten: an idempotency record, a reservation, a "first login" timestamp, an audit event. There, "latest wins" is exactly the wrong policy, because a retry or a race would replace the original.

In Postgres that is INSERT ... ON CONFLICT DO NOTHING, or a plain insert and handling SQLSTATE 23505; in MySQL it is INSERT IGNORE, which I use with care because it also suppresses other warnings, or a plain insert catching error 1062.

For a conditional latest-wins — only update if the incoming version is newer — Postgres allows DO UPDATE SET ... WHERE excluded.updated_at > t.updated_at, and MySQL 8.0.20+ allows referencing the new row via an alias in the UPDATE clause.

"Why do both engines burn auto-increment values on the conflict path, and does it matter?"

Because the id is allocated before the duplicate check.

The engine reserves the next sequence value to build the candidate row, attempts the insert, finds the conflict, and takes the update path, but the reserved value is never returned to the counter, since sequences and auto-increment are deliberately non-transactional for speed.

On a hot UPSERT table this can consume ids far faster than rows are created, and an INT column can exhaust its two billion values years earlier than the row count suggests.

It matters for two reasons: the type should be BIGINT from the start, and nobody should read meaning into gaps. A check-then-insert pattern avoids the burn but loses the race-freedom, so I accept the gaps and use BIGINT.

Q26 · Scenario. "A page-view counter implemented as 'read the count, add one in Java, write it back' drifts lower than the true number under load. Why, and what is the fix?"

Reveal answer

Strong answer It is the lost-update anomaly on a hot row, at high frequency. Ten threads read 500, all compute 501, all write 501 — nine views gone. Every read-modify-write cycle that overlaps another one loses increments, and the busier the page, the worse the undercount.

  1. The fix is to move the arithmetic into the database: UPDATE stats SET views = views + 1 WHERE page_id = ?. A single UPDATE statement is atomic on its own — the engine locks the row, reads the current value, computes, and writes, all under that lock — so concurrent increments queue for microseconds and none is lost. No explicit transaction is needed around one statement.
  2. If that one row becomes a genuine hot spot — thousands of increments per second serializing on its lock — shard the counter: N rows per page, increment one at random, sum on read. Or absorb increments in the application or Redis and flush batched deltas periodically, accepting a small loss window in exchange for load.

Land it Never do arithmetic in the application that the database can do in one statement — the round trip through app memory is exactly where updates get lost.

Likely follow-ups
"The single-statement increment is in place, and now that one row is the hottest lock in the database. Show me the sharded counter concretely."

Create page_view_shards(page_id, shard, views, PRIMARY KEY (page_id, shard)) with, say, sixteen rows per page, shard 0 through 15. Each increment does UPDATE page_view_shards SET views = views + 1 WHERE page_id = ? AND shard = ? with the shard chosen at random or from a hash of the thread id.

Contention drops by roughly the shard count because writers spread across sixteen row locks. Reads become SELECT SUM(views) FROM page_view_shards WHERE page_id = ?, which is sixteen index entries, still trivial.

In Postgres each increment also creates a dead tuple, so autovacuum on that table needs aggressive settings; the shards help there too by spreading updates over more pages. I would pick the shard count from measured lock wait time, not guess.

"What is the actual loss window with the Redis-batched approach, and how do you make it acceptable?"

Whatever has been accumulated since the last flush.

If a service instance increments a Redis key and a job flushes the delta to the database every ten seconds, a Redis crash loses at most ten seconds of counts, and an instance crash between increment and flush loses nothing because Redis holds the state.

To make it acceptable I state the number explicitly in the design — "page views may undercount by up to ten seconds of traffic on a Redis failure" — and I make the flush idempotent by flushing with INCRBY-style deltas that are read-and-reset atomically in Redis using GETDEL or a Lua script, so a flush that fails after the database write but before the reset cannot double-count. For anything with money attached, this approach is off the table.

"Why does this drift lower and never higher?"

Because every failure mode of read-modify-write discards increments; none duplicates them. When ten threads read 500, each writes 501, so nine increments vanish, but nothing ever writes 502 without a corresponding view.

The only way it could drift higher is a retry after a successful write — a client that timed out and repeated the increment — and that is a different bug with the opposite sign.

This asymmetry is diagnostic: a counter that is consistently low under load and correct at low traffic is a lost update almost every time, while one that is high suggests duplicate delivery.

I would prove it by comparing against an independent source, such as web server access logs for the page, over an hour of peak traffic.

Q27. "How can a reader read a row that another transaction is busy updating — without blocking and without seeing garbage?"

Reveal answer

Strong answer Through MVCC — multi-version concurrency control. A writer never destroys the committed version of a row; it creates a new version, and readers continue to read the old committed one.

Which version a reader sees is decided by its snapshot — a record of which transactions' work was committed at the moment the snapshot was taken.

The reader takes no row locks, so it blocks nobody; the writer waits for no readers, so readers cannot stall it.

Mechanically the engines differ: InnoDB stores the newest version in place, with each row carrying the id of the transaction that wrote it and a pointer into the undo log, and a reader reconstructs older versions by walking that chain backwards.

Postgres keeps whole old row versions — called tuples — side by side in the table, each stamped with the creating and deleting transaction ids, and visibility is computed per tuple.

Land it The price of never blocking readers is keeping history around — and every MVCC operational problem, from undo growth to vacuum bloat, is the bill for that history.

Likely follow-ups
"What exactly is in a snapshot, and how does the engine decide a version is visible?"

In Postgres a snapshot is three things: xmin, the lowest transaction id still running when the snapshot was taken; xmax, the next id to be assigned; and a list of ids in between that were still in progress.

A row version is visible if its creating transaction id is below xmax, not in the in-progress list, and committed, and its deleting transaction id, if any, is not visible by the same test.

InnoDB's read view is the same idea: a low water mark, a high water mark, and the list of active transaction ids at creation.

Each row carries the id of the transaction that last changed it, and if that id is not visible, InnoDB follows the undo pointer to an older version until it finds one that is. Visibility is a pure comparison, with no locks.

"Are there any cases where a reader does block in an MVCC engine?"

Yes, on table-level locks and on locking reads.

A plain SELECT waits behind DDL that holds an exclusive table lock — an ALTER TABLE, TRUNCATE, or in Postgres VACUUM FULL and a non-concurrent REINDEX — and in MySQL it also waits behind a pending metadata lock, which is how one slow ALTER queues every query on the table.

A SELECT ... FOR UPDATE or FOR SHARE is a locking read and waits for conflicting row locks. At InnoDB SERIALIZABLE every plain SELECT becomes a locking read.

And in Postgres, a reader on a hot standby can be cancelled, not blocked, when the primary's vacuum removes a version the reader needed, unless hot_standby_feedback is on. Outside those, readers and writers never wait for each other.

"What does reading an old version cost, and when does it become expensive?"

In Postgres, nothing extra: every version is a physical tuple in the heap, and the reader just checks headers, so reading an old version costs the same as reading the newest. The cost surfaces later as bloat, because those versions occupy pages.

In InnoDB, reading an old version means following the row's undo pointer and reconstructing the older image, one hop per intervening change. If a row has been updated a thousand times since my snapshot was taken, my read walks a thousand undo records.

That is why a long-running report on InnoDB gets slower the longer it runs on a busy table, and why a huge history list length correlates with slow reads. The monitoring signal is the history list length; the fix is shorter snapshots.

Q28. "Where do old row versions physically live in InnoDB versus Postgres, and what different operational headaches follow from that choice?"

Reveal answer

Strong answer InnoDB keeps them out-of-line: the table holds only the newest version, and old versions are reconstructed from the undo log, which lives in separate undo tablespaces. Purge threads trim undo records once no active snapshot could need them.

The headache: a long-running transaction pins that history — the "history list length" in SHOW ENGINE INNODB STATUS climbs, undo tablespaces balloon on disk, and reads slow down because reconstructing an old version means walking an ever-longer chain.

Postgres keeps them in-line: an update leaves the old version — a dead tuple, a row version no live snapshot can see — sitting in the table itself, and VACUUM, the cleanup process, reclaims that space later.

The headache: bloat — dead space inside your actual tables and indexes, so scans touch more pages — and a long transaction blocks vacuum from cleaning anything it might still see.

Same disease, different organ: in InnoDB the history bloats a side structure; in Postgres it bloats the tables you query.

Land it Monitor the same root metric on both — the age of the oldest open transaction — because that is the horizon behind which neither purge nor vacuum is allowed to clean.

Likely follow-ups
"Which design would you rather operate, and why?"

For a write-heavy OLTP table with many updates per row, I find InnoDB's design easier to live with day to day: the table stays compact, old versions live in a side structure that is trimmed continuously, and the failure mode — undo growth — is one metric to watch.

Postgres puts the history in the table itself, so bloat affects the pages every query reads, indexes accumulate dead entries, and I have to tune autovacuum per table and watch for anything that pins the horizon.

On the other hand, Postgres makes rollback free, never needs to reconstruct versions on read, and its bloat is visible and measurable with pgstattuple. Both are fine when transactions are short; the discipline that matters most is the same in both, which is transaction age.

"Tell me about Postgres HOT updates. Why do they matter for this?"

Heap-only tuple updates are Postgres's way of reducing the cost of in-line versioning.

When an UPDATE does not change any indexed column and there is room on the same heap page, Postgres writes the new version on that page and links it from the old one, and the indexes are not touched at all — they still point at the old slot, which chains to the new version.

That avoids one index insert per index per update, and lets space be reclaimed on the page itself without a full vacuum.

To get HOT updates, I keep frequently updated columns out of indexes and set a lower fillfactor, say 80, on hot tables so pages have room. pg_stat_user_tables.n_tup_hot_upd versus n_tup_upd shows the hit rate.

"What are the two or three metrics you would put on a dashboard for each engine?"

For InnoDB: the history list length from SHOW ENGINE INNODB STATUS or information_schema.innodb_metrics under trx_rseg_history_len, the age of the oldest transaction from innodb_trx, and undo tablespace size on disk.

For Postgres: the age of the oldest transaction and oldest idle-in-transaction session from pg_stat_activity, dead tuple counts and the time since last autovacuum per table from pg_stat_user_tables, and age(datfrozenxid) per database for wraparound.

In both, I alert on oldest transaction age first, because it is the leading indicator: everything else follows from a snapshot pinned too long. Bloat ratio from pgstattuple is a weekly check, not a live alert.

"Does a long-running SELECT pin history the same way a long-running write transaction does?"

Yes, and that surprises people. Cleanup is bounded by the oldest snapshot, and a read-only transaction holds a snapshot exactly like a writer.

A reporting query that runs for two hours at REPEATABLE READ, or even a two-hour single statement at READ COMMITTED, prevents Postgres from vacuuming any dead tuple created after it started, in any table, and prevents InnoDB purge from trimming undo beyond that point.

The only exemption is InnoDB's optimisation where read-only transactions do not get a transaction id, which avoids some bookkeeping but does not release the read view.

The mitigation is running long reads on a replica, where a pinned horizon only affects that replica, or splitting them into shorter snapshots.

Q29 · Scenario. "A batch job hung this morning. Hours later, the database is slowing down, disk usage is climbing, and unrelated queries are stuck on locks. Walk me through the diagnosis."

Reveal answer

Strong answer The signature — slowdown plus disk growth plus lock waits, hours after a hang — says forgotten open transaction, and I would confirm it directly:

  1. Find old transactions. Postgres: SELECT pid, xact_start, state, query FROM pg_stat_activity ORDER BY xact_start; — the smoking gun is a session in state idle in transaction with an xact_start hours old: it began a transaction, did some work, and is now waiting on nothing, holding everything. MySQL: SELECT * FROM information_schema.innodb_trx ORDER BY trx_started;.
  2. Explain the three damages to the team. The locks: every row the job wrote before hanging is still exclusively locked, and blocked sessions pile up behind them — hence the stuck queries. The history: its snapshot pins the MVCC cleanup horizon, so InnoDB's undo log grows unboundedly, or Postgres's vacuum cannot reclaim any dead tuple newer than that snapshot — hence the disk climb and general slowdown.
  3. Fix now: kill the session — pg_terminate_backend(pid) or MySQL's KILL with the id — knowing its work rolls back, and knowing an InnoDB rollback of a big half-done batch takes real time.
  4. Prevent: set idle_in_transaction_session_timeout in Postgres so the server ends such sessions itself; give batch jobs chunked commits and statement timeouts; alert on the age of the oldest transaction, which is the one metric that catches this whole class early.

Land it An idle transaction is not idle to the database — it is actively holding locks and actively forbidding cleanup, and it costs you by the hour.

Likely follow-ups
"You killed the session and the database is still slow an hour later. Why, and what do you check?"

Killing releases the locks immediately but not the history. On InnoDB, the transaction must roll back first, and a batch that wrote millions of rows can take a long time to undo, during which the rows stay locked; innodb_trx shows trx_state = ROLLING BACK.

After that, purge has to work through a history list that may be tens of millions long, and until it does, reads on affected rows still walk long undo chains.

On Postgres, the dead tuples the job left and everything vacuum was prevented from cleaning are still there; autovacuum now has hours of backlog, and bloated tables and indexes stay bloated until it runs, and the space itself is not returned without a rebuild.

I would watch history list length or n_dead_tup falling, and if needed run manual VACUUM or a concurrent reindex on the worst tables.

"How would you tell 'idle in transaction' from a transaction that is genuinely doing work?"

By the state column and the timestamps.

In pg_stat_activity, state = 'active' with query_start advancing means statements are running; state = 'idle in transaction' with state_change hours ago means the client opened a transaction, ran something, and has been silent since — typically a hung thread, a forgotten commit in a code path, or a connection returned to a pool without commit.

In MySQL, innodb_trx shows trx_state = RUNNING for both, but trx_query is NULL for an idle transaction and processlist.COMMAND = Sleep with a nonzero trx_rows_locked is the equivalent tell. The pair of "no current statement" and "old transaction start" is what identifies the forgotten transaction.

"What code shapes in a Java service produce a forgotten open transaction?"

A few recurring ones.

Manual setAutoCommit(false) on a connection with an exception path that skips the commit and rollback and returns the connection to the pool still in a transaction; Hikari partially guards this by rolling back on return if it detects a dirty state, but not every pool does.

A @Transactional method that blocks on a remote call, a queue take, or a lock inside the transaction, so the transaction is open but idle from the database's view. A Statement or ResultSet held open across requests.

And in Postgres, a JDBC ResultSet with a fetch size, which requires an open transaction for the cursor. I look for these with idle_in_transaction_session_timeout set to a small value in staging so they fail loudly during testing.

"What values would you set for the timeouts, and what breaks if you set them too low?"

For an OLTP application role in Postgres: idle_in_transaction_session_timeout = '30s', statement_timeout = '5s' or a per-endpoint override, and lock_timeout = '2s'. For a batch role, longer values, but still finite — minutes, not hours. On MySQL, innodb_lock_wait_timeout = 5 and max_execution_time for selects.

Too low and legitimate work fails: a report that needs ten minutes hits the statement timeout, a migration is killed mid-way, a slow but healthy lock wait errors during a traffic spike.

The way to avoid that is separate roles or connection pools with separate settings for interactive and batch work, so tightening the interactive path does not break the batch path.

Q30. "Explain Postgres transaction ID wraparound in one honest paragraph."

Reveal answer

Strong answer Every row version in Postgres is stamped with the 32-bit id of the transaction that created it, and visibility is decided by comparing ids in a circular space: roughly two billion ids count as "the past" and two billion as "the future" relative to now.

If a table's old rows are never frozen — vacuum's act of marking them "visible to everyone, regardless of id" — then after about two billion newer transactions, those ancient ids wrap around and suddenly compare as the future, making committed rows invisible: silent data loss in effect.

Postgres refuses to let that happen — escalating log warnings, then forced aggressive autovacuum, and ultimately it stops accepting new transactions until vacuum catches up.

In practice wraparound trouble is always a symptom of the same causes: autovacuum starved or misconfigured, a very long-lived transaction, or an abandoned replication slot pinning the horizon. Monitoring is one query: SELECT datname, age(datfrozenxid) FROM pg_database; — alert well before the two-billion ceiling.

Land it Wraparound is not an exotic failure — it is simply what eventually happens when vacuum is prevented from doing its job for long enough, so the fix is always "find what is blocking vacuum".

Likely follow-ups
"What does 'freezing' actually do to a row, and why is it safe?"

Freezing sets a flag bit in the tuple header saying "the creating transaction is committed and older than every possible snapshot", so visibility checks stop comparing its transaction id altogether.

Once that bit is set, the original id no longer matters and can wrap around any number of times without affecting the row.

It is safe because vacuum only freezes rows whose creating transaction is older than vacuum_freeze_min_age, default fifty million transactions, and is committed, which guarantees every current and future snapshot would see it anyway.

Postgres 9.4 and later use the flag bit instead of overwriting the id, which preserves forensic information. Freezing also lets the visibility map mark a page all-frozen so future vacuums skip it entirely.

"What does the emergency actually look like, and how do you get out of it?"

At about forty million transactions before the limit, Postgres logs warnings; at three million, it refuses new transactions with "database is not accepting commands to avoid wraparound data loss".

Before Postgres 14, the fix required single-user mode; since then, the database still accepts VACUUM in that state.

The way out is to find what is pinning the horizon and remove it: kill the oldest transaction in pg_stat_activity, drop or advance any inactive replication slot in pg_replication_slots, roll back orphaned prepared transactions in pg_prepared_xacts.

Then run VACUUM FREEZE on the tables with the oldest relfrozenxid, found by SELECT relname, age(relfrozenxid) FROM pg_class ORDER BY 2 DESC. It may take hours on a large table; the priority order is the oldest table first.

"Why did a replication slot cause wraparound? It is not a transaction."

Because a logical replication slot records the oldest transaction id its consumer still needs, in catalog_xmin, and Postgres will not freeze or remove catalog rows beyond it.

If the consumer — a Debezium connector, a logical replica — stops and nobody drops the slot, that xmin stays fixed forever while the database keeps consuming ids toward the two-billion ceiling.

Physical slots hold WAL rather than transaction ids, so they fill the disk instead of causing wraparound, unless hot_standby_feedback is on, in which case the standby's oldest query is reflected back as an xmin too.

Since Postgres 13, max_slot_wal_keep_size bounds the WAL retention; the transaction-id pinning is bounded by monitoring, so I alert on pg_replication_slots.active = false and on the age of each slot's xmin.

"Does MySQL have an equivalent problem?"

Not in the same form. InnoDB transaction ids are 64-bit, so exhausting them is not a practical concern, and rows do not need freezing.

The closest analogue is undo history: a long-lived snapshot or a stopped purge lets the history list and undo tablespaces grow without bound, and that degrades performance and fills disk rather than corrupting visibility.

There is a related 32-bit limit in InnoDB's row id counter for tables without a primary key, and older MySQL versions had auto-increment INT overflow that silently failed inserts, but neither is a wraparound of visibility.

So the Postgres-specific operational duty is freezing, and a Postgres shop needs the wraparound alert in place from day one.

Q31. "When exactly is a snapshot taken? Compare statement versus transaction start — and Postgres versus MySQL."

Reveal answer

The real test A precision question — the wrong guess is "at BEGIN", and both engines say no.

Strong answer At READ COMMITTED, both engines take a fresh snapshot for every statement — that is the definition of the level. At REPEATABLE READ there is one snapshot for the whole transaction, but it is not taken at BEGIN in either engine.

Postgres takes it at the first statement after BEGIN. InnoDB takes it at the first consistent read — the first plain SELECT — so a transaction that starts with an UPDATE, or that sits idle after START TRANSACTION, has no snapshot yet, and the eventual first SELECT sees everything committed up to that moment.

If you genuinely need the snapshot at the start, MySQL offers START TRANSACTION WITH CONSISTENT SNAPSHOT. The practical consequence: "BEGIN, then wait, then read" does not freeze time at BEGIN, and two transactions started together can still see different worlds depending on when each first read.

Land it Say "snapshot at first read, not at BEGIN" and you have answered the trap most candidates fall into.

Likely follow-ups
"Why would anyone need the snapshot at BEGIN rather than at first read?"

Coordinated reads across sessions.

A backup or a multi-threaded export wants several connections to read the same instant: mysqldump --single-transaction uses START TRANSACTION WITH CONSISTENT SNAPSHOT so the snapshot is fixed at a known point that it can pair with the binlog position it records for replication setup.

Postgres gets the same effect with pg_export_snapshot() in one session and SET TRANSACTION SNAPSHOT in the others, which is what pg_dump --jobs does.

Application code almost never needs it; the only case is when the code records "as of" timestamps before the first query and the difference would matter for an audit. Otherwise, snapshot-at-first-read is a harmless detail, as long as nobody assumes BEGIN froze time.

"In InnoDB, if the first statement is an UPDATE, what does a later SELECT see?"

Everything committed up to the moment of that SELECT, plus the transaction's own UPDATE.

The UPDATE is a current read and does not create a read view, so the read view is created when the first plain SELECT runs, possibly seconds later, and includes commits that happened after the UPDATE.

That means the transaction is not reading from "the start", and a check like "update the order, then select to verify the state" can see other sessions' changes mixed in.

If the sequence matters, I start with START TRANSACTION WITH CONSISTENT SNAPSHOT, or run a cheap SELECT first to pin the view. At READ COMMITTED none of this applies, since every statement is fresh anyway.

"How would you demonstrate the difference between BEGIN and first read in a test?"

Two sessions, at REPEATABLE READ. In session one: BEGIN, then do nothing. In session two: insert a row and commit.

In session one: SELECT COUNT(*) from that table, and the new row is counted, proving the snapshot was not taken at BEGIN. Then in session two insert another row and commit, and session one's second SELECT does not count it, proving the snapshot was fixed at the first read.

Repeat with START TRANSACTION WITH CONSISTENT SNAPSHOT on MySQL and the first SELECT excludes the first insert. I would put that in the team's onboarding notes with the SQL, because it takes two minutes and permanently fixes the mental model.

Q32. "Who cleans up old row versions in each engine, and what can stop them from doing it?"

Reveal answer

Strong answer In InnoDB it is the purge threads: background threads that remove undo records, and physically remove delete-marked rows, once no active transaction's snapshot could still need them. When purge falls behind, the symptom is a growing "History list length" in SHOW ENGINE INNODB STATUS.

In Postgres it is autovacuum: background workers that scan tables for dead tuples, mark the space reusable, tidy indexes, and freeze old transaction ids.

What stops each of them is the same category of thing — anything that pins the visibility horizon: the oldest running transaction, and in Postgres also abandoned replication slots, orphaned prepared transactions, and on replicas hot_standby_feedback holding the primary's cleanup back.

Autovacuum can additionally simply be too lazy for a hot table — thresholds tuned for small tables scale badly to hundred-million-row ones, so per-table autovacuum settings are a normal tuning task.

Land it Cleanup can never pass the oldest snapshot in the system — so monitoring the oldest transaction, slot, and prepared transaction is monitoring cleanup itself.

Likely follow-ups
"Autovacuum is running but a 200-million-row table never gets vacuumed. What settings do you change?"

The trigger is autovacuum_vacuum_threshold + autovacuum_vacuum_scale_factor × rows, with defaults 50 and 0.2, so that table needs forty million dead rows before autovacuum starts, which is far too late.

I set per-table storage parameters: ALTER TABLE big SET (autovacuum_vacuum_scale_factor = 0.01, autovacuum_vacuum_threshold = 10000), and the same for analyze. Then I check it can keep up: autovacuum_vacuum_cost_delay, default two milliseconds, and autovacuum_vacuum_cost_limit throttle it, and on modern SSDs I raise the cost limit substantially.

If it still cannot keep pace, increase autovacuum_max_workers, default three, remembering workers share the cost limit. pg_stat_progress_vacuum shows a running vacuum's progress, and last_autovacuum in pg_stat_user_tables confirms it is actually firing.

"How does hot_standby_feedback stop cleanup on the primary, and what is the alternative?"

On a streaming replica, a long query needs old row versions that the primary may have vacuumed away; when the replica replays that vacuum, it must cancel the query, giving "canceling statement due to conflict with recovery".

hot_standby_feedback = on fixes that by sending the replica's oldest snapshot back to the primary, which then treats it like a local long transaction and stops vacuuming beyond it. So a three-hour report on the replica bloats the primary.

The alternative is max_standby_streaming_delay, which lets the replica pause applying WAL for up to that long before cancelling the query, buying the report time at the cost of replica lag instead of primary bloat.

I pick per replica: feedback on for short-query replicas, delay for the dedicated reporting replica.

"How does InnoDB purge fall behind even with no long transactions?"

Because purge is throttled and single-purpose.

It runs on innodb_purge_threads, default four, and processes undo records in batches of innodb_purge_batch_size; a burst of deletes or updates that generates undo faster than those threads can consume it makes the history list grow even though no snapshot pins anything.

Heavy secondary-index churn makes it worse because purge must remove delete-marked index entries too. When the history list exceeds innodb_max_purge_lag, if set, InnoDB delays DML to let purge catch up.

The remedies are more purge threads on a machine with spare cores, spreading bulk deletes over time, and checking that purge is not blocked by an old read view from a monitoring tool holding a transaction open.

"What does an orphaned prepared transaction look like and how does it happen?"

It is a transaction that ran PREPARE TRANSACTION 'id' as the first phase of two-phase commit and never received the COMMIT PREPARED or ROLLBACK PREPARED, usually because the XA coordinator — a Java application server with JTA — crashed or was redeployed without recovery.

The prepared transaction survives even a database restart, holds its locks, and holds its snapshot horizon indefinitely. In Postgres it appears in pg_prepared_xacts with a prepared timestamp; in MySQL, XA RECOVER lists them.

Once I confirm with the application owner that the coordinator has no record of it, I ROLLBACK PREPARED. I alert on any prepared transaction older than a minute, because a legitimate one lasts milliseconds.

Drill · Locks, deadlocks & transaction discipline

The final group tests whether you can read lock evidence under pressure, rank the fixes, and run transactions in a Java service with the discipline that prevents the incident in the first place.

Q33. "Shared versus exclusive row locks — who blocks whom, and where does each kind come from?"

Reveal answer

Strong answer A shared lock (S) says "I am reading this row and it must not change" — any number of transactions can hold S on the same row at once.

An exclusive lock (X) says "I am changing this row" — exactly one holder, and it blocks both other X requests and S requests. So readers-with-locks coexist; writers exclude everyone.

Where they arise: plain SELECTs in MVCC engines take no row locks at all — that is the whole point of snapshots. SELECT ... FOR SHARE takes S; UPDATE, DELETE, and SELECT ... FOR UPDATE take X; foreign-key checks take a shared-type lock on the referenced parent row.

InnoDB adds table-level intention locks — cheap flags saying "I hold row locks somewhere in this table" — so a table-level operation can detect conflicts without scanning every row lock.

One classic trap: two transactions holding S on the same row, each then requesting X, deadlock instantly — never take S planning to upgrade.

Land it If you intend to write, lock exclusively from the start — the S-then-upgrade pattern is a deadlock generator, which is why FOR UPDATE exists.

Likely follow-ups
"Explain intention locks properly. Why are they needed and what conflicts with them?"

An intention lock is a table-level flag that says "some transaction holds or will hold row locks of this kind in this table".

Before InnoDB takes a shared row lock it takes an intention-shared lock, IS, on the table; before an exclusive row lock, intention-exclusive, IX. Intention locks are compatible with each other — many transactions can hold IX at once — so they never block normal DML. Their purpose is to let a table-level operation like LOCK TABLES ... WRITE or some DDL check for conflicts in one step: an exclusive table lock conflicts with any IS or IX, so the DDL knows there are row locks somewhere without scanning them.

In performance_schema.data_locks they appear as LOCK_TYPE = TABLE with mode IX; seeing them is normal, not a problem.

"Walk me through the shared-then-upgrade deadlock in detail."

Transaction A runs SELECT ... WHERE id = 1 FOR SHARE and holds S on row 1. Transaction B runs the same and also holds S, which is allowed. A now runs UPDATE ... WHERE id = 1, needs X, and X conflicts with B's S, so A waits.

B runs its UPDATE, needs X, conflicts with A's S, and waits. Cycle. InnoDB detects it immediately and rolls back one with error 1213; Postgres detects it after deadlock_timeout and aborts one with 40P01.

The same thing happens implicitly at InnoDB SERIALIZABLE, where plain reads become shared locking reads.

The rule is that a read whose purpose is to precede a write should take X from the start with FOR UPDATE; S is only for "keep this unchanged while I write something else".

"How do the two engines differ in where they store row locks?"

InnoDB keeps row locks in an in-memory lock table, hashed by page, with a bitmap per page marking locked records; that is why the lock count can be enormous for a full scan and why memory for locks is a consideration, and it is also why data_locks can list them all. Postgres stores row locks inside the tuple itself: the xmax field of the tuple header records the locking transaction, and a waiter blocks on that transaction's id rather than on a row-lock object. That means Postgres can lock unlimited rows without memory growth, but a locked row is physically modified — a heap page write — and information about who holds which row lock is not directly listed; pg_locks shows the transaction-level waits and pgrowlocks is needed to see per-row holders.

Q34 · Scenario. "An UPDATE with a WHERE on an unindexed column froze half the app in MySQL — yet it matched only 12 rows. Explain."

Reveal answer

The real test Whether you know InnoDB locks what it scans, not what it matches.

Strong answer InnoDB takes locks on index records as it scans them. With no usable index on the WHERE column, the UPDATE walks the clustered index — every row in the table — and at REPEATABLE READ it takes next-key locks on each examined row, matched or not. Twelve rows changed; a million rows locked. Every concurrent write to that table now queues, which is the app-wide freeze.

  1. Confirm: EXPLAIN shows a full table scan for that WHERE; performance_schema.data_locks or the lock counts in SHOW ENGINE INNODB STATUS show the lock count wildly exceeding the matched-row count.
  2. Fix: index the WHERE column, so the scan — and therefore the locking — narrows to the matching index range. Alternatively, chunk the update by primary key ranges.
  3. Mitigation context: at READ COMMITTED, InnoDB releases record locks on non-matching rows after examining them and skips gap locks, so the same mistake hurts far less — one reason busy write-heavy shops run READ COMMITTED.
  4. Contrast for the interviewer: Postgres marks lock information inside the row versions themselves and only locks rows that actually match, so the same statement there is merely slow, not a de facto table lock.

Land it In InnoDB a missing index is not just a performance bug, it is a concurrency bug — the scan's footprint is the lock's footprint.

Likely follow-ups
"You cannot add the index right now — the table is huge and the DDL would take an hour. What do you do for tonight's run?"

Two options that need no DDL. First, run the session at READ COMMITTED: SET SESSION transaction_isolation = 'READ-COMMITTED' before the UPDATE. InnoDB then releases the locks on non-matching rows after examining them and takes no gap locks, so the footprint shrinks to the twelve matched rows plus a moment's lock on each scanned one.

Second, chunk by primary key range: UPDATE t SET ... WHERE unindexed = ? AND id BETWEEN ? AND ? in steps of ten thousand, committing each, so any moment's lock footprint is one chunk and other writers slip in between chunks.

I would do both and run it at low traffic. Then the index gets built online with ALGORITHM=INPLACE, LOCK=NONE in a maintenance window.

"How would you prove the lock footprint claim to a sceptical DBA?"

With a live reproduction on a copy. In session one, at REPEATABLE READ, BEGIN and run the UPDATE without committing.

In session two, SELECT COUNT(*) FROM performance_schema.data_locks WHERE OBJECT_NAME = 't'; the count equals the number of scanned rows, in the millions, not twelve, and the lock modes are X next-key locks.

Then in session two try an INSERT or an UPDATE of an unrelated row in the same table; it blocks, and data_lock_waits shows why. Repeat the whole thing with the session at READ COMMITTED and the count drops to twelve.

The SHOW ENGINE INNODB STATUS transaction section also shows "lock struct(s), heap size, N row lock(s)" per transaction, which is the older way to see the same number.

"Would a DELETE or a SELECT FOR UPDATE with the same WHERE behave the same way?"

Yes, all three are locking statements and follow the same rule: InnoDB locks the index records it scans, so with no usable index each of them takes next-key locks on every row at REPEATABLE READ. A plain SELECT is the exception; it takes no locks and reads the snapshot, so a full-scan SELECT is merely slow. The one subtlety is that DELETE and UPDATE with a matched primary-key range still lock only that range, so "unindexed WHERE column" is the trigger, not the statement type. That is why I treat any locking statement in code review as requiring an EXPLAIN that shows an index seek, and why the slow query log with log_queries_not_using_indexes is worth turning on in staging.

"Postgres only locks matched rows, so is a full-scan UPDATE harmless there?"

Not harmless, just not a table lock. The UPDATE still reads every page, which is slow and pushes hot pages out of cache, and on a large table it can run for minutes.

During that time it holds a ROW EXCLUSIVE table lock, which does not block other DML but does block DDL such as CREATE INDEX without CONCURRENTLY or ALTER TABLE, and any DDL queued behind it in turn blocks every later query, including plain SELECTs.

It also holds its twelve row locks and its snapshot for the whole scan, pinning vacuum. So the statement itself lets the app run, but a long full-scan UPDATE is still an incident waiting for a migration to be queued behind it. The index is the right fix in both engines.

Q35. "What's the difference between a lock wait and a deadlock, and how does each engine handle each?"

Reveal answer

Strong answer A lock wait is healthy queueing: I want a lock someone holds, I wait, they commit, I proceed.

It only becomes a problem when the holder is slow, so it is bounded by a timeout — innodb_lock_wait_timeout, default 50 seconds, which raises error 1205 and by default rolls back only the waiting statement, not the whole transaction, unless innodb_rollback_on_timeout is set; Postgres's lock_timeout is unset by default, meaning it will wait forever unless you configure it, which you should.

A deadlock is different in kind: a cycle — I hold what you want and you hold what I want — so no amount of waiting helps, and timeouts would just make everyone suffer 50 seconds first.

Both engines therefore detect deadlocks and break them by force. InnoDB checks the wait-for graph the moment a wait begins and immediately rolls back the transaction with the least undo work, raising error 1213.

Postgres waits deadlock_timeout — one second by default — then runs detection and aborts one participant with SQLSTATE 40P01.

Land it The operational takeaway: timeouts are for slow holders, detection is for cycles — and both errors mean "somebody must retry", so the application owns the last step.

Likely follow-ups
"Why does InnoDB by default roll back only the statement on lock wait timeout, and why is that dangerous?"

Historically it let a client decide whether to retry just the failed statement while keeping the transaction's earlier work.

The danger is that most application code does not distinguish: it catches the exception, and the transaction is still open with earlier statements applied and their locks held.

If the code then continues or commits, it commits a partial transaction — atomicity broken from the application's point of view. If it forgets to roll back and returns the connection to the pool, it is a forgotten open transaction.

Setting innodb_rollback_on_timeout = ON makes error 1205 roll back the whole transaction, which is the behaviour Postgres has by default and the one I want. Either way, the application must treat 1205 as "transaction dead, start over".

"Postgres waits one second before checking for deadlocks. Why not check immediately like InnoDB?"

Cost. Deadlock detection walks the wait-for graph, which requires taking locks on the shared lock manager structures, and doing that on every lock wait would slow the common case, where the wait resolves in microseconds.

Postgres bets that most waits are short, so it sleeps deadlock_timeout, default one second, and only then runs the check. The cost is that a real deadlock costs everyone at least a second.

InnoDB checks eagerly because its lock table is designed for it, though it also caps the search and, under very high concurrency, can be switched to timeout-only mode with innodb_deadlock_detect = OFF to avoid the detection cost.

Lowering deadlock_timeout to a few hundred milliseconds is reasonable on a system with frequent deadlocks.

"What are the exact error codes and SQLSTATEs for each case, and how does Spring map them?"

MySQL: lock wait timeout is error 1205 with SQLSTATE HY000, and deadlock is 1213 with SQLSTATE 40001. Postgres: lock wait timeout via lock_timeout is SQLSTATE 55P03, deadlock is 40P01, serialization failure is 40001, and a statement timeout is 57014.

Spring's SQLErrorCodeSQLExceptionTranslator maps MySQL 1213 and Postgres 40P01 and 40001 to CannotAcquireLockException or DeadlockLoserDataAccessException, both subclasses of PessimisticLockingFailureException in recent Spring versions, and 55P03 and 1205 to CannotAcquireLockException or QueryTimeoutException depending on version.

Because those mappings shift between releases, I test the retry filter against the real exception thrown in my stack rather than trusting the class name from memory.

"How would you set lock_timeout in Postgres without a global config change?"

Per role, which is the cleanest: ALTER ROLE app_user SET lock_timeout = '2s', and the setting applies to every new session for that role.

Per session or per transaction from the application: SET LOCAL lock_timeout = '2s' at the start of a transaction, which reverts at commit and is safe behind transaction-mode poolers. In JDBC, the URL option options=-c lock_timeout=2s sets it at connection time.

For migrations I use SET lock_timeout = '5s' before any DDL so the ALTER gives up rather than queueing behind a long transaction and blocking everything, and I wrap it in a retry loop. Per-role settings can be inspected in pg_db_role_setting.

Q36 · Scenario. "Production throws intermittent deadlock errors. Walk me through one concrete deadlock step by step, how you read the evidence, and the fixes in order of preference."

Reveal answer

Strong answer The canonical case is two transactions touching the same two rows in opposite order.

  1. T1 updates account 1 — takes an exclusive lock on row 1. T2 updates account 2 — takes an exclusive lock on row 2.
  2. T1 now updates account 2 — must wait for T2. T2 now updates account 1 — must wait for T1. The waits form a cycle; neither can ever proceed.
  3. InnoDB detects the cycle immediately and rolls back the cheaper victim with error 1213; Postgres detects after one second and aborts one with 40P01.

The evidence: in MySQL, SHOW ENGINE INNODB STATUS keeps a "LATEST DETECTED DEADLOCK" section showing both transactions, their last statements, and exactly which locks each held and waited for. Postgres writes the equivalent to its log: "Process 8250 waits for ShareLock on transaction 1023; blocked by process 8255" with both queries.

show-engine-innodb-status.txt
------------------------
LATEST DETECTED DEADLOCK
------------------------
*** (1) TRANSACTION:
TRANSACTION 421772, ACTIVE 3 sec starting index read
UPDATE accounts SET balance = balance - 50 WHERE id = 2
*** (1) HOLDS THE LOCK(S):
RECORD LOCKS ... index PRIMARY of table shop.accounts
Record lock, heap no 2 (id = 1) ... lock_mode X
*** (1) WAITING FOR THIS LOCK TO BE GRANTED:
Record lock, heap no 3 (id = 2) ... lock_mode X waiting
*** (2) TRANSACTION:
TRANSACTION 421773, ACTIVE 2 sec starting index read
UPDATE accounts SET balance = balance + 50 WHERE id = 1
*** (2) HOLDS THE LOCK(S):  record lock on id = 2, lock_mode X
*** (2) WAITING FOR:        record lock on id = 1, lock_mode X waiting
*** WE ROLL BACK TRANSACTION (1)

The fixes, ranked:

  1. Consistent lock ordering — the real cure. If every transaction touches rows in one agreed order, sorted account ids in a transfer, cycles cannot form.
  2. Shorter transactions holding fewer locks for less time — shrinks the collision window.
  3. Reduce lock footprint: proper indexes so scans lock less, and READ COMMITTED where gap locks are the culprit.
  4. Retry on 1213 / 40P01 as the backstop — a low, steady deadlock rate is normal in a busy system, not a fire.

Land it Deadlocks are an ordering problem, so the durable fix is imposing an order — everything else only lowers the frequency.

Likely follow-ups
"You imposed consistent lock ordering and deadlocks continue. What did you miss?"

Locks I did not write.

The usual hidden ones: foreign-key checks taking shared locks on parent rows in an order determined by which child rows I insert; secondary unique index checks taking locks in index order rather than primary-key order; InnoDB gap locks from range scans, which lock ranges rather than rows and are compatible with each other until an insert arrives; and locks taken by triggers or ORM cascades that execute in an order the application code never specified.

The deadlock report shows the actual locks — if it lists a gap, a secondary index name, or a table I did not think I touched, that is the missing edge.

Also check that every code path, including batch jobs and admin tools, sorts by the same key; one unsorted path breaks the ordering for everyone.

"How do you get the full history of deadlocks rather than just the latest one?"

In MySQL, SHOW ENGINE INNODB STATUS keeps only the latest, so I enable innodb_print_all_deadlocks = ON, which writes every deadlock to the error log, and I ship that log to central logging where I can count them per statement fingerprint.

In Postgres, every deadlock is logged by default with both queries and the process ids, as long as log_lock_waits is also on for the waits that did not become deadlocks.

From there I build a metric: deadlocks per minute, broken down by the pair of tables involved. A steady low rate with retries succeeding is normal; a spike after a deploy is a regression in lock order that I can bisect to the commit.

"Why does InnoDB pick the transaction with the least undo as the victim, and can you influence it?"

Because rolling back is proportional to the undo written, so the victim with the least undo is the cheapest to roll back and the least work lost. Postgres, by contrast, aborts the transaction that happened to run the detection check, which is roughly random.

You cannot set a priority per transaction in either engine as of Aug 2026, so the way to influence it is to shape the transactions: keep the important transaction small and quick so it rarely participates, and put a retry loop on the ones that can afford it.

If a critical transaction must not be the victim, take its locks in one batch at the start, or serialize the whole operation through an advisory lock so it never enters a cycle at all.

"Can a deadlock involve a single table and a single statement?"

Yes. Two UPDATE ... WHERE id IN (1, 2) statements can lock rows in different orders if the plan walks different indexes or if one is IN (1,2) and the other IN (2,1) with a plan that respects list order.

Two inserts into the same gap under a prior gap lock is the InnoDB single-table case.

And an UPDATE that changes a column with a secondary index locks the primary-key record, then the secondary-index entries, while a concurrent UPDATE via the secondary index locks in the opposite order — an index-order deadlock within one statement.

The mitigation for multi-row statements is to make them deterministic: ORDER BY id in a SELECT ... FOR UPDATE first, then the UPDATE by primary key.

Q37 · Scenario. "Two services deadlock inserting into the same table — yet they never touch the same row. How is that possible?"

Reveal answer

Strong answer That is the gap-lock deadlock, an InnoDB specialty. Recall a gap lock covers the empty space between index entries.

The trap is that gap locks are compatible with each other — two transactions can hold a lock on the same gap simultaneously, because gap locks exist only to block inserts, not each other.

The classic sequence: both transactions run a locking read or DELETE on a key that does not exist — say DELETE FROM t WHERE k = 10 with no row 10 — and each acquires a gap lock over the same empty range.

Then each tries to INSERT into that gap. An insert needs an insert-intention lock, which must wait for the other transaction's gap lock — and now each waits on the other: deadlock, with no shared row anywhere.

Fixes: replace check-then-insert with an UPSERT or a plain insert catching the duplicate-key error; or run READ COMMITTED, where InnoDB drops most gap locking.

Postgres cannot produce this shape — it has no gap locks — the same logic there surfaces as a unique-constraint violation instead, which is easier to reason about.

Land it When a deadlock report shows locks on a gap rather than a record, stop looking for the shared row — the transactions collided over empty space, and the fix is changing the insert pattern.

Likely follow-ups
"What does the deadlock report show that tells you it is a gap lock?"

The lock description lines. In the LATEST DETECTED DEADLOCK section, a next-key lock reads lock_mode X, a pure gap lock reads lock_mode X locks gap before rec, and a waiting insert reads lock_mode X locks gap before rec insert intention waiting.

When the record shown is supremum, the gap is the space after the last key in the index.

If I see one transaction holding a gap lock and the other waiting for an insert intention lock on the same index with the same neighbouring record, and vice versa, it is the gap deadlock.

The key values in the report are the neighbouring index entries, which tells me which range the two inserts were aiming at, and the index name tells me whether it is the primary key or a secondary unique index.

"Does READ COMMITTED remove all gap locks, and what is the remaining risk?"

Not all. At READ COMMITTED InnoDB drops gap locks for ordinary searches and index scans, which removes this deadlock shape for a delete-then-insert. Gap locks remain for two cases: foreign-key constraint checks and duplicate-key checks on unique indexes.

So two transactions inserting the same not-yet-existing unique key can still interact: the first insert holds a record lock for the pending row, the second waits on it with a shared lock request, and if the first then rolls back and both insert, or if both insert different keys after a failed duplicate check, a deadlock is still possible.

The cure for those is the same: insert without a preceding check, and retry on 1213. READ COMMITTED reduces the rate; it does not eliminate the need for the retry.

"How does the same code fail on Postgres, and which is easier to handle?"

On Postgres the delete-then-insert pattern for a missing key takes no gap lock — the DELETE simply affects zero rows — so both transactions proceed to INSERT. If there is a unique index, the second inserter blocks until the first commits and then fails with SQLSTATE 23505, a unique violation.

If there is no unique index, both rows are inserted and there is a silent duplicate. So Postgres gives either a clear constraint error or a data problem, and InnoDB gives a deadlock.

The constraint error is easier: it is deterministic, needs no retry, and points straight at the row.

But it also shows the pattern was relying on the engine to prevent duplicates in the first place, and the correct portable fix is an UPSERT with the unique index named explicitly.

Q38 · Scenario. "Inserts into order_items started blocking on locks held by a completely different part of the app that only updates the orders table. Why do foreign keys take locks?"

Reveal answer

Strong answer Because referential integrity must hold at commit, not just at check time. When I insert a child row, the engine verifies the parent exists — and must then keep it existing until my transaction ends, or a concurrent delete would orphan my child.

So the foreign-key check takes a shared-type lock on the parent row, and that lock can collide with whoever is updating the parent. The engines differ in how painful this is.

InnoDB takes a plain shared record lock on the parent's index entry, which conflicts with any exclusive lock — so a hot parent row that is both frequently updated and frequently referenced becomes a contention point.

Postgres is more surgical: the FK check takes FOR KEY SHARE, and an ordinary UPDATE that does not touch key columns takes FOR NO KEY UPDATE — and those two modes are compatible, so child inserts and non-key parent updates do not block each other; only deleting the parent or updating its key conflicts.

The classic aggravator is a counter or status column on the parent row updated on every child insert — that design serializes the children by itself. Fixes: keep parent-updating transactions short, never update parent primary keys, and move hot counters off the parent row.

Land it A foreign key is a silent locking agreement between two tables — when a lock pileup makes no sense, draw the FK arrows before doubting the lock report.

Likely follow-ups
"The parent row has a counter column, items_count, updated on every child insert. Redesign it."

Move the counter off the parent row or off the hot path. Option one: drop the counter and compute it with COUNT(*) on an index over order_items(order_id) at read time, which is cheap for typical order sizes.

Option two: keep a separate order_stats(order_id, items_count) row, so the update touches a row nothing else references and takes no lock that conflicts with the FK share lock on orders.

Option three: update the counter once at the end of the transaction from the count, in a single statement, rather than incrementing per item.

In Postgres a plain UPDATE of a non-key column takes FOR NO KEY UPDATE and coexists with FK checks, so the counter is less painful there, but it still serializes all children of the same order.

"What exactly does Postgres lock on the parent, and what does the child insert wait for?"

The FK check runs SELECT 1 FROM orders WHERE id = ? FOR KEY SHARE as an internal trigger.

FOR KEY SHARE is the weakest row lock: it blocks only FOR UPDATE, meaning deletes and updates of key columns, and is compatible with FOR NO KEY UPDATE, which a normal UPDATE takes when it does not change any column used in a unique index.

So the child insert waits only if someone is deleting the order or changing its primary key, or if someone explicitly ran SELECT ... FOR UPDATE on it — which is what a lot of application code does out of habit when it means "lock this order while I process it".

Switching that code to FOR NO KEY UPDATE unblocks the child inserts while still preventing concurrent processors.

"How would you find that a foreign key is the source of a lock wait in each engine?"

In MySQL, performance_schema.data_locks shows the waiting transaction holding an S record lock on the parent table's primary key, in a transaction whose current statement is an INSERT into the child table; a shared lock on a table the statement does not name is the FK signature.

In Postgres, pg_stat_activity shows the inserting session with wait_event_type = 'Lock' and wait_event = 'transactionid', and pg_locks shows it waiting on a tuple in the parent table while its query is an INSERT into the child.

pg_blocking_pids() points at the session holding FOR UPDATE on the parent. Once I see a cross-table wait, I draw the FK arrows and the picture is usually complete.

"Would dropping the foreign key and enforcing it in code be a reasonable fix?"

Only as a last resort, and I would argue against it. Enforcing referential integrity in application code cannot be race-free: a check that the parent exists, followed by the child insert, has exactly the check-then-act window, and a concurrent parent delete slips through.

The FK lock exists to close that window. Some very high-throughput shops do drop FKs for write performance, accepting occasional orphans that a cleanup job handles, and on sharded systems it is often unavoidable.

But in a normal service the right fix is shorter parent transactions, not updating parent keys, keeping hot counters off the parent, and on Postgres using FOR NO KEY UPDATE. I would present dropping the constraint with its cost stated: a class of data corruption becomes possible.

Q39. "What should worry you about SELECT ... FOR UPDATE on a query with a JOIN?"

Reveal answer

Strong answer Three things. First, scope: by default FOR UPDATE locks the matched rows of every table in the join — including the reference table you only joined for a label — so you serialize unrelated traffic on lookup rows.

Both Postgres and MySQL 8.0 support FOR UPDATE OF alias to restrict locking to the table you actually intend to modify; use it.

Second, the plan decides the footprint: in InnoDB, locks land on the index records the executor scans, so a plan that examines extra rows locks extra rows, and a plan change after an ANALYZE can change what gets locked.

Third, ordering: lock acquisition follows plan order, so two queries joining the same tables with different plans can take the same locks in opposite order — a deadlock born from the optimizer, not the code.

Safer shape when it matters: first select the target primary keys with FOR UPDATE on the one table, ordered consistently, then join separately for the display data.

Land it Say what you want locked out loud — FOR UPDATE OF — because the default answer, "everything the join touched", is almost never what you meant.

Likely follow-ups
"Show me the two-step shape you prefer and explain why it is deadlock-resistant."

Step one: SELECT id FROM orders WHERE customer_id = ? AND status = 'PENDING' ORDER BY id FOR UPDATE. It touches one table, locks only the rows I will change, and the ORDER BY makes lock acquisition order the same for every transaction.

Step two: SELECT o.*, c.name FROM orders o JOIN customers c ON ... WHERE o.id IN (?) with no lock, for display data. Step three: UPDATE orders ... WHERE id IN (?) by primary key.

Deadlock resistance comes from two properties: all writers lock the same table in the same key order, and no reference rows are ever locked, so lookups elsewhere do not join the cycle.

Postgres adds a caveat that ORDER BY with FOR UPDATE can still lock in plan order before sorting in rare plans; the primary-key IN list on the update is the safe part.

"Does FOR UPDATE OF exist in both engines, and are the semantics identical?"

Both support it as of Aug 2026: Postgres has had FOR UPDATE OF table_alias for a long time, and MySQL added FOR UPDATE OF tbl in 8.0. Both restrict locking to rows from the named tables. The differences are in the edges.

Postgres allows combining lock strengths, such as FOR UPDATE OF o FOR SHARE OF c, and refuses FOR UPDATE on the nullable side of an outer join with an error, which is good.

MySQL's OF works with NOWAIT and SKIP LOCKED similarly, but the InnoDB rule that locks land on scanned index records still applies inside the named table, so a bad plan on that table still over-locks. In both, I read the plan after adding it.

"Can a plan change after ANALYZE really create a deadlock that was not there before?"

Yes, and it is a nasty class of incident because nothing in the code changed. Suppose two statements both lock rows in orders and customers. Yesterday both planners drove from orders and probed customers, so both locked orders rows first.

Overnight statistics changed and one query's plan now drives from customers, locking customers rows first. The two statements now acquire the same locks in opposite orders under load, and deadlocks appear on Monday morning.

The evidence is a deadlock report where the two transactions hold locks on different tables first, and a plan diff against the previous day. The remedy is the two-step shape, which fixes the lock order in the SQL rather than leaving it to the optimizer.

Q40. "Which database errors is it correct to retry automatically, and how should the retry be built?"

Reveal answer

Strong answer Retryable: deadlock victim — MySQL 1213, Postgres 40P01 — and serialization failure — Postgres 40001. Both mean "your transaction was chosen to die so others could proceed; rerun it and it will likely succeed.

" Lock wait timeout — MySQL 1205 — is retryable with more caution, because it can mean a stuck holder that a retry will just wait behind again.

Connection failures are retryable only when the operation is idempotent, since you may not know whether the commit landed. Never auto-retry constraint violations, syntax errors, or data errors — those are deterministic and will fail identically forever.

The construction rules: retry the whole transaction from the top, because every read from the aborted attempt is invalid; bound it at three to five attempts with jittered backoff; only wrap transactions with no external side effects — no email sent mid-transaction, or the retry sends it twice; and in Spring, the retry boundary must sit outside @Transactional, since catching the exception inside the still-open transaction retries nothing.

Land it The error codes are the contract: 1213, 40P01, and 40001 are the database saying "try again" — and a service running at snapshot isolation without that loop has a latent bug, not a policy.

Likely follow-ups
"Show me what the retry looks like in Spring without retrying inside the transaction by accident."

Two beans. The inner one is OrderService with the @Transactional method.

The outer one is OrderFacade whose method loops: for attempt one to five, call orderService.place(cmd); catch PessimisticLockingFailureException and, for Postgres serialization failures, CannotAcquireLockException; sleep a jittered backoff of roughly fifty milliseconds times two to the attempt; continue; rethrow on the last attempt.

Because the facade is a different bean, each call goes through Spring's proxy and gets a fresh transaction and connection.

Spring Retry's @Retryable(retryFor = {...}, maxAttempts = 5, backoff = @Backoff(delay = 50, multiplier = 2, random = true)) on the facade method expresses the same thing declaratively. Self-invocation inside one class skips the proxy, which is the classic mistake.

"What about a connection failure during commit — did the commit happen or not?"

Unknown, and that is the honest state. The commit record may have hit the log before the socket died, or not. Retrying blindly can double-apply.

The safe patterns are idempotent transactions, where re-running the same transaction has the same effect, typically by an idempotency key with a unique constraint so a replay collides and is recognised; or a post-check, where the retry first queries whether the outcome exists before re-executing.

Postgres has no built-in "did transaction X commit" lookup by client, though txid_status(bigint) can answer it if the application recorded txid_current() beforehand; MySQL has nothing equivalent short of GTID inspection.

Frameworks with connection pools mask the disconnect as a generic exception, so the retry filter must treat it as "unknown outcome", not as "safe to repeat".

"Why must side effects not happen inside a retried transaction, and what if they are unavoidable?"

Because a retry reruns the whole body, so anything that already happened — an email sent, a payment captured, a message published — happens again, and the rolled-back database state gives no record that it did.

If the side effect cannot be moved after commit, make it idempotent with a key the retry reuses, so the second execution is recognised as a duplicate by the receiving system.

Better still is the outbox pattern: write the intended side effect as a row inside the transaction, and let a relay perform it after commit; a retry then just rewrites the same outbox row in the new transaction and the side effect happens exactly once per committed transaction.

Anything less than that is a race between the retry loop and the external world.

"How do you keep retries from turning a small contention spike into a storm?"

Bound and randomise. Cap attempts at three to five so a request fails fast instead of piling up. Use exponential backoff with full jitter so retries from a hundred colliding requests spread out rather than stampede the same row together.

Add a circuit breaker per operation: if the retry rate for placing orders exceeds a threshold over ten seconds, shed load at the edge rather than adding retries to a database already saturated by them.

And keep transactions short, because retry cost is proportional to the work redone.

I would monitor retries as a fraction of attempts; a healthy system sits under one percent, and the alert threshold is where I think about redesigning the contended path rather than tuning the loop.

Q41 · Scenario. "Two instances of your scheduler both fired the same nightly job. Prevent that using only the database — no new infrastructure."

Reveal answer

Strong answer This is what advisory locks are for — locks the database manages but that are attached to an application-chosen name or number rather than to any row.

  1. Postgres: at job start, SELECT pg_try_advisory_lock(42) where 42 is my agreed key for "nightly-billing". Exactly one caller gets true and runs; the other gets false immediately and skips this cycle. The lock is session-scoped: released by pg_advisory_unlock or automatically when the connection dies. MySQL: SELECT GET_LOCK('nightly-billing', 0) — the 0 means do not wait — released with RELEASE_LOCK or on connection death.
  2. The crash story is the selling point: if the winning scheduler dies mid-job, its connection drops and the lock releases itself. A hand-rolled locks table needs expiry timestamps and a janitor to handle exactly that case, and gets it wrong under clock skew.
  3. The costs to name: the holder must keep that specific connection open for the whole job — the connection is the lease — which fights connection pools; either hold a dedicated connection outside the pool or be certain the pool cannot recycle it mid-job. And advisory locks are invisible to ordinary row-lock monitoring, so document the key numbers.
  4. For lock-per-transaction semantics, Postgres also offers pg_try_advisory_xact_lock, which releases at commit automatically.

Land it Connection-death-equals-release is the feature you are buying — it turns the database you already run into a crash-safe distributed lock without deploying ZooKeeper for one cron job.

Likely follow-ups
"The scheduler holds the advisory lock, but Hikari's pool recycled the connection mid-job and a second instance started the same job. Fix it."

The lock is tied to the session, so the job must own its connection for its whole life.

I would take a dedicated connection outside the pool for the scheduler — a second small DataSource with maximumPoolSize = 1 and a maxLifetime longer than any job — or open a raw JDBC connection for the job and close it at the end.

The alternative is a transaction-scoped lock: pg_try_advisory_xact_lock(42) inside a transaction that spans the job, so the pool cannot hand the connection out because it is busy; Spring's @Transactional around the job does that naturally, though then the job's locks and snapshot are held for its duration.

A third option is a lease row with an expiry that the job refreshes every thirty seconds, which tolerates pooling but needs a clock and a janitor.

"Can two different jobs accidentally share the same advisory lock key?"

Yes, and it is the classic silent failure. Advisory locks are just integers or strings with no namespace; if the billing job uses 42 and somebody's new cleanup job also picks 42, they exclude each other and one silently skips every night.

Postgres offers the two-argument form pg_try_advisory_lock(classid int, objid int) which gives a natural namespace, and a common pattern is hashtext('nightly-billing') to derive the key from a name. In MySQL, GET_LOCK takes a string, so names are self-documenting.

Either way I keep a single registry of lock names in code, an enum, so keys are reviewed like schema. And I log the acquisition result so a job that always gets false is visible.

"What if the winning instance is alive but hung? The lock is never released."

That is the scenario the advisory lock does not solve on its own, since the connection is healthy and the lock stays held. The mitigations are outside the lock.

Give the job a statement-level or overall timeout so a hung query is cancelled and the job fails and releases. Monitor job duration and alert when it exceeds the expected window by a margin.

Have an operator runbook: find the holder in pg_locks WHERE locktype = 'advisory' joined to pg_stat_activity, or in MySQL performance_schema.metadata_locks with OBJECT_TYPE = 'USER LEVEL LOCK', and terminate the session.

For jobs where liveness matters more than at-most-once, a lease with a heartbeat is the better primitive, because a hung holder stops heartbeating and loses the lease.

"How does this compare to a database-backed lease table, honestly?"

The advisory lock wins on crash safety and simplicity: nothing to clean up, no clock, automatic release on connection death, and no writes to the database.

The lease table wins on visibility and pool-friendliness: a row with owner, acquired_at, and expires_at can be read by dashboards, works across a proxy or pooler, survives connection recycling, and supports a heartbeat that detects a hung owner.

Its weaknesses are the ones the answer named: clock skew between instances, a janitor to expire dead leases, and a check-then-update race that must be closed with a conditional UPDATE, UPDATE lease SET owner = ?, expires_at = ? WHERE name = ? AND (owner IS NULL OR expires_at < now()), checking one row affected.

For a cron job I use the advisory lock; for a long-running leader election I use the lease.

Q42 · Scenario. "Right now, live, queries are piling up behind a lock in production. Show me how you find the blocker and what you do about it."

Reveal answer

Strong answer Minutes matter, so straight to the lock views:

  1. MySQL: SELECT * FROM sys.innodb_lock_waits; — it names the waiting query, the blocking query, both transaction ids, how long the wait has run, and even a ready-made KILL statement. Cross-check information_schema.innodb_trx for the blocker's age and state.
  2. Postgres: SELECT pid, pg_blocking_pids(pid), state, xact_start, query FROM pg_stat_activity WHERE wait_event_type = 'Lock'; — pg_blocking_pids hands you the blocker chain directly; look up the root blocker's row to see what it is running and since when.
  3. Judge the root blocker. If it is idle in transaction — holding locks while doing nothing — kill it without guilt: pg_terminate_backend(pid) or KILL with the id, remembering that InnoDB must roll back its work first. If it is a legitimate long operation — a migration, a huge batch — the call is business, not technical: wait or kill, decided with its owner, knowing the rollback cost.
  4. Stop the secondary damage: the real outage mechanism is usually the connection pool — every blocked query occupies a pooled connection, the pool empties, and the whole app 503s, not just the locked table. That is why prevention is lock_timeout (Postgres) or a lowered innodb_lock_wait_timeout plus statement timeouts, so requests fail fast and release connections instead of queueing forever.
  5. Afterwards: alert on lock-wait counts and on oldest-transaction age so the next one pages you before users notice.

Land it Lock pileups take systems down via pool exhaustion before the lock itself matters — failing fast is not defeatism, it is the containment strategy.

Likely follow-ups
"You killed the root blocker and a different session immediately became the new blocker. What is happening?"

Either the blocker was not the root, or the pattern is systemic.

In a chain A waits on B waits on C, killing B just makes A wait on C, so I should have followed the chain to its end; pg_blocking_pids returns the direct blockers, and I recurse until a session with an empty blocker list — or sys.innodb_lock_waits ordered by wait age shows the oldest holder.

If the root really was killed and a new root appeared with the same query, the cause is workload, not one session: a statement that locks far too much, a lock-ordering deadlock cycle resolving slowly, or a hot row every request updates.

Then I stop killing and look at the statement itself, its plan, and its lock footprint, and I apply a temporary lock_timeout so the queue drains.

"What is the difference between pg_cancel_backend and pg_terminate_backend, and which do you use first?"

pg_cancel_backend(pid) sends a cancel signal that interrupts the currently running statement, leaving the session connected; if the session is idle in transaction there is no statement to cancel, so it does nothing.

pg_terminate_backend(pid) closes the connection, which rolls back the open transaction and releases all its locks. For a session running a long statement I try cancel first, because the client gets an error it can handle and stays connected.

For idle in transaction, terminate is the only option. In MySQL the equivalents are KILL QUERY id and KILL id.

Both need the right privilege — pg_signal_backend role in Postgres, CONNECTION_ADMIN or SUPER in MySQL — which I make sure the on-call role has before the incident.

"Show me the Postgres query that gives the whole picture in one result."

I keep this one in the runbook:

SELECT a.pid, a.state, now() - a.xact_start AS xact_age,
       pg_blocking_pids(a.pid) AS blocked_by,
       a.wait_event_type, a.wait_event,
       left(a.query, 80) AS query
FROM pg_stat_activity a
WHERE cardinality(pg_blocking_pids(a.pid)) > 0
   OR a.pid IN (SELECT unnest(pg_blocking_pids(pid)) FROM pg_stat_activity)
ORDER BY a.xact_start;

It lists every waiter with who blocks it and every blocker with its age and query, oldest first. The row with an empty blocked_by and the oldest transaction is the root. If its state is idle in transaction, I terminate it. If it is active, I read the query and decide with its owner. Then I re-run the query to watch the waiters drain.

"What would you set up so this pages you before users notice?"

Three alerts. One on lock waits: count of sessions with wait_event_type = 'Lock' in Postgres, or rows in sys.innodb_lock_waits in MySQL, above a small number for more than thirty seconds.

One on oldest transaction age, from max(now() - xact_start) or innodb_trx.trx_started, above a minute for the application role. One on connection pool saturation from Hikari's hikaricp.connections.pending metric, since that is the symptom users feel.

Plus the preventive settings: lock_timeout and idle_in_transaction_session_timeout on the application role, and log_lock_waits = on so every wait longer than deadlock_timeout is logged with both queries for later analysis.

Q43. "What belongs inside a @Transactional method — and why is a remote call inside a transaction a double bug?"

Reveal answer

Strong answer Spring's @Transactional opens a transaction on method entry, commits or rolls back at exit, and pins one pooled database connection to the thread for the whole method. So the method body should contain database work and cheap computation — nothing else.

A remote call inside it is a double bug. First, duration: every row lock and the MVCC snapshot are now held for the remote call's latency, timeouts, and retries — seconds of locking dictated by someone else's service.

Second, resources: the pinned connection sits idle-in-transaction during the call; with a pool of 20 and a slow downstream, 20 threads hold 20 connections while waiting on HTTP, and every other database operation in the process starves — an app-wide outage from one dependency.

There is a third, subtler wound: the remote call does not roll back with the transaction, so a later rollback un-writes your rows while the email or payment already left — fake atomicity.

The shape that works: call out first, then open the short transaction; or write an outbox row inside the transaction and let a relay make the call after commit.

Land it My rule in reviews: a transaction should contain milliseconds of database work and zero network calls — anything else is borrowing locks and connections against another system's latency.

Likely follow-ups
"The remote call must succeed before we commit — it is a payment authorisation. How do you structure that?"

As three steps with the transaction last and short. Step one, in its own quick transaction, insert the order in state AUTHORISING with an idempotency key, so a crash leaves a record to reconcile.

Step two, outside any transaction, call the payment provider with that key, with a timeout. Step three, in a second short transaction, update the order to AUTHORISED or FAILED based on the result.

If the process dies between steps two and three, a recovery job finds orders stuck in AUTHORISING older than a minute and queries the provider by idempotency key to learn the truth.

That gives the same guarantee as "call inside the transaction" without holding locks and a connection for the provider's latency, and it survives crashes, which the single-transaction version does not.

"How would you detect transactions that contain remote calls in an existing codebase?"

Statically and dynamically.

Statically, I look for @Transactional methods that reach an HTTP client, a Kafka producer, a message queue, or a Feign interface, including transitively through injected services; an ArchUnit rule that forbids classes in the transactional layer from depending on the client packages makes it a build failure.

Dynamically, I set idle_in_transaction_session_timeout low in staging — a few hundred milliseconds — so any transaction that waits on a network call is killed and the test fails, and I watch Hikari's connections.active against request latency in production: active connections that track downstream latency rather than database latency mean connections are held across calls.

pg_stat_activity sampled every second showing many sessions idle in transaction during peak is the same evidence.

"What does Spring actually do at method entry and exit, and where does the connection pin happen?"

The proxy around the bean intercepts the call and asks the PlatformTransactionManager to begin.

For JDBC or JPA that means obtaining a connection from the DataSource, setting autoCommit = false, and binding the connection to the current thread in TransactionSynchronizationManager, so every repository call in that thread reuses it.

That binding is the pin: the connection cannot return to the pool until the method exits. On normal return the manager commits, on a RuntimeException it rolls back, on a checked exception it commits unless rollbackFor says otherwise, and then the connection is unbound and returned.

With spring.jpa.open-in-view = true, the default in Spring Boot web apps, the EntityManager stays open for the whole request, which can extend connection use even further; I turn it off.

"Is there any remote call that is acceptable inside a transaction?"

Only one I would accept: a call to another resource enlisted in the same transaction, which in practice means a second database under an XA transaction manager, and even then I would rather avoid it.

Everything else — HTTP, gRPC, message brokers, caches, email — has no rollback, so it breaks atomicity, and has latency the database has no control over, so it breaks the lock and connection budget.

A cache read is the borderline case: it is fast and has no side effect, so a Redis GET inside a transaction is tolerable, but a Redis timeout still holds the transaction, so I put a tight timeout on it.

The rule I enforce in reviews is that the transaction boundary contains only calls to the database it was opened on.

Q44 · Scenario. "A 50,000-row import takes 25 minutes in production but seconds on a laptop. The code inserts one row at a time. Diagnose."

Reveal answer

Strong answer The signature — per-row inserts, catastrophically slower on real hardware — is autocommit: the JDBC default where every single statement is its own transaction, committed immediately.

  1. Confirm it: JDBC connections default to autocommit on; check the code never calls setAutoCommit(false), or ask the server — SELECT @@autocommit in MySQL.
  2. Explain the arithmetic: every commit must fsync the write-ahead log — physically wait for the disk to confirm. Call it 2–5 milliseconds on a production disk with strict durability: 50,000 commits × 3 ms is around 20 minutes of pure fsync waiting. The laptop is "fast" because consumer disks lie about flushes or the test database runs relaxed durability — the laptop is not faster, it is less honest.
  3. Fix: wrap the import in one transaction — one fsync at the end instead of 50,000 — typically a 10–40× speedup on its own. Batch the statements too: addBatch/executeBatch with rewriteBatchedStatements=true on MySQL or reWriteBatchedInserts=true on Postgres collapses network round trips, which is a separate, additive win.
  4. But do not swing to one giant transaction for millions of rows: commit in chunks of 1,000–10,000 so undo growth, lock lifetime, and replication lag stay bounded, and a failure loses one chunk, not the world.
  5. If this import is a regular event, use the bulk paths — LOAD DATA in MySQL, COPY in Postgres — built exactly for this.

Land it Commit is the expensive word in SQL — say it 50,000 fewer times and the problem disappears; say it once and you have created a different problem.

Likely follow-ups
"You wrapped the import in one transaction and it is still slow. What else is on the list?"

Round trips next: 50,000 statements are 50,000 network round trips even in one transaction, and at one millisecond each that is nearly a minute.

JDBC batching with addBatch and executeBatch every thousand rows, plus rewriteBatchedStatements=true on MySQL or reWriteBatchedInserts=true on Postgres, turns those into a few dozen multi-row INSERTs.

Then indexes: every secondary index is updated per row, so on a table with eight indexes each insert is nine B-tree inserts, and for a truly large load it is faster to drop non-unique indexes and rebuild after.

Then triggers and foreign-key checks, which run per row. Then the ORM: Hibernate's default flush and identity generation force a round trip per insert; use hibernate.jdbc.batch_size and a sequence-based id. Finally, COPY or LOAD DATA bypass all of it.

"Why is the laptop faster? Be precise."

Because the laptop is not paying for durability. Consumer SSDs typically have volatile write caches that acknowledge fsync before data reaches persistent media, so an fsync costs microseconds instead of milliseconds.

Docker on macOS adds another layer where fsync may be a no-op against the virtual disk. And developer databases are often configured with innodb_flush_log_at_trx_commit=2 or fsync=off in Postgres for speed. Each of those makes the 50,000 commits nearly free.

Production uses storage that honestly flushes, at two to five milliseconds each, and multiplies that by 50,000. So the laptop measurement is not a performance number, it is the absence of a cost.

I would benchmark imports against a database with production durability settings on production-like disks before believing any number.

"What chunk size do you commit at, and what are you balancing?"

Typically one thousand to ten thousand rows per commit, tuned by measurement.

Larger chunks mean fewer fsyncs and fewer round trips, so throughput rises, but they hold row locks longer, generate bigger undo or WAL bursts, create bigger replication transactions that replicas apply as a unit, and lose more work on failure.

Smaller chunks bound all of those but pay more commits. The throughput curve flattens quickly: one thousand rows per commit is already 99.9 percent of the fsync savings of a single transaction, so I start there and only go bigger if measured.

The other constraint is restartability: each chunk should be identifiable so a failed import resumes from the last committed chunk rather than restarting, which means the source has an ordering key I record.

"How would you make the import restartable and safe to rerun?"

Give every source row a stable key and make the insert idempotent against it. With a unique constraint on that key, rerunning uses INSERT ... ON CONFLICT DO NOTHING in Postgres or INSERT IGNORE in MySQL so already-loaded rows are skipped, and the import cannot double-load.

For resume, record progress: after each chunk commits, write the last key processed to a small import_progress table in the same transaction as the chunk, so progress and data are atomic. On restart, read the progress row and continue from there.

For files without a key, derive one from the file name plus line number. Finally, run the import under a job lock — an advisory lock — so two instances cannot both process the same file.

Q45. "A transaction ran for two hours. Name the four separate kinds of damage it does."

Reveal answer

Strong answer Four independent wounds, and naming them separately is the point:

  • Locks held. Every row it has written stays exclusively locked for the full two hours. Blocking chains build behind each one, and other transactions time out or pile up.
  • History pinned. Its snapshot holds the MVCC cleanup horizon: InnoDB's undo log and history list grow the whole time, and Postgres's vacuum cannot reclaim any dead tuple the transaction might still see — bloat and disk growth that outlive the transaction itself.
  • Replication lag. In MySQL the transaction reaches the binary log only at commit, as one unit — so at hour two, replicas receive a giant lump they must apply while fresh commits queue behind it, and lag spikes exactly when the transaction finally ends. In Postgres, a large transaction floods the WAL stream at commit-heavy moments, and long transactions on replicas with hot_standby_feedback reflect bloat back to the primary.
  • Pool starvation. It occupies one pooled connection for two hours; a handful of these and the pool is visibly smaller than configured, and under load the application starves for connections that are technically "in use" doing nothing.

Land it These are four different pagers going off — lock alerts, disk alerts, lag alerts, pool alerts — and the senior insight is recognizing them as one root cause: transaction age.

Likely follow-ups
"Which of the four is worst, and which is the one most people forget?"

Worst in immediate impact is lock holding, because it blocks other transactions right now and cascades into pool exhaustion within minutes.

Worst in lingering damage is the pinned history, because the bloat or undo growth it causes outlives the transaction and degrades performance for hours or days until vacuum or purge catch up, and on Postgres the space is not returned without a rebuild.

The one most people forget is replication lag, especially on MySQL, where the transaction is invisible to replicas until commit and then arrives as one lump; a team that carefully monitors locks and disk will still be surprised when replicas fall ten minutes behind at the moment the batch finally commits.

Pool starvation is the most commonly noticed because it is what the application sees.

"The two-hour transaction is a legitimate report. How do you run it without the damage?"

Move it and split it. Run it on a read replica, so its snapshot pins cleanup only there and its locks and connection do not touch the primary; on Postgres set max_standby_streaming_delay on that replica rather than hot_standby_feedback so the primary is not affected.

If it must run on the primary, run it as a series of shorter transactions, each reading a bounded range and writing its result to a staging table, so no single snapshot lasts more than a few minutes; accept that the report is then not one consistent instant, or make it consistent by keying every chunk on a fixed "as of" timestamp column. Mark it read-only, give it a statement_timeout, and schedule it off-peak.

"Does Postgres really send a big transaction to replicas only at commit?"

No, and that is the difference from MySQL. Postgres streams WAL continuously, so the replica receives and applies each row change as it is written, even for an uncommitted transaction; at commit only the small commit record arrives.

So a two-hour Postgres transaction does not cause a lag spike at commit on physical replicas.

Where it hurts is logical replication and CDC: a logical decoding consumer such as Debezium only emits a transaction at commit, and before Postgres 14's streaming of in-progress transactions it had to buffer or spill the whole thing to disk, so the lag spike moves to the logical consumer.

MySQL's binlog is written at commit, which is why its replicas see the lump.

"What single metric would you alert on to catch all four?"

The age of the oldest open transaction, per role. In Postgres: SELECT max(now() - xact_start) FROM pg_stat_activity WHERE state <> 'idle'; in MySQL: SELECT max(timestampdiff(SECOND, trx_started, now())) FROM information_schema.innodb_trx.

Every one of the four damages grows with that number, so alerting at, say, sixty seconds for the application role and thirty minutes for a batch role catches lock holding, history pinning, the coming lag spike, and pool occupancy before any of the individual symptoms trips its own alert.

It is also cheap to collect and easy to attribute, since the same row gives the query and the user. I would put that on the primary dashboard above lock waits and disk.

Q46. "What does marking a transaction read-only actually buy you?"

Reveal answer

Strong answer Four concrete things, ranked by real-world impact.

In a Spring service the biggest win is usually in the ORM: @Transactional(readOnly = true) tells Hibernate to skip dirty checking — the bookkeeping of snapshotting every loaded entity to detect changes at flush — which saves real CPU and memory on large result sets.

Second, engine optimizations: InnoDB skips assigning a transaction id and setting up undo for read-only transactions, keeping them off structures that writers contend on; Postgres pure reads avoid consuming a transaction id anyway, so the flag there is mostly enforcement.

Third, safety: writes fail loudly, turning "this method should never write" from a comment into a contract. Fourth, routing: pools and proxies can send read-only transactions to replicas.

What it does not buy: it changes nothing about isolation, and a long read-only transaction still holds a snapshot — it pins undo and blocks vacuum exactly like a writer.

Land it Read-only is a real optimization and a real contract, but not an exemption — the two-hour read-only report job bloats the database just as effectively as a writer.

Likely follow-ups
"How does readOnly = true actually reach the database, and does it always?"

It depends on the driver and the transaction manager. Spring calls Connection.setReadOnly(true). The Postgres JDBC driver translates that into SET SESSION CHARACTERISTICS AS TRANSACTION READ ONLY or per-transaction BEGIN READ ONLY depending on readOnlyMode, and the server then rejects writes.

The MySQL Connector/J driver sends SET SESSION TRANSACTION READ ONLY when readOnlyPropagatesToServer is true, which is the default, and InnoDB then uses its read-only transaction path. With JPA, Spring additionally sets Hibernate's session to FlushMode.MANUAL, which is where the dirty-checking saving comes from.

If the flag does not reach the server — some pools or proxies strip it — the ORM benefits remain but the engine ones and the write protection do not, so I verify with a deliberate write in a test.

"You said pools can route read-only transactions to replicas. What goes wrong when they do?"

Stale reads. A user writes on the primary and the next request, marked read-only, is routed to a replica that has not yet applied the write, so the user does not see their own change.

This is replication lag surfacing as a bug report, and it is worse under load when lag grows.

The fixes: route reads to the primary for a few seconds after a write for that user, using a cookie or a session timestamp; or wait for the replica to reach the primary's write position, in Postgres by comparing pg_last_wal_replay_lsn() to the LSN recorded at commit, in MySQL with WAIT_FOR_EXECUTED_GTID_SET; or only route reads that tolerate staleness, by annotating those methods explicitly rather than all read-only ones.

Routing must be a decision per use case, not a blanket rule on the flag.

"Is a read-only transaction ever better than just autocommit reads?"

Yes, when several reads must agree. Under autocommit each SELECT is its own snapshot, so a two-query report can see a commit between them.

A read-only transaction at REPEATABLE READ gives one snapshot for all the reads, which is exactly what a consistent export or a multi-query page render needs. It also lets the ORM reuse the first-level cache across queries and avoid re-fetching entities.

And in Postgres a read-only REPEATABLE READ transaction can never receive a serialization error, since it never writes, so it is the safe way to get snapshot consistency without retries.

The cost is the same as any transaction: the snapshot pins cleanup for its duration, so it should still be short.

Q47. "What are savepoints, and where do they actually earn their keep?"

Reveal answer

Strong answer A savepoint is a named marker inside a transaction that you can roll back to without abandoning the transaction: SAVEPOINT sp1; ... ROLLBACK TO sp1; undoes only the work after the marker, and the transaction continues. They earn their keep in three places.

In Postgres they are near-mandatory for optional sub-steps, because of a Postgres-specific rule: any error aborts the whole transaction — you get "current transaction is aborted, commands ignored until end of transaction block" on every subsequent statement — so a try-insert-catch-duplicate pattern only works if the insert was wrapped in a savepoint to roll back to.

Second, batch processing where one bad row should be skipped, not kill ten thousand committed-so-far siblings. Third, Spring's PROPAGATION_NESTED is implemented with savepoints — a nested unit that can fail and be rolled back while the outer transaction survives.

The honest cost: in Postgres every savepoint creates a subtransaction, and heavy use — per-row savepoints in a loop — hits real performance cliffs when more than 64 are live in a session; use them per meaningful step, never per row.

Land it Savepoints are partial rollback for planned failure paths — priceless in Postgres's all-or-nothing error model, and poison when sprinkled per-row.

Likely follow-ups
"Explain the 64-subtransaction cliff in Postgres mechanically."

Each backend caches up to 64 of its own subtransaction ids in shared memory, in the PGPROC array, so other sessions building a snapshot can see them cheaply. When a transaction has more than 64 live subtransactions, that cache overflows and the session is marked "suboverflowed".

From then on, every other session that takes a snapshot cannot trust the cache and must look up subtransaction parents in pg_subtrans, an on-disk structure, for every tuple whose transaction id is not obviously visible.

On a busy system that turns a memory lookup into repeated buffer lookups and lock contention on the subtrans SLRU, and throughput across the whole server can fall sharply while that one transaction runs.

Postgres 17 enlarged the SLRU caches, which softens it, but the per-row savepoint loop is still a pattern to avoid.

"Hibernate throws an exception inside my transaction and then every later statement fails. Where does the savepoint go?"

Around the statement that is allowed to fail, before it runs.

In Spring that is @Transactional(propagation = Propagation.NESTED) on the method that does the risky insert, which makes Spring issue SAVEPOINT before the call and ROLLBACK TO SAVEPOINT if it throws, so the outer transaction stays healthy.

It requires a JDBC transaction manager, or JpaTransactionManager with nested transactions enabled, which support savepoints; plain JpaTransactionManager may reject NESTED. Programmatically, TransactionStatus.createSavepoint() and rollbackToSavepoint() do the same. Without a savepoint, catching the exception is useless because Postgres has already marked the transaction aborted.

On MySQL a failed statement does not abort the transaction, which is why code written on MySQL breaks this way when moved to Postgres.

"How do savepoints interact with locks and with the retry loop?"

Rolling back to a savepoint releases the rows written after it in the sense that they become invisible, but in Postgres the locks acquired after the savepoint are also released, while InnoDB keeps row locks acquired after the savepoint until the transaction ends — a difference worth knowing when the savepoint was meant to reduce contention. With retry loops, a savepoint rollback does not help with serialization failures or deadlocks: SQLSTATE 40001 and 40P01 abort the whole transaction in Postgres, and InnoDB's deadlock victim is rolled back entirely, so the retry must restart from the top regardless of savepoints. Savepoints are for expected, local failures like a unique violation, not for concurrency failures.

Q48 · Scenario. "Order rows commit fine, but the 'order created' Kafka event sometimes never appears — and once, an event existed for an order that had rolled back. Fix the pattern."

Reveal answer

Strong answer Both symptoms are the same disease: dual-write. The database commit and the Kafka publish are two systems with no shared transaction, so there is always an ordering and always a crash window.

  1. Publish after commit: a crash between commit and publish loses the event forever — symptom one. Publish before commit: a rollback leaves a ghost event for an order that never existed — symptom two. Reordering the two writes only chooses which failure you get.
  2. The fix is the transactional outbox: inside the same database transaction that inserts the order, insert an event row into an outbox table. Now "order exists" and "event recorded" are atomic — one commit covers both or neither, which is exactly the guarantee that was missing.
  3. A separate relay moves outbox rows to Kafka: either a poller that reads unpublished rows, publishes, and marks them done, or change data capture (CDC) — a tool like Debezium that reads the database's own binlog or WAL and turns committed changes into events with no polling.
  4. Accept the new contract: delivery is at-least-once — the relay can crash after publishing but before marking — so consumers must be idempotent, deduplicating on the event id carried in the outbox row.

Why not a distributed transaction instead? Kafka does not participate in XA — the standard two-phase-commit protocol for spanning resources — and even where 2PC is possible, the outbox achieves the guarantee with one ordinary local transaction.

Land it The principle generalizes: one atomic write to one system, then asynchronous propagation with idempotent consumers — that is the honest contract for events, and everything else is a race with a crash.

Likely follow-ups
"The outbox is in place. The relay published an event, crashed before marking it, and published it again. The consumer is not idempotent. Now what?"

Then the consumer must become idempotent; there is no other end to this. At-least-once delivery is the contract of the outbox, and the only way to get effectively-once processing is deduplication on the consumer side.

The mechanism is a processed_events(event_id PRIMARY KEY) table in the consumer's own database, written in the same transaction as the consumer's business change; a redelivered event collides on the primary key and is skipped.

If the consumer's action is external — sending an email — it needs the provider's idempotency key instead.

For consumers I do not control, I would reduce the duplicate window by marking the outbox row before publishing and treating publish failure as "unmark and retry", accepting the reverse risk of a lost event, and I would say that trade out loud.

"Poller versus Debezium — how do you choose, and what does each cost?"

The poller is simple: a scheduled query SELECT ... FROM outbox WHERE published_at IS NULL ORDER BY id LIMIT 100 FOR UPDATE SKIP LOCKED, publish, mark. It costs a polling load on the database, latency equal to the poll interval, and needs the outbox table pruned.

It is fine up to a few hundred events per second.

Debezium reads the binlog or the WAL, so latency is milliseconds, no polling load, and ordering per table is preserved, but it is a Kafka Connect deployment to operate, needs a replication slot in Postgres, which pins WAL if the connector stops, and requires the outbox schema to match its event router.

For a team already running Kafka Connect, Debezium; for a single service with modest volume, the poller.

"Ordering: events for the same order must arrive in order. Does the outbox guarantee that?"

Only if the relay preserves it. The outbox rows have a monotonic id and a commit order, but a poller that runs several workers in parallel, or a Kafka producer that sends to multiple partitions, can reorder them.

The standard fix is to partition by aggregate: use the order id as the Kafka message key so all events for one order go to one partition in send order, and have the relay process rows in id order within each key.

Debezium does this naturally when the outbox has an aggregate_id column configured as the key. Cross-order ordering is not guaranteed and should not be promised.

One subtlety on Postgres is that outbox ids from a sequence can commit out of order under concurrency, so a poller keyed on "last id seen" can skip a row; polling on published_at IS NULL avoids that.

"How do you keep the outbox table from growing forever?"

Delete published rows after a retention window, in chunks. A nightly job runs DELETE FROM outbox WHERE published_at < now() - interval '7 days' LIMIT 10000 in a loop on MySQL, or the ctid-subquery form on Postgres, committing each batch.

Keep a partial index WHERE published_at IS NULL in Postgres so the relay's poll never scans published rows, and the table size stops mattering to the poll. If volume is high, partition the outbox by day and drop old partitions, which is a metadata operation.

With Debezium, rows can be deleted immediately after insert in the same transaction, because the connector reads the insert from the log regardless, and the table stays empty.

Q49. "Distributed transactions across services: give me the honest one-paragraph verdict on two-phase commit, and one on sagas."

Reveal answer

Strong answer Two-phase commit (2PC): a coordinator asks every participant to prepare — durably promise it can commit — and once all promise, orders the commit. The honest verdict: it is a blocking protocol.

A participant that has prepared must hold its locks while it waits for the verdict, so a coordinator crash leaves in-doubt transactions holding locks until recovery, which can be minutes of a table being unusable.

Add the latency of extra round trips and extra fsyncs per transaction, and the fact that most things you integrate with — Kafka, HTTP services, most cloud databases — are not XA participants at all, and 2PC's honest niche is narrow: two resources you fully control, both XA-capable, short transactions, low volume.

Sagas: break the business operation into a sequence of ordinary local transactions, each paired with a compensating action that undoes it — refund reverses charge, release reverses reserve.

The honest verdict here: you give up isolation between steps — intermediate states are visible to everyone, and compensation is business logic you must design, test, and sometimes explain to customers.

In exchange you get no global locks, no coordinator to trust, and failure handling that is explicit instead of hidden — which is why sagas, orchestrated or choreographed, are the practical answer in microservice architectures.

Land it The trade in one sentence: 2PC buys atomicity by holding locks across machines, sagas buy availability by admitting the intermediate states exist — and modern systems almost always choose the second.

Likely follow-ups
"Walk me through what happens in 2PC if the coordinator crashes after every participant has prepared."

Each participant has written a prepare record, holds every lock the transaction took, and is waiting for a commit or abort decision. It cannot decide alone: if it commits and the coordinator later says abort, or vice versa, the system is inconsistent. So it waits.

In Postgres that is a row in pg_prepared_xacts; in MySQL, XA RECOVER lists it.

The locks stay held, blocking every other transaction that touches those rows, until the coordinator restarts and reads its own log to replay the decision, or an operator resolves it by hand with COMMIT PREPARED or ROLLBACK PREPARED.

That in-doubt window is the blocking problem, and it is why 2PC's availability is bounded by the coordinator's availability. Some systems add a third phase or use consensus for the decision to shrink it.

"Give me a saga concretely for an order: the steps, the compensations, and what a customer might see."

Steps: reserve inventory, charge the card, create the shipment. Compensations, in reverse: cancel the shipment, refund the charge, release the reservation. If the shipment service fails after the charge succeeded, the orchestrator runs the refund and the release, and marks the order failed.

What the customer might see: a pending charge on their card that later disappears, an item that showed as reserved for a few minutes, and an order that briefly said "processing" then "could not be completed". Those visible intermediate states are the isolation we gave up.

Design consequences: every step must be idempotent because the orchestrator retries, every compensation must succeed eventually even if it retries for hours, and some actions cannot be compensated at all — an email sent — so they go last.

"Orchestration or choreography — which do you pick and why?"

Orchestration by default.

An orchestrator — a service or a workflow engine like Temporal or Camunda — holds the saga's state, calls each step, and runs compensations on failure, so the whole flow is readable in one place and its state is queryable when something goes wrong.

Choreography, where each service reacts to the previous service's event and emits its own, has no central state, which makes it resilient to one coordinator failing but makes the flow invisible; debugging "why is this order stuck" means tracing events across five services.

I choose choreography only for simple, short flows with two or three steps and no complex compensation. For anything with money and more than a couple of steps, the orchestrator's explicit state is worth its coupling.

"When would you still choose 2PC today?"

When both resources are databases I control, both support XA, the transaction is short, volume is moderate, and the alternative — a saga with compensations — would be more complex than the failure it avoids.

A classic example is moving a record between two Postgres databases during a migration, where a saga's intermediate state would be visible to users and the compensation logic would rival the feature.

Another is a JMS queue and a database in the same JTA transaction within one application server, which is 2PC hidden in the framework.

Even then I put in-doubt monitoring on pg_prepared_xacts and XA RECOVER and a runbook for resolving them, because that is the failure mode I am accepting.

Q50 · Scenario. "During a failover you lost writes the application had confirmed to users. The team says 'never again'. Walk through the durability and replication settings and what each one trades."

Reveal answer

Strong answer First establish where the write died, because "durable" has two independent layers — the node and the fleet:

  1. If the write was confirmed and the same node lost it after a crash, node durability was relaxed. MySQL: innodb_flush_log_at_trx_commit — 1 fsyncs the redo log at every commit (safe); 2 fsyncs about once a second, so an OS crash loses up to a second of acknowledged commits; 0 is worse. Its partner sync_binlog=1 fsyncs the binary log per commit — without it, a crash can lose binlog events the replicas needed, leaving primary and replicas divergent. The pair set to 1 and 1 is the durability baseline, and its cost is commit latency. Postgres folds this into synchronous_commit: off risks the last moments of acknowledged work on that node.
  2. If the write survived on the old primary but vanished because you promoted a replica that never had it — the usual failover story — the cause is asynchronous replication: the primary acknowledged commits before any replica received them. That data loss is not a bug; it is the documented contract of async replication.
  3. The fix for that layer is synchronous replication: commit does not return until a standby confirms. MySQL: semi-synchronous replication or Group Replication — the commit waits for at least one replica to acknowledge receipt. Postgres: synchronous_standby_names plus synchronous_commit levels — remote_write (standby received it), on (standby flushed it), remote_apply (standby applied it, so reads there see it). Each step right is safer and slower.
  4. Now state the trades so the business chooses with open eyes: synchronous replication adds a network round trip to every commit — the standby's latency is now in your commit path — and it couples availability: if the only sync standby dies, commits stall until you reconfigure or fail open, which quietly reintroduces the loss window.

Land it "We lost writes in failover" means async replication was a decision someone made — "never again" is purchasable, and the price is stated in commit milliseconds and availability coupling, so make the business say the number.

Likely follow-ups
"You turned on synchronous replication and the only standby went down at 3 a.m. What happened to the application?"

Every commit stalled. With synchronous_standby_names naming one standby and synchronous_commit = on, the primary waits for that standby's acknowledgement before returning, and with the standby gone it waits forever; writes hang, connections fill, and the application is down even though the primary is healthy.

The recovery is either bringing the standby back or removing it from synchronous_standby_names and reloading, which reopens the loss window.

The design that avoids this is more than one standby with a quorum: synchronous_standby_names = 'ANY 1 (s1, s2)', so any one of two acknowledging is enough.

MySQL semi-sync has the same trap and a built-in fallback: after rpl_semi_sync_source_timeout, default ten seconds, it silently degrades to asynchronous, which is the "fail open" I mentioned and must be alerted on.

"What is the difference between remote_write, on, and remote_apply in practice?"

remote_write means the standby has received the WAL and written it to its operating system, not fsynced; it survives a standby process crash but not a standby power loss, and it is the cheapest.

on means the standby has fsynced the WAL to disk, so the commit survives any single-node loss; this is the level that makes failover lossless.

remote_apply means the standby has also applied the WAL so a read on the standby immediately after the commit sees the data; it is for read-your-writes across replicas and is the slowest because apply lag is included.

For "never lose a confirmed write", on is the requirement; remote_apply is a consistency feature, not a durability one, and I would not pay for it unless reads are routed to the standby.

"How does the failover tool decide which replica to promote, and how does a wrong choice lose data?"

It should promote the replica with the most recent replicated position: in Postgres the highest pg_last_wal_receive_lsn(), in MySQL the most complete executed GTID set. Tools like Patroni and Orchestrator do this and also refuse to promote a candidate that lags beyond a configured threshold.

A wrong choice — promoting a replica that is behind another — loses the transactions that only the more advanced replica had, and worse, when the old primary or the advanced replica is reattached, its extra transactions must be discarded to rejoin, which is where pg_rewind and MySQL's errant-transaction handling come in.

With asynchronous replication even the best candidate may lack the last commits; only synchronous replication guarantees the promoted node has everything acknowledged.

"What number would you put in front of the business, and how would you measure it?"

Two numbers.

First, the added commit latency: measure p50 and p99 of a simple insert-and-commit with synchronous replication off and then on, against the real standby over the real network; within a region I would expect one to three milliseconds added, across regions tens of milliseconds, and I would show how that changes end-user request latency for the write-heavy endpoints.

Second, the availability coupling: the probability and duration of standby unavailability from the last year's incidents, and what each minute of stalled writes costs.

Against those, the third number is the current loss window: replication lag at p99 from monitoring, which is the amount of confirmed work a failover today would discard. With those three figures the decision is a business one, made with open eyes.

07 · DrillIndexes & Query Tuning — Q51–Q100

Index questions are where a database round stops being trivia and starts being engineering. The interviewer is checking whether you understand what an index physically is, why the planner sometimes refuses to use one, and whether you can read a real execution plan under pressure. Every answer below names the engine — MySQL's InnoDB and PostgreSQL disagree in places, and a senior is expected to say which one they mean.

Drill · B+trees & storage

These questions test whether you know what an index physically is on disk — because everything else about tuning follows from that picture.

Q51. "Why do databases use B+trees for indexes instead of hash tables or binary search trees?"

Reveal answer

The real test Can you connect the data structure choice to disk pages and range queries, with actual numbers.

Strong answer A B+tree is a balanced tree where every node is one disk page — the fixed-size block the database reads and writes as a unit, 16 KB in InnoDB and 8 KB in Postgres — and all the actual keys live in the leaf pages, sorted and linked left to right.

That shape wins for three reasons.

First, because each node is a whole page holding hundreds of keys, the tree is extremely wide and therefore extremely shallow: if one 16 KB internal page holds roughly 1,000 child pointers, three levels already address 1,000 × 1,000 × 1,000 — a billion entries — so a lookup costs three or four page reads, and the top levels are almost always cached in memory.

A binary tree stores one key per node, so a billion rows means a path about 30 nodes deep — potentially 30 separate disk reads.

Second, the sorted, linked leaves make range scans cheap: BETWEEN, ORDER BY, and prefix matches just walk sideways along the leaf chain. A hash table answers only exact-equality questions — it has no ordering at all.

Third, B+trees degrade gracefully under growth, while hash tables need disruptive resizing.

Land it The B+tree is the shape you get when you optimize for "few page reads per lookup, and sorted order for free" — which is exactly what a disk-backed database needs.

Likely follow-ups
"What is the difference between a B-tree and a B+tree, and why does the plus matter for databases?"

In a B-tree every node, internal or leaf, holds keys and the data or pointers to it. In a B+tree the internal nodes hold only separator keys and child pointers, and all the actual entries live in the leaves, which are linked into a sorted list.

The plus matters twice. Internal nodes without data fit far more separators per page, so fan-out is higher and the tree is shallower — that is where the three-levels-for-a-billion number comes from.

And the linked leaves make a range scan a sequential walk: find the start leaf, then follow next-page pointers, never climbing back up the tree.

InnoDB's clustered index and secondary indexes, and Postgres's btree access method, are all B+trees in this sense, though everyone still says "btree".

"How many entries actually fit on a page, and what shrinks that number in practice?"

For an InnoDB secondary index on a BIGINT with a BIGINT primary key, each leaf entry is roughly 8 bytes of key, 8 bytes of primary key, plus about 5 bytes of record header, so around 20 bytes, which gives about 700 entries on a 16 kilobyte page after overhead.

Internal pages hold key plus a 4-byte child pointer, so more than a thousand.

What shrinks it: wide keys, especially VARCHAR with utf8mb4 where the maximum length is reserved in the sort key; composite indexes with several columns; a fat primary key such as a 36-character UUID string copied into every secondary entry; and low fill from random inserts, which leaves pages half empty.

Postgres's 8 kilobyte pages halve all of these, which is why its indexes are slightly deeper.

"When does an LSM tree beat a B+tree, and do MySQL or Postgres offer one?"

A log-structured merge tree buffers writes in memory, flushes sorted runs sequentially, and merges them in the background, so it turns random writes into sequential ones and wins on write-heavy workloads with many inserts and few reads, at the cost of read amplification — a lookup may check several runs — and background compaction I/O. B+trees win on read-heavy and mixed workloads where point and range lookups dominate and in-place updates are common. MySQL offers an LSM engine, MyRocks, in the Percona and Facebook distributions, used for space and write efficiency at very large scale; upstream MySQL and Postgres are B+tree-based with no built-in LSM as of Aug 2026. For an ordinary OLTP service, the B+tree is the right default and the LSM is a specialist tool.

"Why is the top of the tree 'almost always cached'? Quantify it."

Because the upper levels are tiny relative to the leaves. A billion-entry index with fan-out of a thousand has one root page, about a thousand second-level pages, about a million leaf pages.

The root and second level together are a thousand pages, sixteen megabytes in InnoDB, and they are touched by every lookup, so the cache's least-recently-used policy keeps them resident even under pressure.

The leaf level is sixteen gigabytes and only the leaves matching recent queries stay cached. So the cost of a lookup is dominated by whether that one leaf page is in memory, and that is what the buffer pool hit ratio really measures.

This is also why doubling the table rarely doubles lookup cost: it adds leaf pages, not levels.

Q52. "Explain clustered versus secondary indexes — and how a secondary-index lookup actually reaches the row in InnoDB versus Postgres."

Reveal answer

The real test Whether you know the two engines store tables completely differently, and what that costs per lookup.

Strong answer In InnoDB the table is a B+tree: the clustered index is a B+tree ordered by the primary key whose leaf pages contain the full rows themselves.

Every secondary index — any other index you create — stores at its leaves the indexed columns plus a copy of the primary key.

So a secondary-index lookup is two traversals: descend the secondary index to find the primary-key value, then descend the clustered index to fetch the row.

Postgres has no clustered index at all — the table is a heap, an unordered pile of pages, and every index is secondary.

A Postgres index entry points to a TID, the tuple identifier, which is a physical address of the form (page number, slot on that page), so the index leads straight to the row in one hop.

But Postgres then must do a visibility check, because its MVCC — multi-version concurrency control, the scheme where updates create new row versions rather than overwriting, so each transaction sees a consistent snapshot — keeps old and new versions side by side in the heap, and the index cannot tell which version your transaction is allowed to see.

Land it InnoDB pays a second tree traversal per secondary lookup; Postgres pays a heap visit plus a visibility check — different taxes, same lesson: a covering index that avoids the second step is gold in both engines.

Likely follow-ups
"Does Postgres's CLUSTER command give it a clustered index?"

No, only a one-time physical sort. CLUSTER orders USING idx_orders_customer rewrites the heap so rows are stored in that index's order, which improves locality for range scans on that key.

But the heap does not stay sorted: new inserts and updates go wherever there is free space, so the order decays until the next CLUSTER, which takes an exclusive lock and rewrites the whole table.

Postgres tracks how well the heap matches an index in pg_stats.correlation, and the planner uses that to cost index scans.

The nearest thing to InnoDB's behaviour is a table whose rows are inserted in key order and rarely updated, like an append-only event table keyed by time, where correlation stays near one naturally.

"What are the operational consequences of the InnoDB design when a row is updated?"

Two things happen. First, if the update changes any indexed column, the corresponding secondary index entry is deleted and reinserted, and because the secondary entry holds the primary key rather than a physical address, updates that do not touch indexed columns leave all secondary indexes alone.

Second, if the update changes the primary key itself, InnoDB must delete and reinsert the whole row in the clustered index and update every secondary index entry, since they all carry the key — that is why changing primary keys is treated as a schema smell.

There is also the change buffer: for secondary indexes that are not unique, InnoDB can buffer the index modification in memory and apply it later when the page is read, which is a significant write optimisation Postgres lacks.

"What is the practical cost of the visibility check in a Postgres index scan, and how do you see it?"

Each index entry leads to a heap page read, where the tuple header's xmin and xmax are compared with the snapshot.

If the heap page is cached, that is a memory access; if not, it is a random I/O. The cost shows up in EXPLAIN (ANALYZE, BUFFERS) as shared hits and reads on the index scan node, and in Heap Fetches on an index-only scan node.

What makes it expensive is dead tuples: a row updated a hundred times without vacuum has a hundred index entries pointing to versions that the scan must visit and reject, so the same query does a hundred times the heap reads.

pg_stat_user_tables.n_dead_tup and a recent last_autovacuum are what I check when an index scan is slower than its row count suggests.

"What happens in InnoDB if a table has no primary key?"

InnoDB still needs a clustered index, so it picks one. If there is a unique index with all non-null columns, it uses the first such index as the clustered key.

Otherwise it generates a hidden 6-byte row id column, DB_ROW_ID, and clusters on that; the row id comes from a global counter shared by all such tables, which is a contention point under heavy inserts, and the hidden key is unusable for lookups and invisible to replication tools, so row-based replication of updates and deletes must scan the table on the replica.

As of MySQL 8.0.30 sql_require_primary_key can forbid creating such tables, and I turn it on. In Postgres a table without a primary key is normal storage-wise, but logical replication needs a replica identity.

Q53. "Why do people insist that InnoDB primary keys should be short and monotonically increasing?"

Reveal answer

Strong answer Both properties fall out of the clustered-index design.

Short, because InnoDB copies the primary key into every leaf entry of every secondary index — a 36-byte primary key versus an 8-byte BIGINT makes every secondary index on the table dramatically fatter, which means fewer entries per page, deeper trees, and less of each index fitting in the buffer pool — the slice of RAM where InnoDB caches pages.

Monotonic, because rows physically live in primary-key order: if each new key is larger than the last, inserts always append to the rightmost leaf page, which stays hot in memory and fills pages completely.

If keys arrive in random order, every insert lands on a random page somewhere in the tree, forcing that page to be read into memory and often split. An auto-increment BIGINT gives you both properties by construction.

Land it In InnoDB the primary key is not just an identifier — it is the physical layout of the table and a component of every other index, so its size and ordering are a storage-wide decision.

Likely follow-ups
"Is there a downside to a monotonically increasing key? What is the 'rightmost page' problem?"

Yes: every insert targets the same leaf page, the rightmost one, so under very high concurrent insert rates all inserters contend on the same page latch and the same auto-increment counter.

InnoDB mitigates the counter with innodb_autoinc_lock_mode = 2, interleaved mode, the default in 8.0, which hands out values without a table-level lock.

The page latch contention remains and shows up in SHOW ENGINE INNODB STATUS as waits on the index page, typically only above tens of thousands of inserts per second on one table.

In Postgres the equivalent is contention on the rightmost btree leaf, which Postgres 12+ reduced with better page split behaviour.

For that extreme case, a key with a small amount of prefix variety — a hash bucket prefix, or UUIDv7 which spreads within a millisecond — spreads the inserts across a few pages.

"How much bigger do secondary indexes get with a CHAR(36) UUID primary key versus BIGINT? Give me the arithmetic."

Take a secondary index on a BIGINT column. With a BIGINT primary key, each leaf entry is about 8 plus 8 plus header, call it 21 bytes.

With a CHAR(36) key in utf8mb4, the primary key portion is 36 characters but InnoDB reserves up to 144 bytes for it in the sort key and stores the actual 36, so the entry is about 8 plus 36 plus header, around 49 bytes, more than double.

Fewer entries per page means the index has more than twice as many leaf pages, may gain a level, and needs twice the buffer pool to cache the same fraction. With ten secondary indexes on a table, that is ten indexes each more than doubled.

Storing the UUID as BINARY(16) brings the entry to about 29 bytes, which is why that is the minimum I accept.

"Does the same advice apply to Postgres?"

Partly. Postgres index entries point to a six-byte tuple id, not the primary key, so secondary indexes do not grow with the primary key's width, and "short" matters far less.

"Monotonic" still matters for the primary-key index itself: random keys cause the same random-page inserts and splits in that one btree, with the same cache and bloat effects, though not for the table, since the heap is unordered.

The practical guidance for Postgres is: BIGINT identity or a time-ordered UUID for the primary key, and a native uuid column type, which is 16 bytes, never a text UUID. Postgres 13 added btree deduplication and Postgres 18 added a native uuidv7() function, so as of Aug 2026 time-ordered UUIDs are a first-class option there.

Q54 · Scenario. "Your orders table uses random UUIDv4 strings as the InnoDB primary key. At 200 million rows, insert throughput has fallen off a cliff and the disk is constantly busy. What is happening, and what would you change?"

Reveal answer

The real test Can you narrate the physical failure mode — splits, bloat, cold cache — and give a realistic migration, not just "don't use UUIDs".

Strong answer I would diagnose it in this order:

  1. Because UUIDv4 values are random, each insert lands at a random position in the clustered index instead of appending at the right edge. The target leaf page is usually not in the buffer pool, so it must be read from disk, and if it is full it undergoes a page split — one full page becomes two half-full ones. I would confirm the cache is thrashing by watching innodb_buffer_pool_reads (misses that went to disk) climbing relative to total read requests.
  2. Splits everywhere leave pages 50–70% full instead of the ~94% you get with sequential inserts, so the table and every secondary index are perhaps a third larger than they need to be — and each secondary index also carries the fat 16-byte (or worse, CHAR(36)) primary key in every entry.
  3. Random inserts mean the working set is effectively the entire tree, which no longer fits in the buffer pool — that is the cliff: the moment the hot set outgrew RAM.

The fix is to make the key time-ordered.

Either switch to UUIDv7 or ULID — UUID formats whose leading bits are a timestamp, so values generated close in time sort close together — or use an auto-increment BIGINT primary key internally and keep the UUID as a separate BINARY(16) column with a unique index for external references.

Prevention: treat primary-key choice as a capacity decision at design time. In Postgres the pain is smaller because the heap is not ordered by the key, but the primary-key index itself still splits and bloats the same way, so time-ordered IDs are still the right call.

Land it The problem was never "UUIDs are slow" — it is that random key order turns every insert into a random cold-page write, and the fix is restoring locality, not abandoning UUIDs.

Likely follow-ups
"You cannot change the primary key on a 200-million-row table overnight. What is the migration plan?"

Expand-and-contract with an online tool. Step one, add a BIGINT id column with auto-increment or a sequence, and a BINARY(16) uuid column, and backfill in chunks.

Step two, add a unique index on the new id and update application code to write both and read by either.

Step three, use gh-ost or pt-online-schema-change to rebuild the table with the new primary key — those tools copy the table row by row into a new one with the new definition while capturing changes via triggers or the binlog, then swap, so the only lock is the final rename.

The rebuild also compacts the 50-70 percent full pages. Step four, repoint foreign keys in child tables, which is the slow part and often done table by table. Total elapsed time is days; the write cost is bounded by chunk size and the tool's throttling.

"Why does UUIDv7 fix it, and what is the risk of using it?"

UUIDv7 puts a 48-bit Unix millisecond timestamp in the leading bits, followed by random bits.

Values generated in the same millisecond sort together and later ones sort after, so inserts go to the rightmost region of the clustered index, pages fill, and the working set is the recent edge rather than the whole tree.

The residual randomness within a millisecond spreads inserts over a few pages, which is actually good for latch contention.

Risks: the timestamp leaks creation time, which may matter for privacy; generators on machines with skewed clocks produce out-of-order keys, which is harmless for correctness but reintroduces some randomness; and it must be stored as BINARY(16) or the native Postgres uuid type, not as a 36-character string, or the size problem stays.

"How do you confirm the buffer pool hypothesis rather than assume it?"

With three numbers over the same window.

SHOW GLOBAL STATUS LIKE 'Innodb_buffer_pool_read%' gives Innodb_buffer_pool_reads, pages read from disk, and Innodb_buffer_pool_read_requests, all logical reads; a miss ratio above a few percent on an OLTP system is bad, and I would graph it against insert rate to see them correlate.

Innodb_buffer_pool_pages_dirty and Innodb_buffer_pool_wait_free rising mean the pool is thrashing dirty pages out. Then the physical evidence: information_schema.innodb_metrics has index_page_splits, and comparing the table's data length from information_schema.tables with row count times average row size shows the fill factor.

And I would check the disk: iostat showing high read IOPS during an insert-only workload is the signature of random cold-page reads.

"What would you cut if you had one week and a tight budget?"

The rebuild. Changing the primary key type is the right long-term fix but is the multi-day, high-risk part.

In one week I would stop the bleeding: switch new inserts to UUIDv7 in the same column type, which immediately makes new inserts append at the right edge, so the hot working set shrinks from the whole tree to the recent region even though old rows stay random; run OPTIMIZE TABLE via ALTER TABLE ... ENGINE=InnoDB, ALGORITHM=INPLACE or gh-ost to compact the half-full pages, which recovers a third of the space and cache; and size the buffer pool up if the hardware allows, since the cliff is where the working set left RAM. The BIGINT-plus-BINARY(16) redesign goes on the roadmap with the measured numbers attached.

Q55. "What exactly is a page split, and why should I care?"

Reveal answer

Strong answer When an insert must go into a leaf page that is already full, the database allocates a new page, moves roughly half the entries across, and inserts a new pointer into the parent — that is a page split.

If the parent is also full, it splits too, and in the worst case the split cascades up and the tree grows a level. You care for three reasons. It multiplies write cost: one logical insert becomes several page writes plus their log records.

It wastes space: the two resulting pages are each about half full, and with random inserts they tend to stay that way, so the structure bloats. And it destroys locality: entries that were neighbors end up on pages far apart on disk.

Sequential inserts avoid nearly all of this because InnoDB detects the append pattern and splits at the insertion point instead of the middle, leaving full pages behind.

Land it Page splits are the mechanism behind "random keys are expensive" — one sentence of mechanism is worth more in an interview than ten rules of thumb.

Likely follow-ups
"Do pages ever merge back when rows are deleted?"

Rarely, and the engines differ. InnoDB does merge: when a page's fill drops below MERGE_THRESHOLD, 50 percent by default and settable per index, it tries to merge with a neighbour, so deletes can eventually shrink the tree.

Postgres btrees do not merge: a page that becomes completely empty is unlinked and recycled by vacuum for reuse within the same index, but a page that keeps even one live entry stays, and partially empty pages never combine.

So on Postgres, a table that churns through deletes and inserts on an advancing key — a queue, a time-series table with retention — ends up with many sparse pages, which is index bloat, and only REINDEX compacts it.

That asymmetry is why bloat monitoring is a Postgres duty and mostly not an InnoDB one.

"What is fill factor, and how would you set it?"

Fill factor is how full the engine packs a page when it builds or splits it, leaving the rest as slack for future inserts. Postgres defaults to 90 percent for btree leaves and 100 percent for heap pages; both are settable with CREATE INDEX ... WITH (fillfactor = 70) or ALTER TABLE ... SET (fillfactor = 80).

InnoDB has innodb_fill_factor, default 100, applied only during index builds and rebuilds.

I lower fill factor for indexes on columns that receive random inserts, so the slack absorbs them without splitting, and for heap tables with frequent updates, so Postgres HOT updates find room on the same page.

I leave it at default for append-only keys, where slack would just waste space, since inserts never land in the middle.

"How would you measure how many splits a workload is causing?"

In MySQL, information_schema.innodb_metrics has counters index_page_splits and index_page_merge_successful, which are off by default and enabled with SET GLOBAL innodb_monitor_enable = 'index_page_splits'; I would sample them per minute and compare against the insert rate.

A split rate approaching the insert rate on a large table means nearly every insert is landing on a full page — the random-key signature.

In Postgres, pgstattuple's pgstatindex() shows avg_leaf_density and leaf page counts over time, and the number of leaf pages growing faster than entries indicates splits; pg_stat_user_indexes does not count splits directly.

The proxy in both is the fill: sequential inserts leave pages near 94 percent, random ones near 50 to 70.

Q56. "MySQL's EXPLAIN says Using index; Postgres says Index Only Scan. What do these mean — and why might Postgres still read the table anyway?"

Reveal answer

Strong answer Both mean a covering index: every column the query needs is present in the index itself, so the engine answers from the index alone and skips the second step — no clustered-index traversal in InnoDB, no heap visit in Postgres.

That is often the difference between one page read and two per row, so on hot queries it can halve the I/O. The Postgres caveat comes from MVCC: the index does not know whether an entry is visible to your snapshot.

Normally that would force a heap visit per row, which would defeat the whole idea, so Postgres keeps a visibility map — one bit per heap page saying "every row version on this page is visible to all transactions".

An Index Only Scan trusts that bit and only falls back to the heap for pages where the bit is unset. The bit is set by vacuum, the background process that cleans up dead row versions.

So on a heavily updated table that has not been vacuumed recently, EXPLAIN ANALYZE will show a large Heap Fetches count and the "index only" scan quietly does heap reads anyway.

Land it A covering index is a contract, and in Postgres vacuum is the party that keeps it honest — if Heap Fetches is high, tune autovacuum before blaming the index.

Likely follow-ups
"Heap Fetches is high. What exactly do you do about it, in order?"

First, confirm it is vacuum lag and not just churn: SELECT n_dead_tup, n_tup_upd, last_autovacuum FROM pg_stat_user_tables WHERE relname = 'orders'. If the last autovacuum is old and dead tuples are high, run VACUUM orders manually and re-check the plan; Heap Fetches should collapse.

Then make it stay fixed: lower autovacuum_vacuum_scale_factor for that table so vacuum runs after a small fraction changes, since the visibility map is only set by vacuum.

If the table is updated so constantly that pages are never all-visible for long, an index-only scan is the wrong expectation on that table, and I accept the heap visit or reduce updates to the indexed columns.

Note that inserts also clear the bit, and since Postgres 13 autovacuum triggers on inserts too via autovacuum_vacuum_insert_scale_factor.

"Does InnoDB have any equivalent problem with covering reads?"

Not the visibility map problem, because InnoDB's secondary index entries carry the transaction id of the last change on the page in a way that lets it decide visibility differently: a secondary index page has a PAGE_MAX_TRX_ID field, and if that id is older than the reader's snapshot, every entry on the page is known visible and the covering read proceeds without touching the clustered index.

If the page was modified recently by a transaction the reader cannot see, InnoDB has to go to the clustered index and walk undo to check the row, so a covering index on a hot page can quietly stop being covering.

It is the same shape of caveat as Postgres, but per page and automatic, with no vacuum dependency. It shows up as a rising Innodb_buffer_pool_read_requests relative to rows returned rather than as an EXPLAIN line.

"What does 'Using index condition' mean in MySQL, and how is it different from 'Using index'?"

Using index means the query is fully answered from the index with no table access.

Using index condition is index condition pushdown: part of the WHERE clause that references indexed columns but cannot be used to seek — say a LIKE on a trailing column — is evaluated inside the storage engine while scanning the index, before fetching the row, so rows that fail it never cost a clustered-index lookup.

It still touches the table for the survivors. It is a good sign but not a covering read. The related Using where means filtering in the server layer after the row is fetched, which is the most expensive form.

Postgres has the analogous distinction between Index Cond, used for seeking, and Filter, applied after fetch, with Rows Removed by Filter quantifying the waste.

"How do you find out which of your queries could become index-only with a small change?"

From plans of the top queries by total time.

For each, I look at the index scan node and compare the columns it returns against the index definition: if the query projects one or two columns beyond the index, adding them with INCLUDE in Postgres or as trailing key columns in MySQL turns it index-only.

pg_stat_user_indexes.idx_tup_read versus idx_tup_fetch gives a table-wide view: a high fetch count relative to reads means many heap visits through that index. In MySQL the performance_schema.table_io_waits_summary_by_index_usage table shows reads per index and the NULL index row shows full scans.

Then I estimate the write cost per candidate and only convert the ones with a large read volume behind them.

Q57. "When would you actually use a hash index?"

Reveal answer

The real test Honesty — the expected answer is "almost never", said with precise reasons.

Strong answer Almost never, and I would say so plainly.

A hash index answers only exact equality — no ranges, no ORDER BY, no prefix matching — so it competes with a B+tree only on point lookups, where the B+tree is already three or four mostly-cached page reads.

In MySQL you cannot even create one on InnoDB; explicit hash indexes exist only in the MEMORY engine.

InnoDB does build an adaptive hash index internally — an automatic in-memory hash over hot B+tree pages — but that is managed for you and is sometimes disabled on high-concurrency workloads because of contention on its latches.

Postgres does have real hash indexes, and since Postgres 10 they are crash-safe and replicated, so they are no longer dangerous — they can slightly beat a btree for equality on very long keys, where the btree would store huge entries. That is the one honest niche.

Land it Default to btree and mention the long-key equality niche — knowing why the exotic option loses is the senior signal here.

Likely follow-ups
"What does the adaptive hash index do, and when would you turn it off?"

InnoDB watches which index pages are looked up by equality frequently and builds an in-memory hash from those key prefixes directly to the page record, so a hot point lookup skips the B+tree descent. It is automatic and controlled by innodb_adaptive_hash_index, on by default.

The problem is that the hash is protected by a small number of latches, partitioned by innodb_adaptive_hash_index_parts, and under high concurrency with mixed reads and writes those latches become a contention point that shows up in SHOW ENGINE INNODB STATUS under the semaphores section as waits on btr0sea.cc.

I turn it off when I see those waits, when the workload is mostly range scans or joins that gain nothing from it, or during a large data load, and I measure throughput before and after because the effect varies by workload.

"Postgres hash indexes are fine now, you said. Give me the concrete case where you would create one."

Equality lookups on a long text key, such as a URL or a JSON document hash column, where a btree entry would be hundreds of bytes and the index would be huge and deep.

A hash index stores a 4-byte hash per entry regardless of key length, so it is small, fits in cache, and answers WHERE url = ? in about one page read. I would create it with CREATE INDEX ON pages USING hash (url).

What it cannot do: enforce uniqueness, so a unique constraint still needs a btree or an expression btree on md5(url); serve ranges, ordering, or prefix LIKE; or be used by the planner for anything other than equality.

Since Postgres 10 it is WAL-logged and safe on replicas, which removed the old reason to avoid it.

"How does a hash index handle growth without disruptive resizing?"

Postgres uses linear hashing, which splits one bucket at a time as the index grows instead of rehashing everything at once, so growth is incremental and there is no big pause.

Each split moves roughly half of one bucket's entries to a new bucket and advances a split pointer. That answers the classic objection to hash tables in a database.

The remaining costs are that buckets overflow into extra pages when many keys collide or the index is behind on splits, and that the index has no useful order, so a scan of the whole index is random over the heap.

In practice for the long-key equality case it performs well; for everything else the btree's flexibility wins.

Q58. "How deep does a B+tree index actually get as a table grows — say from a million rows to a billion?"

Reveal answer

Strong answer Far shallower than intuition suggests, and I would put numbers on it. With InnoDB's 16 KB pages and a BIGINT key, an internal page holds on the order of 1,000 to 1,200 child pointers.

So two levels — root plus leaves — already cover roughly a million entries; three levels cover on the order of a billion; four levels cover more rows than any real table.

Postgres pages are 8 KB so the fan-out is roughly half, but the arithmetic still lands at four or five levels for a billion rows.

The practical consequences: a point lookup costs "depth" page touches, the root and inner levels are almost always cached, so growing a table 100× typically adds one level — one extra page read — to each lookup.

That is why index lookups feel flat as tables grow, and why the real scaling pain comes from elsewhere: cache misses at the leaf level and write amplification, not tree depth.

Land it Being able to say "three to four levels for a billion rows, and only the leaf read is likely cold" shows you have actually done the arithmetic rather than memorized "logarithmic".

Likely follow-ups
"So if depth barely grows, why do big tables feel slow?"

Because depth measures logical page touches, not physical I/O. As the table grows, the leaf level grows linearly, and the fraction of leaves that fit in the buffer pool falls.

A lookup on a small table hits three cached pages; the same lookup on a huge table hits two cached pages and one leaf page that must come from disk, and one random read at a hundred microseconds on an SSD is a thousand times a memory access.

Then range scans and joins touch many leaves. And writes: every insert updates every index, and random inserts on huge indexes are cache misses plus page splits.

So the slowdown is the cache hit ratio and the write amplification, both of which scale with data size, while the tree depth stays at three or four.

"Show me how to check the actual depth of an index in each engine."

In Postgres, the pageinspect extension: SELECT level FROM bt_metap('idx_orders_customer') returns the root level, so a root level of 3 means four levels including leaves, and pgstatindex from pgstattuple returns tree_level too, alongside density. In MySQL, information_schema.innodb_indexes has no depth column, but mysql.innodb_index_stats with stat_name = 'n_leaf_pages' and 'size' per index lets me infer it, and the older innochecksum or the innodb_ruby tool can dump page levels. In practice I mostly use the leaf page count from those views: a hundred thousand leaf pages with fan-out around a thousand means three levels, and that arithmetic is enough for capacity discussions.

"What happens to depth with a composite index of four VARCHAR columns?"

Fan-out drops, so depth rises sooner.

If each internal separator is now 150 bytes instead of 12, a 16 kilobyte page holds about a hundred child pointers instead of a thousand, so two levels cover ten thousand entries, three cover a million, four cover a hundred million, and a billion rows need five levels.

Two extra levels means two extra page touches per lookup and a much larger set of internal pages, some of which may not stay cached.

InnoDB and Postgres both use suffix truncation to shorten separator keys in internal pages to the minimum distinguishing prefix, which recovers some fan-out for long keys, but a wide key still costs.

This is the depth argument for narrow leading columns and for hashing long strings instead of indexing them raw.

Drill · Composite & specialized indexes

This group tests whether you can design an index deliberately — column order, coverage, and the specialized forms — instead of throwing single-column indexes at a table.

Q59 · Scenario. "A colleague added a composite index on (a, b, c), but the query WHERE b = ? AND c = ? still does a full table scan. They insist the columns are indexed. What do you tell them?"

Reveal answer

Strong answer I would explain the leftmost-prefix rule with the phone-book picture. A composite index sorts entries by a first, then by b within each value of a, then by c — exactly like a phone book sorted by last name, then first name.

Asking for b = ? AND c = ? without a is asking the phone book for everyone named "John": the Johns are scattered through the whole book, so there is no single place to seek to.

The index is usable only when the query constrains a leading prefix of the column list — a, or a, b, or a, b, c. Then I would walk through the fixes in order:

  1. If the query is the important one, create an index leading with b — (b, c) — or reorder the existing one if nothing depends on the current order.
  2. If a has only a handful of distinct values, some engines can work around it: MySQL 8.0.13+ has a limited skip scan, and Postgres 18 added one too, but both are narrow optimizations I would verify in the plan, never design for.
  3. Honesty note: Postgres may still show an "Index Scan" here if the index covers the query — but it is scanning the entire index and filtering, which is cheaper than the table only because the index is smaller. The rows and cost numbers give it away.

Land it "The columns are indexed" is not the question — "can the engine seek on a sorted prefix" is, and that is decided by column order, not column membership.

Likely follow-ups
"Which queries does the existing (a, b, c) index serve, and which does it not?"

It serves any query that constrains a with equality, plus optionally b, plus optionally c, in that order: a = ?, a = ? AND b = ?, a = ? AND b = ? AND c = ?, and ranges on the last constrained column such as a = ? AND b > ?.

It also serves ORDER BY a, b, c and ORDER BY a, b within an equality on a. It does not seek for b = ?, c = ?, or b = ? AND c = ?.

And with a range on a, such as a > ?, it can seek on a but must then filter on b and c rather than seek, because inside a range of a the b values are no longer contiguous. That last point is what people miss.

"Explain skip scan mechanically, and why you would not design for it."

Skip scan turns WHERE b = ? on an index (a, b) into a loop over the distinct values of a: for each distinct a, seek to (a, b), read the matches, then jump to the next distinct a.

If a has five distinct values, that is five seeks, which is excellent. If a has a million distinct values, it is a million seeks, which is worse than a full scan, so the planner only chooses it when the leading column's cardinality is small.

I would not design for it because the cardinality of a is a property of the data that changes over time, so a query that is fast today can become slow when a new tenant adds ten thousand distinct values, and the failure is silent. A dedicated index on (b, c) is deterministic.

"Would (b, c, a) be a better single index than (a, b, c)?"

Only if the queries justify it, and the honest answer is that no single order serves both. (b, c, a) serves the colleague's query and any query leading with b, but stops serving a = ? alone.

The way to decide is to list the actual queries from pg_stat_statements or the digest table, grouped by the columns they constrain and how, then choose one or two indexes that cover the leading patterns, with equality columns first and the most frequently constrained column leading.

Often the answer is two indexes, (a, b, c) and (b, c), and the write cost of the second is paid for by removing some other unused index. Column order is a workload decision, not a table decision.

"How would you show the colleague, in the plan, that the index is being scanned rather than sought?"

In Postgres, EXPLAIN (ANALYZE, BUFFERS): a true seek shows Index Scan with Index Cond: ((a = ?) AND (b = ?)), a small Buffers: shared hit count, and rows close to the result.

A full index scan shows Index Only Scan or Index Scan with Index Cond listing only b and c, a buffers count proportional to the index size, and Rows Removed by Filter in the thousands if it is filtering.

The comparison of buffers touched with rows returned is the tell.

In MySQL, EXPLAIN shows type: index, meaning a full index scan, versus type: ref for a seek, and key_len tells how many leading columns are actually used for the seek — if it equals only the width of a, only a is used.

Q60. "For WHERE status = ? AND created_at > ?, does the composite index go (status, created_at) or (created_at, status) — and why?"

Reveal answer

The real test The equality-first rule, derived rather than recited.

Strong answer (status, created_at) — equality columns first, then the range column. Walking it through: with (status, created_at), all rows for status = 'PAID' form one contiguous section of the index, sorted by created_at inside that section.

The engine seeks straight to ('PAID', ?) and reads forward — every entry it touches is a result row, and the rows even come out ordered by created_at, so an ORDER BY created_at is free.

With (created_at, status) reversed, the engine seeks to the timestamp and must then read every row after that date across all statuses, filtering each one for status — potentially millions of entries examined for thousands returned.

The general rule: columns used with equality first, then exactly one range column; any column after the range column cannot be used for seeking, because within a range the later columns are no longer sorted usefully.

Land it Equality columns narrow the index to one contiguous strip; the range column then walks that strip — that ordering argument is the answer, not the memorized rule.

Likely follow-ups
"What if the query is WHERE status IN ('PAID', 'SHIPPED') AND created_at > ? — does the equality-first rule still hold?"

Mostly. An IN list is a set of equalities, so (status, created_at) still works: the engine does one range scan per status value — seek to ('PAID', ?), read forward, then seek to ('SHIPPED', ?), read forward.

Both engines do this; Postgres calls the result a multi-key index scan and MySQL shows type: range. The cost is one seek per list element, which is fine for a few values and bad for a thousand.

What breaks is the free ordering: rows come out ordered by created_at within each status, not globally, so an ORDER BY created_at now needs a merge or a sort.

If the ORDER BY matters more than the filter, (created_at, status) with a filter may win for recent-first queries with LIMIT. I would test both plans.

"Two range columns: WHERE created_at > ? AND amount > ?. What is the index?"

Only one of them can be seeked; the other is filtered inside the range. I put the more selective one first, meaning the range that eliminates more rows.

If most rows are old and the created_at range keeps only last week's, (created_at, amount) seeks to last week and filters by amount within it; the amount column still helps because it is checked in the index before the row is fetched.

If a typical query is "large amounts in all history", (amount, created_at) is better. There is no index that seeks on both with a btree.

For genuinely two-dimensional ranges, Postgres offers a GiST or BRIN index, or a bitmap AND across two single-column indexes, which the planner will choose if both ranges are selective.

"How much does column order matter if the table is small?"

Almost not at all until it is not small. On a hundred thousand rows, the wrong order means scanning a few thousand extra index entries, which is sub-millisecond, and both indexes seem fine in testing.

That is why the mistake ships: it is invisible at staging scale. At a hundred million rows the same wrong order scans millions of entries per query.

The rule I use is to design the index for the size the table will be in two years, and to test against a prod-sized copy or at least the planner's estimates with representative statistics.

When I cannot, I follow the derivation — equality first, then range, then order or covering columns — because it is correct at every size.

Q61 · Scenario. "Your hottest endpoint runs SELECT id, status, total FROM orders WHERE customer_id = ? ORDER BY created_at DESC LIMIT 10 two thousand times a second. Design the ideal index and justify every column."

Reveal answer

Strong answer I want one index that serves the filter, the sort, and the projection, so the query never touches the table:

  1. customer_id leads, because it is the equality predicate — it takes us to one contiguous strip of the index.
  2. created_at DESC comes second, so within each customer the entries are already in the order the query wants — the engine reads the first 10 entries and stops. No sort, and the LIMIT actually limits work.
  3. Then I make it covering. In Postgres: CREATE INDEX ON orders (customer_id, created_at DESC) INCLUDE (status, total) — INCLUDE stashes columns in the leaf entries without making them part of the sort key, keeping the internal pages lean. id is the primary key; adding it to INCLUDE too makes the index-only scan complete. In MySQL I would write (customer_id, created_at, status, total) — there is no INCLUDE, so trailing columns join the key — and id rides along automatically because every InnoDB secondary index carries the primary key.
  4. Verify: Postgres should show Index Only Scan with near-zero Heap Fetches; MySQL should show type: ref with Using index and no filesort.

The cost side: this index is wider than a bare (customer_id), so every insert and every update of status or total pays for it. At two thousand reads a second, that trade is easy to defend — but I would say the trade out loud.

Land it A great index for a hot query answers filter, order, and projection in one structure — and a senior names the write cost while accepting it.

Likely follow-ups
"Product now wants the same endpoint filtered by status too: WHERE customer_id = ? AND status = 'OPEN' ORDER BY created_at DESC LIMIT 10. Does the index change?"

Yes, the equality on status should move into the key ahead of the sort column: (customer_id, status, created_at DESC), with total included or trailing.

With the old index, the engine seeks to the customer's strip in created_at order and filters status row by row, which for a customer with mostly closed orders can read hundreds of entries to find ten open ones — the LIMIT no longer bounds the work.

With status in the key, the strip is exactly the customer's open orders in date order, and ten entries are read.

If both variants of the query are hot, the new index serves the old query too, since customer_id is still leading, except that the plain query then needs a merge across statuses for the ordering; I would measure and probably keep both.

"What is the actual write cost of that covering index, in numbers?"

Each insert into orders adds one entry of roughly 8 bytes customer_id plus 8 bytes timestamp plus status and total, say 30 bytes, plus the id, and lands in the customer's strip, which is a random position across customers — a cache miss and possibly a split per insert on a large table, so it is not free.

Each update of status or total rewrites the entry: in Postgres that is a new index tuple and a dead one, and it defeats HOT for that row, so every status change costs an index insert in every index on the table plus this one.

At, say, 200 orders per second created and 400 status changes per second, that is 600 index writes per second on this index, which a healthy instance handles easily, and the index adds a few gigabytes over a hundred million orders.

Against two thousand reads per second saved from a sort, it pays.

"Why put id in INCLUDE in Postgres if the index-only scan works without it?"

Because the query projects id, and a Postgres index does not carry the heap tuple's primary key; it carries a physical tuple id, which is not the id column.

So without id in the index the scan must visit the heap to read it, and the plan becomes a plain Index Scan with a heap fetch per row.

Adding INCLUDE (id, status, total) makes every projected column available in the leaf entry, so the plan is a true Index Only Scan and Heap Fetches is near zero once vacuum has set the visibility map.

In MySQL this is automatic, since every secondary index entry carries the primary key. That difference is a common surprise for people moving between the engines.

"How do you verify the improvement in production, not just in a plan?"

Three checks after the concurrent build. The plan from EXPLAIN (ANALYZE, BUFFERS) with a real customer id shows Index Only Scan Backward, Heap Fetches: 0 or near it, and buffers in the single digits.

Then the aggregate: pg_stat_statements for that query fingerprint shows mean and p99 dropping and shared_blks_hit per call collapsing, and pg_stat_user_indexes.idx_scan on the new index climbing at roughly the endpoint's request rate.

Then the service metric: endpoint latency at p99 in the application's dashboards, and the database's CPU and read IOPS, which should fall visibly at two thousand calls per second. And I check the old index's idx_scan stops climbing so it can be dropped.

Q62. "If I have separate single-column indexes on a and on b, is that as good as a composite index for WHERE a = ? AND b = ??"

Reveal answer

Strong answer No, and I would be precise about what actually happens.

The planner usually picks the more selective single index, fetches every row matching that one predicate, and filters the rest — so if a = ? matches 100,000 rows and the combination matches 50, you do 100,000 row fetches for 50 results.

Both engines can sometimes combine the indexes: MySQL's index merge (you see Using intersect(idx_a, idx_b) in Extra) and Postgres's BitmapAnd, which scans each index, builds a bitmap of matching pages, and intersects the bitmaps before touching the table.

That genuinely helps, but it is honest to say it is a fallback: it costs two full index probes plus the combining work, it cannot return rows in index order, and the planner does not always choose it.

A composite (a, b) seeks directly to the 50 rows in one traversal, deterministically.

Land it Index merge is the planner rescuing a schema that was not designed for the query — design the composite for queries you actually care about and let merge cover the long tail.

Likely follow-ups
"When does index merge or BitmapAnd actually win over a composite?"

When the predicate combinations are unpredictable. If queries filter on any two or three of ten columns in different combinations, building a composite for every combination is impossible, and single-column indexes with bitmap combination cover the long tail with one index per column.

It also wins for ad-hoc analytics, where the planner can pick any subset. Postgres's bitmap approach is strong here: it scans each index, builds a bitmap of matching heap pages, ANDs them, and reads the heap in physical order, which is efficient.

What it never gives is index-ordered output or a tight LIMIT, and each extra index in the combination is a full probe. So for the hot, known queries I build composites; for the everything-else surface I keep single-column indexes and let the planner combine.

"How do you read whether merge happened, and how do you turn it off if it is making things worse?"

In MySQL EXPLAIN, type: index_merge with Extra: Using intersect(idx_a, idx_b), Using union(...), or Using sort_union(...); the key column lists both indexes. In Postgres, a BitmapAnd or BitmapOr node above two Bitmap Index Scan nodes, feeding a Bitmap Heap Scan.

If the merge is a bad choice — usually because one index alone would have been selective enough and the second probe is waste — MySQL has the optimizer switch SET optimizer_switch = 'index_merge_intersection=off' per session or globally, or a NO_INDEX_MERGE hint, and Postgres has SET enable_bitmapscan = off for testing, never for production.

The real fix in either case is the composite index for that query.

"Is there a case where two single-column indexes are actually better than the composite for the same query?"

Rarely, and only on cost grounds.

If one of the two predicates is almost always highly selective on its own — a = ? returns five rows — the planner uses just that index, filters b on the five rows, and the composite would save nothing while costing a wider index on every write.

In that situation I would keep the single-column index on a alone and drop the one on b if nothing else uses it. The composite only earns its keep when the leading predicate alone returns many rows and the combination returns few.

That is a data-distribution question, so I check the actual row counts in the plan before adding it.

Q63. "You find indexes on (a) and on (a, b) on the same table. Is one redundant, and what does keeping it actually cost?"

Reveal answer

Strong answer (a) is redundant, because (a, b) is sorted by a first — any query that could seek on (a) can seek on the leading column of (a, b) just as well.

The reverse is not true: (b) or (b, a) would not be made redundant, since b is not a leading prefix.

The cost of keeping the extra index is paid on every write: each INSERT must add an entry to every index on the table; an UPDATE that changes an indexed column deletes the old entry and inserts the new one in each affected index; and every one of those changes is also recorded in the WAL — the write-ahead log, the sequential journal the database writes before touching data pages, which is also what ships to replicas.

More indexes also mean more pages competing for the buffer pool. The one caveat before dropping: if (a) backs a unique constraint, or is dramatically smaller and serves a scan-heavy query where index size matters, keep it deliberately.

Land it An index is a standing tax on every write and every byte of cache — a prefix-redundant one pays the tax and buys nothing.

Likely follow-ups
"Is (a, b) also redundant if there is a (a, b, c) index?"

Yes, by the same prefix rule: (a, b, c) is sorted by a then b, so every seek that (a, b) serves, the wider index serves too. The reservations are the same as before.

If (a, b) is unique, it enforces a constraint that (a, b, c) does not, and it stays.

If (a, b) is dramatically narrower — say c is a wide text column — a query that scans a large range of a reads fewer pages from the narrow index, and on a hot query that can matter.

And for covering: a query projecting only a and b is index-only under both. So the decision is "drop unless unique or measurably narrower on a hot scan", and the usage counters decide the last part.

"What is the write cost of one extra index, concretely?"

Per insert: one extra btree insert, which is a page read, possibly from disk if the target page is cold, a page modification, and a log record; on a random-key index that is a cache miss per row.

Per update of an indexed column: an entry delete and insert, so two of the above, and in Postgres it also blocks the HOT optimisation for that row, so every index on the table is written, not just this one.

Per delete: an entry removal, deferred to purge or vacuum. In benchmarks, going from one to six secondary indexes on an InnoDB table roughly halves insert throughput, and each further index costs a few percent.

Then there is the doubled replication traffic in Postgres, where index changes are WAL-logged, and the buffer pool space the index occupies.

"How do you find prefix-redundant indexes across a whole database?"

In Postgres, a catalog query over pg_index comparing the indkey arrays: two indexes on the same table where one's column list is a leading prefix of the other's and the shorter one is not unique.

The community's "duplicate indexes" query from the Postgres wiki does exactly this and also finds exact duplicates.

In MySQL, pt-duplicate-key-checker from Percona Toolkit scans every table and reports prefix and exact duplicates with the DROP statements ready, and it also knows that InnoDB secondary indexes implicitly end with the primary key, so (a, id) is a duplicate of (a).

I run one of these quarterly and after any big schema change, and I cross-check the output against usage counters before dropping.

Q64 · Scenario. "A table uses soft deletes and 90% of its 100 million rows have deleted = true. Every query filters WHERE deleted = false, and the indexes are huge. What is your move?"

Reveal answer

Strong answer In Postgres this is the textbook case for a partial index — an index built only over rows matching a predicate:

  1. CREATE INDEX idx_orders_live ON orders (customer_id) WHERE deleted = false; — the index contains only the 10 million live rows, so it is a tenth the size, its depth may drop a level, far more of it fits in cache, and writes to already-deleted rows never touch it.
  2. The catch: the planner uses it only when the query's WHERE provably implies the index predicate — so every query must actually say deleted = false. An ORM that sometimes forgets the filter silently falls off the index; I would centralize the predicate in one place in the data layer.
  3. MySQL has no partial indexes, so I would name the honest alternatives: move dead rows to an archive table on a schedule, so the main table stays small — usually the right long-term answer anyway; or include deleted as the leading index column, which at least clusters live entries together but still stores all the dead ones.
  4. Either way, I would question the retention story: 90 million tombstones in a hot operational table is a lifecycle problem wearing an indexing costume.

Land it Partial indexes let Postgres index the 10% you query instead of the 100% you store — and when the engine lacks them, archiving beats indexing around the corpse pile.

Likely follow-ups
"The ORM does not always add deleted = false. Concretely, how do you make the partial index safe?"

Put the predicate in one place the ORM cannot skip. In Hibernate that is @SQLRestriction("deleted = false") on the entity, which appends the predicate to every generated query for that entity, including collection loads.

For native queries and other clients, a view live_orders AS SELECT * FROM orders WHERE deleted = false that all reads go through.

Then I verify with pg_stat_statements: any query on orders whose text lacks the predicate is a candidate for a full scan, and pg_stat_user_indexes shows the partial index's scan count growing at the expected rate.

I would also keep a plain index on the most critical column for the first weeks as a safety net, and drop it once the counters prove every hot query hits the partial one.

"Archiving on MySQL: how do you move 90 million rows out without the same outage as a big delete?"

In chunks, with a copy-then-delete loop keyed on the primary key. Each iteration: INSERT INTO orders_archive SELECT * FROM orders WHERE deleted = 1 AND id BETWEEN ? AND ?, then DELETE FROM orders WHERE deleted = 1 AND id BETWEEN ? AND ?, commit, sleep a hundred milliseconds, advance the range by ten thousand.

pt-archiver automates this with throttling on replica lag. Once the table holds only live rows, OPTIMIZE TABLE or an online rebuild reclaims the space and compacts the indexes, which is where the actual read benefit appears, since a delete alone leaves the pages allocated.

The application needs a read path to the archive for the rare "show me a deleted order" case, usually a UNION behind a feature flag.

"When would a partial index be the wrong choice even on Postgres?"

When the predicate is not stable or not selective. If rows flip between deleted true and false frequently, every flip is an index insert or delete plus a dead entry, and the index churns.

If the live fraction is 60 percent rather than 10, the size saving is small and the planner's extra constraint is not worth the fragility. If queries sometimes need deleted rows too, they need a second full index anyway, doubling the write cost.

And if the predicate involves a parameter, like WHERE tenant_id = 42, a partial index per tenant does not scale. The sweet spot is a small, stable, always-filtered subset: unpublished rows, pending jobs, live records in a mostly-dead table, or rows with a non-null optional column.

"What is the leading-column alternative in MySQL, and why is it worse?"

The alternative is (deleted, customer_id), so that all live entries sit together in the deleted = 0 strip and a query with deleted = 0 AND customer_id = ? seeks straight into it.

It works, and the live strip is one-tenth of the index, so the hot part stays cached.

It is worse because the index still stores all 90 million dead entries, so it is ten times larger on disk, every write to a dead row still maintains it, and its depth is that of the full index.

Also, a leading column with two values makes the index useless for any query that does not specify deleted. It is a reasonable stopgap while the archiving job is built, not a destination.

Q65. "Users log in with any casing of their email, so you query WHERE lower(email) = ?. How do you index that?"

Reveal answer

Strong answer A plain index on email is useless here, because the index stores raw values sorted as-is, and the query asks about a computed value.

The fix is an expression index — an index built over the result of an expression: in Postgres, CREATE INDEX ON users (lower(email)); in MySQL 8.0.13+, CREATE INDEX ON users ((lower(email))) — note the doubled parentheses — or on older MySQL, a generated column that stores lower(email) with an ordinary index on it.

The critical discipline is that the query must use the exact same expression: lower(email) = lower(?) matches, LCASE(email) or an added trim() does not, and the index is silently ignored.

Two footnotes worth saying: Postgres keeps separate statistics for expression indexes, populated by ANALYZE, so estimates improve after the first analyze; and the cleaner long-term fix is often normalizing the data itself — store the lowercased email at write time, or use Postgres's citext case-insensitive type.

Land it The index must be built on exactly what the query compares — match the expression character for character, or normalize at write time and stop needing the trick.

Likely follow-ups
"Compare citext, a case-insensitive collation, and the expression index — which do you ship?"

For a new Postgres schema, a case-insensitive collation or normalisation at write time; for an existing one, the expression index.

citext works but is an extension type with quirks: comparisons lowercase both sides on every operation, it does not support pattern operators efficiently, and some drivers map it awkwardly.

Postgres 12+ supports non-deterministic ICU collations, CREATE COLLATION ci (provider = icu, locale = 'und-u-ks-level2', deterministic = false), which make = case-insensitive and let a plain index serve equality, but they disable LIKE and pattern matching on that column.

Normalising at write time — store lower(email), and validate — is the simplest: one plain unique index, no tricks, and every query stays ordinary. In MySQL, the default collations are already case-insensitive, so the question rarely arises there.

"The expression index exists, but the plan still shows a sequential scan. What are the causes?"

Four common ones. The query's expression differs from the index's — LOWER(email) versus lower(email) is fine, but lower(trim(email)) or email ILIKE ? is not the same expression.

The parameter side is cast differently, so the comparison is lower(email)::text = ?::varchar and the planner cannot match the operator class; binding as the right type fixes that.

The function is not marked IMMUTABLE, which lower is, but a custom function must be, or the index cannot even be created. And statistics: right after creation, Postgres has no statistics for the expression until ANALYZE runs, so it may estimate poorly and choose a scan.

EXPLAIN on the exact query with the exact bind types answers which it is.

"MySQL 8.0.13 functional indexes — what are the limitations?"

They are implemented as hidden virtual generated columns with an ordinary index on them, which explains the rules. The expression must be deterministic and cannot reference subqueries, parameters, variables, or nondeterministic functions. It cannot be used as a primary key.

The query must contain the identical expression so the optimizer can substitute the generated column; unlike Postgres, it will not do algebraic matching.

Prefix lengths on the expression are not allowed directly, so indexing the first sixty characters of an expression requires an explicit generated column with a prefix index. And because the hidden column exists, SHOW CREATE TABLE and some tools display it oddly.

For an older MySQL, or when I want control, I create the generated column explicitly and index that.

Q66 · Scenario. "You need to index a VARCHAR(2048) URL column in MySQL for exact lookups, and CREATE INDEX fails complaining about key length. What are your options?"

Reveal answer

Strong answer InnoDB caps an index key at 3,072 bytes, and with a 4-bytes-per-character charset like utf8mb4, a VARCHAR(2048) can need 8,192 — hence the failure. Options in the order I would consider them:

  1. A prefix index: CREATE INDEX idx_url ON pages (url(64)) indexes only the first 64 characters. Before choosing the length I would measure selectivity — SELECT COUNT(DISTINCT LEFT(url, 64)) / COUNT(*) — and grow the prefix until that ratio approaches 1. Limitations to state honestly: a prefix index can never be covering, and it cannot fully serve ORDER BY url or GROUP BY url, because the index does not contain the whole value — the engine must fetch rows to compare full strings.
  2. Usually better for exact-match lookups: a hash column. Add a generated column such as url_sha1 BINARY(20) AS (UNHEX(SHA1(url))) STORED, index that, and query WHERE url_sha1 = UNHEX(SHA1(?)) AND url = ? — the second predicate guards against hash collisions. The index entries are a fixed 20 bytes regardless of URL length.
  3. In Postgres the analogous wall is a btree entry limit of about 2,700 bytes (a third of a page); the same tricks apply — an expression index on md5(url), or a hash index, which handles equality on long keys natively.

Land it Prefix indexes trade coverage for fit and only work if the prefix is selective — for pure equality on long strings, indexing a fixed-length hash is the cleaner engineering.

Likely follow-ups
"Why 3,072 bytes, and what are the other limits I might hit?"

The 3,072-byte limit applies to InnoDB with the DYNAMIC or COMPRESSED row formats, which are the defaults in 5.7 and 8.0, and comes from the requirement that an index key fit comfortably in a 16 kilobyte page with room for multiple entries.

Under the older COMPACT row format the limit is 767 bytes, which is why upgrading old tables sometimes fixes the error. With utf8mb4 at four bytes per character, 3,072 bytes means at most 768 characters.

Other limits: a maximum of 16 columns per index, and a total row size limit of about 65,535 bytes.

In Postgres, the corresponding wall is that a btree entry cannot exceed about one-third of a page, around 2,704 bytes, which gives the "index row size exceeds maximum" error.

"How do you choose the prefix length so the prefix index is actually selective?"

Measure the distinct ratio at increasing lengths against the full column. SELECT COUNT(DISTINCT LEFT(url, 32)) / COUNT(*), COUNT(DISTINCT LEFT(url, 64)) / COUNT(*), COUNT(DISTINCT url) / COUNT(*) FROM pages. Pick the shortest length whose ratio is within a percent or two of the full-column ratio.

URLs are a bad case because they share long prefixes like https://www.example.com/products/, so the selective part starts late and the required prefix can be a hundred characters or more; that is exactly when the hash-column approach wins.

I would also check the worst case: the most common prefix value's row count, since a lookup for a URL sharing a popular prefix must fetch and compare every row in that prefix group.

"Why keep AND url = ? after the hash comparison?"

Because a hash can collide: two different URLs can produce the same SHA-1 or MD5, and the index lookup alone would return both.

The second predicate compares the full string on the small set of rows the hash returned, which is a cheap check after a tight seek, and it guarantees exactness.

SHA-1 collisions are astronomically unlikely by chance, but adversarial inputs can be constructed, and a lookup must not return the wrong row.

The pattern also protects against implementation drift: if the hash is ever computed differently on write than on read, the full-string check fails loudly instead of returning a wrong row. In Postgres the same holds for an expression index on md5(url): WHERE md5(url) = md5(?) AND url = ?.

Q67. "A query does ORDER BY created_at ASC, priority DESC. Can a normal index on (created_at, priority) serve that sort?"

Reveal answer

Strong answer Not the mixed version. An all-ascending index (created_at, priority) can serve ASC, ASC by scanning forward and DESC, DESC by scanning the same index backward — reversing the walk reverses both columns together.

But ASC, DESC is a different physical ordering: within each created_at, the entries would need to run high-to-low on priority, and no direction of walking an all-ascending index produces that, so the engine falls back to an explicit sort.

The fix is to declare the direction in the index itself: CREATE INDEX ON tasks (created_at ASC, priority DESC). Postgres has always supported per-column direction (plus NULLS FIRST/LAST).

MySQL supports real descending index columns only since 8.0 — MySQL 5.7 accepted the DESC keyword in DDL and silently ignored it, which is a classic trap worth naming.

Land it An index serves a sort only if some single scan direction yields exactly the requested order — mixed directions must be baked into the index definition.

Likely follow-ups
"How would you confirm MySQL is really using the descending column and not silently ignoring it?"

Two places.

SHOW CREATE TABLE or SHOW INDEX: in 8.0 the Collation column of SHOW INDEX shows D for a descending column, whereas in 5.7 it always shows A even if the DDL said DESC. Then the plan: EXPLAIN for ORDER BY created_at ASC, priority DESC should show the index in key and no Using filesort in Extra.

If filesort is present, the index is not serving the sort. Also worth knowing: a query with the exact reverse ordering, created_at DESC, priority ASC, is served by the same index scanned backward, and MySQL 8.0 shows Backward index scan in Extra for that case. Postgres shows Index Scan Backward similarly.

"The sort is served, but the query also filters WHERE status = 'open'. Does the index still work?"

Not efficiently.

The index (created_at ASC, priority DESC) yields rows in the requested order, but with no leading equality column the engine must scan from the beginning and filter every entry on status until it collects enough rows for the LIMIT, which for a rare status could be the whole index.

The right index is (status, created_at ASC, priority DESC): equality first, then the sort columns in their exact directions. Then the engine seeks to the status strip and reads it in order.

This is the same equality-then-order principle from the composite index discussion, with the added rule that the direction of each sort column is part of the definition.

"What about NULLS FIRST or NULLS LAST — can they break index use in Postgres?"

Yes.

Postgres btrees store nulls at one end, and the index's null ordering is part of its definition; the default for ASC is NULLS LAST and for DESC is NULLS FIRST. A query asking ORDER BY created_at ASC NULLS FIRST on a default ASC index does not match, and the planner sorts.

The fix is to declare it: CREATE INDEX ON tasks (created_at ASC NULLS FIRST, priority DESC).

The subtle version is backward scans: an index (a ASC NULLS LAST) scanned backward yields a DESC NULLS FIRST, which is Postgres's default for DESC, so the common pairs line up, but any mixed request needs the exact combination.

MySQL has no null-ordering syntax; nulls sort first in ASC, and there is no way to change it in the index.

Q68 · Scenario. "You put a unique index on a nullable external_ref column, yet the table now holds thousands of rows where it is NULL. Is the index broken — and how do the engines differ here?"

Reveal answer

Strong answer The index is working as specified. In SQL, NULL means "unknown", and one unknown is never equal to another unknown — NULL = NULL is not true. A unique index rejects equal values, so any number of NULLs coexist. Both Postgres and MySQL's InnoDB behave this way by default, and it is frequently what you want: "unique when present". If I need at most one NULL, the options differ by engine:

  1. Postgres 15+ supports it directly: CREATE UNIQUE INDEX ... ON t (external_ref) NULLS NOT DISTINCT — declaring that NULLs count as duplicates of each other. Before 15, the idiom was a partial unique index plus a second partial index tricking uniqueness of NULL, or simply a NOT NULL redesign.
  2. MySQL has no equivalent clause. The realistic options are making the column NOT NULL with an explicit sentinel design, or enforcing the rule in the application within a transaction — and I would say out loud that application-level uniqueness is race-prone without a locking strategy.
  3. Worth adding: in Postgres a UNIQUE constraint is implemented by a unique index underneath — the constraint is the declared rule, the index is its enforcement machinery — so this NULL behavior applies to both forms.

Land it Unique indexes deduplicate equality, and NULL never equals NULL — if your invariant is "at most one missing value", you must say so explicitly, and only Postgres 15+ lets you say it in DDL.

Likely follow-ups
"Show me the pre-15 Postgres idiom for 'at most one NULL' and explain why it works."

Two partial indexes. The first is the normal one, CREATE UNIQUE INDEX ux_ref ON t (external_ref) WHERE external_ref IS NOT NULL, which enforces uniqueness among present values.

The second is CREATE UNIQUE INDEX ux_ref_null ON t ((true)) WHERE external_ref IS NULL, a unique index on a constant expression restricted to rows where the column is null. Every such row indexes the same value, true, so the second row with a null violates uniqueness.

Alternatively, COALESCE(external_ref, '') in a unique expression index treats all nulls as the empty string, which then can appear at most once, provided the empty string is not a legitimate value. Both are tricks; the Postgres 15 NULLS NOT DISTINCT clause is the readable version.

"On MySQL, how do you enforce it without relying on application code?"

With a generated column that turns "null" into a unique-able value.

Add ref_key VARCHAR(64) AS (IF(external_ref IS NULL, 'NULL', external_ref)) STORED with a unique index on it — if the column has no legitimate value 'NULL', all null rows collide on that sentinel and the second is rejected with error 1062.

A cleaner variant uses a second generated column that is 1 when the ref is null and NULL otherwise, with a unique index on that column alone: null_marker TINYINT AS (IF(external_ref IS NULL, 1, NULL)).

Because NULLs are distinct in the unique index, non-null-ref rows never collide, and null-ref rows all collide on 1. That makes it a database-enforced rule with no race, which the application-level check cannot be.

"Does NULL in a composite unique index behave the same way?"

Yes, and it bites harder. A unique index on (tenant_id, external_ref) allows unlimited rows with the same tenant_id and a null external_ref, because any row containing a null in the key is distinct from every other. People often expect that "tenant plus null" is one combination.

And in InnoDB, older versions of the BDB and MyISAM engines had different behaviour, so legacy documentation may contradict it.

If the rule is "one null per tenant", Postgres 15+ handles it with NULLS NOT DISTINCT, and MySQL needs the generated-column trick per tenant, (tenant_id, COALESCE-style marker).

The more robust design is usually to make the column NOT NULL with a real value, if the domain allows it.

Drill · The planner & reading real plans

These questions test whether you can think like the query planner — predict when it will ignore your index, and read its actual output line by line when it does something surprising.

Q69. "There is an index on status, which has three values, and the planner ignores it. Why — and where is the tipping point?"

Reveal answer

The real test Selectivity explained through I/O cost, not as a slogan.

Strong answer Two words matter here. Cardinality is how many distinct values a column has — three, for this status. Selectivity is what fraction of the rows a predicate matches — with three roughly even values, status = ? matches about a third of the table.

The planner ignores the index because of how the two access paths pay for I/O. A sequential scan reads pages in physical order, which disks and caches love — read-ahead streams them in.

An index scan on a non-clustered index fetches rows one by one, and each fetch can land on a different table page — a random read.

If the query matches 33% of a table with 100 rows per page, nearly every page contains matches anyway, so the index adds work without skipping anything.

The break-even is far lower than people expect: as a rule of thumb, once a predicate matches more than a few percent of the rows — low single digits for truly random row order — the full scan wins.

The nuance a senior adds: with skewed data, status = 'FAILED' at 0.1% is absolutely worth indexing even though the column has three values, and both engines keep value-frequency histograms so the planner can tell the popular value from the rare one.

Land it Indexes are for skipping most of the table; when the predicate keeps a third of it, sequential I/O beats a million random hops — selectivity of the predicate, not existence of the index, decides.

Likely follow-ups
"How does the planner know FAILED is rare when the column has three values?"

From the most-common-values statistics. Postgres's ANALYZE samples the table and stores, per column, the list of the most frequent values and their frequencies in pg_stats.most_common_vals and most_common_freqs, plus a histogram for the rest.

For status = 'FAILED' it looks up FAILED in that list, finds 0.1 percent, and estimates rows accordingly, choosing the index; for 'DONE' at 80 percent it chooses a scan. MySQL 8.0 has the same in histograms created with ANALYZE TABLE ... UPDATE HISTOGRAM ON status; without an explicit histogram, InnoDB only knows the cardinality, three, and assumes even distribution, so it may estimate a third of the table for FAILED and skip the index.

That is one of the most common reasons MySQL under-uses indexes on skewed columns.

"What happens with a bound parameter, where the planner does not know the value?"

It has to guess with the average.

In Postgres, a generic plan built for status = $1 uses the average selectivity across values, one-third here, and picks a sequential scan — wrong for FAILED. Custom plans, used for the first five executions and whenever they are estimated cheaper, see the actual value; the switch to a generic plan after five runs is the classic "fast then slow" incident.

plan_cache_mode = force_custom_plan keeps value-specific plans. MySQL re-plans prepared statements each execution with the real value, so it does not have this problem, but without a histogram it has the even-distribution problem.

In both, the robust fix for a skewed column is a partial index on the rare value in Postgres, or querying the rare value in a way that makes its selectivity obvious.

"Is the tipping point different for InnoDB because of the clustered index?"

The principle is identical but the numbers shift. In InnoDB a secondary index lookup costs two tree traversals, and the row fetch from the clustered index is a random page read unless the rows happen to be in primary-key order correlated with the predicate.

So random-fetch cost per row is similar to Postgres's heap fetch, and the break-even sits in the same low single-digit percent range.

What differs is correlation: if the matched rows are clustered by primary key — say all FAILED orders are recent and ids are increasing — then fetches hit consecutive clustered-index pages and the index path stays cheap even at ten percent.

Postgres captures this in pg_stats.correlation; MySQL's optimizer has no equivalent statistic and relies on fixed cost constants.

"How would you force the issue and prove the planner is right, rather than argue?"

Run both plans and time them. In Postgres, SET enable_seqscan = off in a session forces the index path, then EXPLAIN (ANALYZE, BUFFERS) both ways, and compare actual time and buffers read. In MySQL, FORCE INDEX (idx_status) in a test session does the same.

If the forced index plan is slower on the common value, the planner was right, and the discussion ends with data.

If it is faster, the estimates are wrong: stale statistics, a missing histogram, or a cost setting like random_page_cost still at the spinning-disk default of 4 on an SSD system, which biases against index scans.

Adjusting random_page_cost to around 1.1 on SSDs is often the actual fix.

Q70 · Scenario. "A query that ran in 10 ms yesterday is sequential-scanning today. Last night a batch job loaded 40 million rows into the table. Walk me through it."

Reveal answer

Strong answer My hypothesis is stale statistics — the sampled summary of each table (row count, distinct values, common values, value distribution) that the planner uses to estimate costs. It chooses plans from those estimates, not from the actual data.

  1. Confirm: run EXPLAIN ANALYZE and compare estimated rows to actual rows. After a 40-million-row load with old statistics, estimates are typically off by orders of magnitude — that mismatch is the smoking gun.
  2. Check when statistics were last refreshed. Postgres: SELECT last_analyze, last_autoanalyze FROM pg_stat_user_tables WHERE relname = 'orders'. Autoanalyze triggers after roughly 10% of a table changes (autovacuum_analyze_scale_factor), but on a huge table 10% is a lot of rows, and after a bulk load it may not have fired yet — or is still grinding.
  3. Fix now: run ANALYZE orders; manually — it samples the table and takes seconds even on large tables. In MySQL: ANALYZE TABLE orders; InnoDB keeps persistent statistics and auto-recalculates after about 10% of rows change, but the recalculation is sample-based and can also be triggered manually.
  4. Verify the plan flipped back, then prevent: make bulk-load jobs end with an explicit ANALYZE, and on Postgres consider lowering the autoanalyze scale factor for very large, frequently-loaded tables so "10% of huge" stops being the trigger.

Land it The planner is only as smart as its statistics — any pipeline that changes a table's size or shape wholesale should refresh them as its final step.

Likely follow-ups
"You ran ANALYZE and the plan is still a sequential scan. What next?"

Then the statistics may be right and the data changed shape. Forty million new rows can change selectivity: if the loaded rows all share a status value that used to be rare, the predicate now matches a large fraction and the scan is correct.

I would check the estimated versus actual rows in EXPLAIN ANALYZE again; if they now agree and the row count is large, the query needs a different index or a rewrite, not a statistics fix.

If they still disagree, the default sample may be too small for the new distribution: ALTER TABLE orders ALTER COLUMN status SET STATISTICS 1000 and re-analyse.

Also check the query uses a bound parameter with a generic plan, and check pg_class.reltuples and relpages updated, since a load can also leave the visibility map cold, making index-only scans look expensive.

"How long does ANALYZE take on a huge table, and does it block anything?"

Seconds to a minute, because it samples rather than scans: Postgres reads 300 times default_statistics_target rows, 30,000 by default, chosen from random pages, so it touches a fixed number of pages regardless of table size.

It takes a SHARE UPDATE EXCLUSIVE lock, which blocks only DDL and other vacuum or analyze on that table, never reads or writes.

MySQL's ANALYZE TABLE samples innodb_stats_persistent_sample_pages, default 20 pages per index, so it is also quick, but it does take a brief metadata lock, and on a table with a long-running query it can queue behind that and then block subsequent queries — the same metadata-lock trap as DDL.

So on MySQL I check for long transactions on that table before running it.

"Why did autoanalyze not fire, and how do you make bulk loads trigger it?"

Because the trigger is proportional: autovacuum_analyze_scale_factor of 0.1 times the table's row count plus autovacuum_analyze_threshold of 50.

On a 400-million-row table that is forty million changed rows, which the load just barely reached, and then autoanalyze had to wait for a worker slot and run, so it may have been mid-way when the day started.

To make loads self-healing: end every bulk job with an explicit ANALYZE, which is the reliable fix; and set per-table autovacuum_analyze_scale_factor = 0.01 or lower for very large tables so ten percent of huge stops being the bar.

On MySQL, innodb_stats_auto_recalc triggers after ten percent of rows change too, and the same explicit ANALYZE TABLE at the end of the job applies.

"Could the plan flip be caused by something other than statistics after a load?"

Yes. The load could have evicted the working set from the buffer pool, so the same index plan is now doing disk reads and just looks slow rather than having changed — BUFFERS output distinguishes that.

The load could have bloated the index in Postgres if it was an update-heavy load, making the index scan genuinely more expensive.

The visibility map is cleared for every page the load touched, so an index-only scan now does heap fetches for all of them until vacuum runs. And on MySQL, innodb_stats_persistent off means statistics were recalculated at an unlucky moment from a random sample.

So my checklist after "it was fast yesterday" is: estimates, buffers, bloat, visibility map, and only then the query itself.

Q71 · Scenario. "In MySQL, WHERE phone = 9876543210 on an indexed VARCHAR column does a full scan, but WHERE phone = '9876543210' uses the index. Explain, and tell me what you would fix in the Java code."

Reveal answer

Strong answer This is an implicit type cast killing the index. When MySQL compares a string column to a numeric literal, its coercion rules convert the column to a number, not the literal to a string.

A function applied to the column — even an invisible one — means the index, which stores raw string values in string order, cannot be used to seek, so every row is scanned and cast.

It is worse than slow: numeric coercion can produce wrong matches, since '09876543210' and ' 9876543210 ' both coerce to the same number.

  1. Immediate fix: quote the literal so the comparison is string-to-string.
  2. The real fix is in the Java layer: someone is calling setLong() on a PreparedStatement parameter for a VARCHAR column, or the ORM entity maps the field as Long. Bind it with setString() — parameter types must match column types.
  3. Postgres behaves differently and more safely: there is no implicit cast between varchar and integer, so phone = 9876543210 fails outright with "operator does not exist". You hit the subtler Postgres version through JDBC when the driver sends a parameter with the wrong declared type — the plan then casts the column and the index goes unused, silently.
  4. Prevention: a review rule that bind-parameter Java types mirror column types, and a periodic sweep of the slow-query log for full scans on indexed columns — type mismatch is one of its classic causes.

Land it Whichever side of the comparison gets converted loses its index — and MySQL converts the column, so one unquoted literal or one wrong setLong turns an indexed lookup into a full scan.

Likely follow-ups
"Show me the Postgres JDBC version of this problem and how you would catch it."

In Postgres the driver sends parameters with a declared type.

If the code calls setObject(1, someLong) or the ORM maps a VARCHAR column to a Long field, the parameter arrives as int8, and Postgres either errors with "operator does not exist: character varying = bigint" or, if an implicit cast path exists, casts the column side and skips the index.

A subtler one is setTimestamp against a timestamptz column, which makes the driver send timestamp and forces a per-row cast.

I catch it with auto_explain logging plans for slow statements, looking for a Filter with a cast around a column name, and with log_min_duration_statement capturing the bound parameter types. In tests, a Hibernate schema validation with hibernate.hbm2ddl.auto=validate fails on type mismatches between entity and column.

"Why is the wrong-match problem worse than the performance problem?"

Because it returns the wrong customer. MySQL converts both sides to DOUBLE for a string-versus-number comparison. Strings that are not valid numbers convert to zero, so WHERE phone = 0 matches every row with a non-numeric phone. Leading zeros vanish, so '09876543210' equals 9876543210.

Whitespace is trimmed. And beyond about fifteen significant digits, DOUBLE loses precision, so two long numeric strings that differ in the last digit compare equal. A lookup by account number or phone that returns another customer's record is a data leak, not a slow query.

That is the argument I use to get the fix prioritised, and it is why I treat implicit conversion warnings in the MySQL log as correctness bugs.

"What review or tooling rule prevents this class of bug?"

Three layers. In code review, the rule that every bind parameter's Java type mirrors the column type, checked against the entity mapping; for JPA that means the field type is String for VARCHAR and the annotation carries an explicit columnDefinition where the type is unusual.

In the build, hbm2ddl.auto=validate against a real database schema so type mismatches fail the deploy.

In production, the MySQL slow query log with log_queries_not_using_indexes on, digested weekly with pt-query-digest, which lists full scans on tables that have indexes; a full scan on a WHERE that names an indexed column is almost always a type or expression mismatch. Postgres gets the same from auto_explain with auto_explain.log_min_duration.

"Does MySQL ever convert the literal instead of the column?"

Only in the rare cases the rules say so. The relevant rule is that when comparing a string column with a numeric literal, both are compared as numbers, which in effect converts the column.

When comparing a numeric column with a string literal, WHERE id = '42', the literal is converted to a number and the index on id works fine — that is the harmless direction.

Dates behave differently: comparing a DATE column with a string literal converts the literal to a date and uses the index. So the trap is specifically the string column with a numeric literal.

MySQL 8.0 logs a warning for these implicit conversions when they might affect index use, visible with SHOW WARNINGS after the query and in the optimizer trace.

Q72. "Why does WHERE DATE(created_at) = '2026-08-23' ignore the index on created_at, and what do you write instead?"

Reveal answer

Strong answer The index stores raw created_at values in timestamp order. The predicate asks about DATE(created_at) — a value computed from each row — and the index knows nothing about computed values, so the engine must evaluate the function on every row: a full scan.

The fix is to rewrite the predicate so the bare column stands alone on one side — the property people call sargable, meaning "a form the index can seek on".

A day equality becomes a half-open range: WHERE created_at >= '2026-08-23' AND created_at < '2026-08-24', which the index serves as a simple range scan and which is also correct across timestamp precision and time zones in a way BETWEEN with 23:59:59 is not.

The same disease appears as YEAR(created_at) = 2026, created_at + INTERVAL 1 DAY > now(), or arithmetic on the column.

If the function truly cannot be moved off the column, an expression index on the function is the fallback — but the range rewrite is almost always available and costs nothing.

Land it Move the computation to the constant side and leave the column naked — the index can only seek on values it actually stores.

Likely follow-ups
"Why is the half-open range better than BETWEEN with '23:59:59'?"

Because BETWEEN is inclusive at both ends and timestamps have sub-second precision. BETWEEN '2026-08-23 00:00:00' AND '2026-08-23 23:59:59' misses every row in the last second of the day, from 23:59:59.000001 to 23:59:59.999999, silently. Adding microseconds to the literal is fragile and depends on the column's precision.

The half-open form >= '2026-08-23' AND < '2026-08-24' includes everything up to but excluding midnight, at any precision, with no magic constants. It also composes for any interval: a month is >= '2026-08-01' AND < '2026-09-01' with no need to know the month's length.

And it is time-zone safe when the boundaries are computed in the application's zone and passed as timestamptz values.

"The date arrives from the application as a LocalDate. What is the exact JDBC code?"

Compute both bounds in Java and bind them as timestamps. LocalDate day = ...; ZoneId zone = ZoneId.of("Asia/Kolkata"); Instant from = day.atStartOfDay(zone).toInstant(); Instant to = day.plusDays(1).atStartOfDay(zone).toInstant(); then ps.setObject(1, OffsetDateTime.ofInstant(from, zone)) and the same for the second parameter against WHERE created_at >= ? AND created_at < ?.

Binding OffsetDateTime makes the Postgres driver send timestamptz, which matches a timestamptz column without a cast; for a timestamp without time zone column bind LocalDateTime instead.

The point is that all date arithmetic, including the time zone decision, happens once in the application, and the database sees plain comparable values it can seek on.

"When is an expression index on DATE(created_at) the right answer anyway?"

When many queries group or filter by the calendar date in a way a range cannot express: GROUP BY DATE(created_at) over a wide period, or a join on date to a calendar table, or a unique constraint of "one row per user per day".

In those cases CREATE INDEX ON events ((created_at::date)) in Postgres, or a generated column in MySQL, gives a sorted date key the planner can use for grouping and equality.

The caveat is time zones: timestamptz::date depends on the session's TimeZone setting, so it is not immutable and Postgres refuses to index it; the expression must be (created_at AT TIME ZONE 'Asia/Kolkata')::date, which pins the zone. And the query must use that identical expression.

Q73 · Scenario. "The product search box runs WHERE name LIKE '%shoe%' and it is crawling at 20 million rows. The team wants to 'add an index'. What do you actually do?"

Reveal answer

Strong answer First I would explain why no ordinary index can help: a B+tree sorts strings left to right, so it can seek to everything starting with "shoe", but a pattern with a leading wildcard matches strings whose relevant part is anywhere inside — those rows are scattered across the whole sorted order, and there is no place to seek to. Then the real options:

  1. Postgres: the pg_trgm extension with a GIN index — a Generalized Inverted Index, which maps each token to the list of rows containing it, here each three-character fragment ("trigram") of the text. CREATE EXTENSION pg_trgm; CREATE INDEX ON products USING gin (name gin_trgm_ops); — after that, LIKE '%shoe%' and even similarity search use the index. This is the one-liner that genuinely solves substring search in Postgres.
  2. If the need is word search rather than raw substrings, full-text search — tsvector in Postgres, or MySQL's FULLTEXT index with MATCH ... AGAINST — is a better semantic fit. Be honest that MySQL FULLTEXT is word-based: it will find "shoe" as a word but not inside "snowshoeing" unless you configure the ngram parser.
  3. MySQL has no trigram equivalent built in, so for serious substring or fuzzy search on MySQL the honest recommendation is a search engine alongside — Elasticsearch or OpenSearch — fed from the table, accepting the sync complexity.
  4. Trade-offs to state: GIN indexes are large and make writes slower, so I would put them only on the searched columns.

Land it A leading wildcard defeats sorted indexes by definition — the answer is a different index family (trigram or full-text), not a bigger B+tree.

Likely follow-ups
"How does a trigram index actually find '%shoe%'? Walk through it."

At index build, each product name is broken into overlapping three-character pieces, with padding at the ends, so "shoes" gives " s", " sh", "sho", "hoe", "oes", "es ". The GIN index maps each trigram to the list of rows containing it.

At query time, "shoe" is broken into "sho" and "hoe" — no padding, since the wildcard means it can appear anywhere — and the index returns the rows that contain both trigrams, which is the intersection of two posting lists.

Those candidates are then rechecked against the actual LIKE, since having both trigrams does not guarantee they are adjacent. That recheck shows in the plan as Rows Removed by Index Recheck.

Short search strings under three characters produce no trigrams and fall back to a scan, which is a limitation to state.

"GIN indexes and write cost — what is the pending list, and what do you tune?"

A GIN insert must update one posting list per trigram, which for a fifty-character name is around fifty index updates per row.

To make that bearable, GIN buffers new entries in a pending list appended sequentially, and merges it into the main structure when it exceeds gin_pending_list_limit, default four megabytes, or at vacuum.

The trade is that queries must scan the pending list too, so a large pending list slows searches, and the merge itself is a burst of work.

For search-heavy tables I set fastupdate = off on the index so writes pay immediately and reads stay flat, or keep it on with a smaller limit and aggressive autovacuum. And I put the GIN only on the searched column, never on wide text nobody searches.

"When would you choose Elasticsearch even on Postgres, where pg_trgm exists?"

When the search feature outgrows substring matching.

Relevance ranking across multiple fields with weights, typo tolerance beyond trigram similarity, faceted counts across categories, synonyms and stemming in several languages, autocomplete at high query rates, and search load that should not compete with transactional load — those are what a search engine is built for.

pg_trgm handles "find products whose name contains this" at moderate scale, and Postgres full-text search handles word search with basic ranking.

The cost of Elasticsearch is a second system to run and a sync pipeline with its own lag and failure modes, so I would start with pg_trgm and move when product asks for relevance features rather than at a row-count threshold.

"What would you tell the team to ship this week if the proper fix is a sprint away?"

Constrain the query so the existing btree helps.

If most users type the beginning of a product name, switch the search box to prefix matching, LIKE 'shoe%', which uses the index on name — with text_pattern_ops on Postgres — and covers most searches; keep the contains search behind an explicit "search anywhere" option.

Add a LIMIT and require a minimum of three characters so a one-letter search cannot scan twenty million rows. Add a statement_timeout on that endpoint.

And on Postgres, CREATE EXTENSION pg_trgm plus a concurrent GIN build is honestly a one-day change, so the "proper fix" may be closer than the team thinks; on MySQL, the prefix constraint plus a FULLTEXT index for word search is the week-one answer.

Q74 · Scenario. "WHERE email = ? OR phone = ? full-scans even though both columns have individual indexes. Why, and what is the classic rewrite?"

Reveal answer

Strong answer With AND, one index is enough — use it, then filter. With OR across different columns, one index is not enough: rows matching only the phone predicate are invisible to the email index, so using just one index would miss results. The engine must either combine both indexes or scan the table, and when the planner does not trust the combination, it scans.

  1. Check what the plan actually chose. Postgres handles this case fairly well with BitmapOr — scan each index, union the bitmaps of matching pages, then visit the table once. MySQL's equivalent is index merge union, shown as Using union(idx_email, idx_phone) in Extra; it exists but the optimizer abandons it more readily.
  2. The classic rewrite when merge does not happen: split the OR into a UNION — SELECT ... WHERE email = ? UNION SELECT ... WHERE phone = ?. Each branch is a clean single-index seek, and UNION deduplicates the row that matches both; if the predicates are provably disjoint, UNION ALL skips the dedup cost.
  3. Two clarifications worth volunteering: OR on the same column is fine — it is just an IN list, one index, several seeks; and an OR mixing an indexed column with an unindexed one forces a full scan no matter what, because one side has no index to merge.

Land it OR across columns needs the union of two searches — either the planner unions bitmaps for you, or you write the UNION yourself.

Likely follow-ups
"The UNION rewrite returns duplicates when a row matches both branches — how do you handle that, and what does it cost?"

UNION without ALL deduplicates by comparing entire rows, which is a sort or a hash over the combined result. For a lookup returning a handful of rows that is negligible.

For large results, it is a real cost, and the cleaner way is to deduplicate on the primary key only: SELECT * FROM users WHERE id IN (SELECT id FROM users WHERE email = ? UNION SELECT id FROM users WHERE phone = ?), which unions narrow id lists from index-only scans, deduplicates cheaply, and fetches each row once.

If the two predicates cannot both be true for one row — say email and phone are mutually exclusive lookups by design — UNION ALL skips deduplication entirely, and I document why it is safe.

"Why does MySQL abandon index merge union more readily than Postgres's BitmapOr?"

Partly cost model, partly implementation.

MySQL's index merge union requires each branch's index to produce row ids that it then merges; for non-primary-key indexes on InnoDB the row id is the primary key, and merging requires sorting each branch's results, shown as sort_union, which the optimizer prices high, so it often prefers a full scan when either branch is not very selective.

It also refuses merge when the OR mixes ranges and equalities in certain ways, or when one branch is on a prefix index.

Postgres's bitmap machinery works at the page level, needs no sort, and combines any number of indexes uniformly, so its cost is lower and it is chosen more often. The behaviour difference is why the UNION rewrite is standard advice on MySQL.

"The OR is on the same column but with a range: WHERE a = ? OR a > ?. Does the same problem apply?"

No, that is one index doing two range scans.

Both engines treat an OR on a single indexed column as a set of ranges on that index — an equality is a one-point range — and scan each range in turn; MySQL shows type: range and Postgres shows a single Index Scan with two index conditions or a BitmapOr over the same index.

The output is not in a single index order across the ranges, so an ORDER BY on that column may still need a sort, but the filtering is efficient.

The multi-index problem only arises when the OR spans different columns, because then no single sorted structure contains both sets of matching rows.

Q75 · Scenario. "In Postgres, DELETE FROM customers WHERE id = ? takes 40 seconds. The customers table is tiny. What is going on?"

Reveal answer

The real test The unindexed foreign key — and knowing that Postgres and MySQL differ on auto-indexing.

Strong answer When the deleted table is small, the cost is almost certainly not the delete itself but its foreign keys — the declared references from child tables. For every parent row deleted, the database must check the child tables for referencing rows (to block the delete, cascade it, or null the reference). If the child's foreign-key column has no index, each check is a full scan of the child table.

  1. Confirm: plain EXPLAIN will not show it, because the checks run as internal triggers. EXPLAIN ANALYZE does — at the bottom you see lines like Trigger for constraint orders_customer_id_fkey: time=39800.21 calls=1. That line is the whole diagnosis.
  2. The trap is engine-specific and worth stating precisely: Postgres does not automatically index foreign-key columns — it indexes the referenced side (the parent's key is unique) but leaves the referencing column bare. MySQL's InnoDB requires an index on the foreign-key column and creates one if you did not, so this failure mode barely exists there.
  3. Fix: CREATE INDEX CONCURRENTLY ON orders (customer_id); — concurrently, so writes are not blocked during the build. The delete drops from 40 seconds to milliseconds.
  4. Prevention: a periodic catalog query that lists foreign keys lacking a supporting index, run as part of schema review — this is one of the most common Postgres production landmines, and it also throttles UPDATE of parent keys and cascaded operations, not just deletes.

Land it Every foreign key is a hidden query against the child table — in Postgres, you must index it yourself, and EXPLAIN ANALYZE's trigger lines are where that hidden cost surfaces.

Likely follow-ups
"Give me the catalog query that finds unindexed foreign keys in Postgres."

The idea is to join constraints of type f against indexes on the referencing table and keep those where no index's leading columns match the constraint's columns:

SELECT c.conrelid::regclass AS tbl, c.conname,
       array_agg(a.attname ORDER BY k.ord) AS cols
FROM pg_constraint c
JOIN LATERAL unnest(c.conkey) WITH ORDINALITY k(attnum, ord) ON true
JOIN pg_attribute a ON a.attrelid = c.conrelid AND a.attnum = k.attnum
WHERE c.contype = 'f'
  AND NOT EXISTS (
    SELECT 1 FROM pg_index i
    WHERE i.indrelid = c.conrelid
      AND (i.indkey::int2[])[0:array_length(c.conkey,1)-1] = c.conkey)
GROUP BY 1, 2;

The prefix comparison is what matters: an index whose leading columns are the FK columns counts, so (customer_id, created_at) covers customer_id. I run it in CI against the migrated schema and fail the build on new hits, with an allow-list for tiny child tables where a scan is genuinely cheap.

"Is there ever a reason not to index a foreign key column?"

Yes, when the child table is tiny or when the parent is never deleted or key-updated and no query joins in that direction. Every index costs writes, and a child table with a hundred rows scans in microseconds.

Another case is a very wide-fanout FK on a huge, insert-heavy table — an events.tenant_id with a hundred million rows and twenty tenants — where the index is large, low-selectivity, and rarely used for lookups; if tenants are never deleted, the index's only job is the FK check, which never runs.

I would still usually have a composite starting with that column for query reasons. The rule is: default to indexing FK columns, and document the specific exceptions with the reason.

"Postgres 'does not index FK columns' — but does that also affect INSERT or UPDATE of the child?"

No, and that is why it hides. When a child row is inserted or its FK updated, Postgres checks that the parent exists by looking up the parent's primary key, which is always indexed, so that direction is fast.

The unindexed direction is the parent-side check: deleting a parent, updating its key, or cascading, which must find children by the FK column.

So an application that creates orders all day sees no problem, and the first customer deletion or GDPR erasure takes forty seconds and holds a lock on the parent row throughout.

Also affected is any explicit join or filter on the child's FK column, which is common and usually why the index gets added anyway. MySQL's InnoDB creates the index automatically at FK creation time, so the trap does not exist there.

Q76 · Scenario. "A query from your Java service is fast for the first few calls after deploy, then suddenly 50× slower — but the same SQL is always fast in psql. What is happening?"

Reveal answer

Strong answer "Fast five times, then slow" is the signature of Postgres's prepared-statement plan caching. A server-side prepared statement gets a custom plan — planned fresh using the actual parameter values — for its first five executions.

After that, Postgres compares costs and may switch to a generic plan: one plan reused for every future execution, built without looking at the parameter values.

If your data is skewed — say one tenant owns half the rows — the generic plan can be catastrophically wrong for the common parameter, and it kicks in exactly on execution six.

In psql you send plain queries, so every run is custom-planned and fast — which completes the picture.

  1. Confirm: prepare the statement in a session and run EXPLAIN EXECUTE stmt(...) six times, watching the plan flip; or check that the JDBC connection has crossed pgJDBC's prepareThreshold (default 5), the point where the driver switches to server-side prepared statements.
  2. Fix options, in preference order: SET plan_cache_mode = force_custom_plan for the affected role or session — planning on every execution is usually pennies next to a wrong plan; or set prepareThreshold=0 in the JDBC URL to stop server-side preparation; or attack the skew itself with better statistics.
  3. MySQL note for contrast: it keeps no plan cache across executions — prepared statements are re-optimized per execution with the real values, so this failure mode does not exist, at the cost of paying optimization every time.

Land it "Slow only from the app, and only after a handful of calls" points at the generic-plan switch — parameter skew is the disease, plan_cache_mode is the lever.

Likely follow-ups
"How does Postgres decide to switch to the generic plan, exactly?"

For the first five executions of a prepared statement it plans with the actual parameter values, a custom plan, and records each plan's estimated cost.

On the sixth execution it also builds a generic plan, one that does not look at the values, and compares the generic plan's estimated cost against the average estimated cost of the custom plans so far, plus a small planning-cost allowance.

If the generic estimate is not more expensive, it switches to the generic plan permanently for that prepared statement.

The trap is that the comparison uses estimates, not measured time, and the generic estimate assumes average selectivity, so on skewed data it looks cheap while being terrible for the common value. plan_cache_mode, available since Postgres 12, overrides the choice.

"You set plan_cache_mode = force_custom_plan. What does that cost, and where do you set it?"

It costs planning time on every execution, typically a fraction of a millisecond for a simple query and a few milliseconds for a complex join, instead of amortising one plan across thousands of runs.

For most OLTP statements that is negligible next to execution, and the safety of a plan that always sees the values is worth it.

I set it per role, ALTER ROLE app SET plan_cache_mode = force_custom_plan, so it applies to the application without touching the server config, and I can leave the reporting role on the default.

For a single known statement I would rather fix the skew: a partial index or extended statistics let even the generic plan be right. Forcing generic plans, the other option, is for statements with genuinely uniform data and heavy planning cost.

"How do you distinguish this from a cache-warmth or statistics problem?"

The "exactly after five calls per connection" pattern is the tell; warmth and statistics do not count executions. To confirm, in psql I do what the driver does: PREPARE q(int) AS SELECT ..., then EXPLAIN (ANALYZE) EXECUTE q(42) six times.

Executions one through five show a plan with the literal value in the Index Cond; the sixth shows $1 in the condition and a different shape, and the timing jumps. Since Postgres 16, EXPLAIN (GENERIC_PLAN) shows the generic plan directly.

On the application side, pgJDBC's prepareThreshold defaults to five, matching the symptom, and setting prepareThreshold=0 in the connection URL and seeing the slowness disappear is a second confirmation.

"Does using a connection pooler like PgBouncer change this?"

Yes, in two ways.

In transaction pooling mode, server-side prepared statements did not work at all until PgBouncer 1.21, because the statement is prepared on one server connection and the next transaction may run on another; older setups therefore ran with prepareThreshold=0 and never hit the generic-plan switch.

Newer PgBouncer tracks prepared statements per server connection, so the problem returns once you upgrade and enable it.

The other way is that execution counts are per server connection, so with a pool of fifty connections, each one flips to a generic plan after its own five runs, and the slowdown appears gradually across the fleet rather than all at once, which makes it harder to correlate with a deploy.

Q77. "EXPLAIN versus EXPLAIN ANALYZE — what is the difference, and is there any danger in running them?"

Reveal answer

Strong answer EXPLAIN shows the plan the optimizer would use, with its cost and row estimates — it never touches the data, so it is always safe, but it can lie, because estimates come from statistics.

EXPLAIN ANALYZE actually executes the query and reports reality alongside the estimates: actual rows, actual time per node, loop counts — comparing estimated to actual rows is the single most useful diagnostic in query tuning.

The danger follows directly from "actually executes": EXPLAIN ANALYZE on an UPDATE or DELETE really performs the writes. The discipline is to wrap destructive statements: BEGIN; EXPLAIN ANALYZE DELETE ...; ROLLBACK; — and never skip that on production.

In Postgres I would also add BUFFERS — EXPLAIN (ANALYZE, BUFFERS) — to see pages read from cache versus disk. MySQL has EXPLAIN ANALYZE since 8.0.18 with the same semantics and the same danger, plus EXPLAIN FORMAT=TREE for the readable form of estimates only.

Land it Estimates tell you what the planner believed; ANALYZE tells you what actually happened — and because ANALYZE means "run it", destructive statements get a transaction around them, always.

Likely follow-ups
"Besides writes, is there any other risk in EXPLAIN ANALYZE on production?"

Yes: it runs the full query, so a bad query is a bad query, and it costs the same locks, memory, and I/O as the real thing.

An EXPLAIN ANALYZE on a five-minute report holds its snapshot for five minutes and pins vacuum like any long read.

On Postgres the TIMING option adds overhead from calling the clock per row, which on some virtual machines inflates times by a large factor; EXPLAIN (ANALYZE, TIMING OFF) still gives row counts and total time. And it consumes memory: a hash join's work_mem is real.

So on production I run it at low traffic, with a statement_timeout set, and wrapped in a rolled-back transaction if it writes. MySQL's version can be cancelled with KILL QUERY and has the same characteristics.

"What does BUFFERS add, and how do you read it?"

Per node, the number of 8 kilobyte pages touched, split into shared hit — found in the buffer cache — shared read — read from the operating system, which may itself be cached — dirtied, and written, plus temp read and written for spills.

It turns "this node took 800 milliseconds" into "this node read 90,000 pages from disk", which points at the cause.

A high hit count with a low read count and still slow means CPU-bound work like a sort or a poor join order; a high read count means cache misses and the fix is a narrower index or more memory; temp buffers mean work_mem is too small.

Since Postgres 15, EXPLAIN (BUFFERS) without ANALYZE also shows planning-time buffers, which reveals catalog bloat when planning itself is slow.

"How do you get plans for slow queries you did not run yourself?"

With automatic plan logging. In Postgres, the auto_explain module: shared_preload_libraries = 'auto_explain', auto_explain.log_min_duration = '500ms', auto_explain.log_analyze = on, auto_explain.log_buffers = on, and auto_explain.log_nested_statements for function bodies. Every statement slower than the threshold logs its actual plan with bound parameter values.

The cost is the ANALYZE instrumentation on every statement, so I set auto_explain.sample_rate to a fraction on busy systems.

In MySQL 8.0 there is no equivalent that captures the plan at run time, so I use the slow query log to get the statement and then EXPLAIN ANALYZE it with the logged values; EXPLAIN FOR CONNECTION id can show the plan of a currently running statement.

Q78. "Here is a Postgres plan from production. Read it to me and tell me what is wrong."

Reveal answer

Strong answer Take this plan:

explain-analyze.txt
Nested Loop  (cost=0.86..1245.10 rows=8 width=64)
             (actual time=0.041..4180.20 rows=48120 loops=1)
  ->  Index Scan using idx_orders_status on orders o
        (cost=0.43..812.40 rows=8 width=32)
        (actual time=0.025..95.20 rows=48120 loops=1)
        Index Cond: (status = 'PENDING'::text)
  ->  Index Scan using order_items_pkey on order_items i
        (cost=0.43..8.45 rows=1 width=32)
        (actual time=0.004..0.085 rows=1 loops=48120)
        Index Cond: (order_id = o.id)
Planning Time: 0.210 ms
Execution Time: 4183.117 ms

Reading it: indented children feed their parents, so I start inside. The first index scan finds PENDING orders — estimated rows=8, actual rows=48120. That is the bug: the estimate is five thousand times too low. Trusting it, the planner chose a nested loop — for each outer row, probe the inner index — which is perfect for 8 rows. The inner scan's loops=48120 says it actually ran 48,120 times; its actual time is per loop, so the real inner cost is 0.085 ms × 48,120 ≈ 4.1 seconds — essentially the whole execution time. With the true row count, a hash join reading order_items once would win easily. The estimate is wrong because statistics are stale or the value distribution is skewed, so the fix is ANALYZE orders, then re-check; if PENDING correlates with another predicate, extended statistics (CREATE STATISTICS) address the correlation.

Land it The reading order is: find the worst estimate-versus-actual gap, multiply per-loop times by loops, and you usually have both the culprit and the reason the planner was fooled.

Likely follow-ups
"ANALYZE did not fix the estimate. Why might an estimate of 8 versus 48,000 survive fresh statistics?"

Several reasons. The value is not in the most-common-values list because the statistics target is too low for a column with many distinct values, so PENDING is estimated from the histogram's average; raising SET STATISTICS on the column fixes that.

The estimate is a generic plan's average across all statuses, not a value-specific estimate; forcing custom plans fixes that.

There is a second predicate with a correlated column — status = 'PENDING' AND region = 'IN' — where the planner multiplies independent selectivities and under-estimates the combination; CREATE STATISTICS ... (dependencies) ON status, region fixes that.

Or the predicate involves an expression or a function the planner cannot estimate, where it falls back to a fixed default selectivity of 0.5 percent for equality on unknowns; an expression index gives it statistics.

"If you cannot fix the estimate quickly, how do you make this plan safe today?"

Give the planner a reason to choose the hash join on its own, without a hint. The cheapest lever is SET enable_nestloop = off for the session that runs this query, which is a blunt tool but confined to one reporting job, not the whole server.

A better one is a partial index ON orders (id) WHERE status = 'PENDING', which gives the planner exact statistics for that predicate, since Postgres collects stats for partial indexes, and turns the outer scan into a cheap index-only scan too.

Or rewrite the query so the inner side is materialised: WITH p AS MATERIALIZED (SELECT id FROM orders WHERE status = 'PENDING') SELECT ... FROM p JOIN order_items USING (order_id), which in Postgres 12+ forces the planner to see the CTE's true row count before choosing the join.

"What does 'actual time is per loop' mean for the top-level number, and where do people misread it?"

In Postgres, the actual time and rows shown on a node are averages per iteration when loops is greater than one, so the inner Index Scan reads "0.085 ms, rows=1, loops=48120", and the real totals are the products: about 4.1 seconds and 48,120 rows.

People misread it by looking at 0.085 milliseconds and concluding the inner scan is fine, then hunting elsewhere.

The other misreading is the opposite: the parent's actual time is inclusive of its children, so the Nested Loop's 4,180 milliseconds is not its own work, it is mostly the inner scan it contains.

Reading a plan means subtracting children from parents to find each node's own cost, then multiplying by loops. Tools like explain.depesz.com or pgMustard do that arithmetic and highlight the worst node.

"The plan is now a hash join. What is the right index for order_items, if any?"

With a hash join, Postgres reads order_items once — sequentially or via an index — and probes the hash of pending orders per row, so the order_items_pkey index is no longer used for the join itself.

If the query only needs a few columns of order_items, an index on (order_id) with the needed columns included allows an index-only scan that is narrower than the heap; otherwise a sequential scan of the table is often right.

If the pending set is really large and stable, the hash side should be the smaller input, and the planner chooses that.

The important point is that the index that mattered for the nested loop matters much less for the hash join, so I re-check index usage after the plan change rather than assume.

Q79 · Scenario. "A MySQL query is slow; here is its EXPLAIN before and after your fix. Walk me through every field that changed."

Reveal answer

Strong answer Suppose the query is SELECT * FROM orders WHERE customer_id = 42 ORDER BY created_at DESC LIMIT 20:

mysql-explain-before-after.txt
mysql> EXPLAIN SELECT ... \G          -- BEFORE
         type: ALL
possible_keys: NULL
          key: NULL
         rows: 2013456
     filtered: 10.00
        Extra: Using where; Using filesort

mysql> ALTER TABLE orders ADD INDEX idx_cust_created (customer_id, created_at);
mysql> EXPLAIN SELECT ... \G          -- AFTER
         type: ref
          key: idx_cust_created
         rows: 118
     filtered: 100.00
        Extra: NULL

Decoding the before: type: ALL means a full table scan — the worst access type. rows: 2013456 is the optimizer's estimate of rows it must examine, and filtered: 10.00 means it expects only 10% of those to survive the WHERE — so it examines two million rows to keep two hundred thousand, then Using filesort says it sorts them outside the index (in memory or on disk — "filesort" does not necessarily mean a file, which is worth saying) just to keep 20. Its sibling Using temporary, had it appeared, would mean an implicit temporary table, typical of GROUP BY. After adding (customer_id, created_at): type: ref means an equality seek on a non-unique index; rows: 118 — only that customer's rows are touched; filtered: 100.00 — everything examined survives; and the filesort is gone because the index already yields created_at order, so the engine reads 20 entries backward and stops.

Land it The trio to read every time is type, rows, and Extra — access method, work volume, and hidden extras like filesort — and a good index moves all three at once.

Likely follow-ups
"Explain the type column values in order from best to worst."

From best: system and const, a single-row lookup by primary key or unique index with a constant; eq_ref, one row per outer row via a unique index in a join, the ideal join type; ref, an equality on a non-unique index returning a few rows; fulltext for FULLTEXT indexes; ref_or_null, ref plus a NULL check; index_merge, several indexes combined; range, an index range scan from BETWEEN, comparison, or IN; index, a scan of the entire index in order, better than ALL only because the index is narrower; and ALL, a full table scan. For a hot OLTP query I want const, eq_ref, or ref, accept range with a tight range, and treat index or ALL on a large table as a bug unless the query genuinely needs most rows.

"What would key_len have told you, and what does rows: 118 not tell you?"

key_len is the number of bytes of the index actually used for the seek, which tells me how many leading columns the query exploits.

For (customer_id BIGINT, created_at DATETIME) with an equality on customer_id only, key_len is 8, meaning the second column is used for ordering but not seeking; if it were 13, both columns would be part of the seek condition.

It is how I catch a composite index only half used. rows: 118 is an estimate from index statistics, not a count: it is the optimizer's guess of rows examined, and it can be badly wrong for a skewed customer.

EXPLAIN ANALYZE in 8.0.18+ shows actual rows and time per node, which is what I use to confirm.

"filtered went from 10 to 100. What is that number for, and why does it matter for joins?"

filtered is the optimizer's estimate of the percentage of examined rows that survive the table's WHERE conditions after the access method.

Its main use is in join planning: the number of rows passed to the next table is rows × filtered / 100, so a wrong filtered estimate on the first table skews every later join's cost.

Before the fix, the optimizer expected 200,000 survivors from a two-million-row scan, which would have made any subsequent join look expensive and might have pushed it to a bad join order.

After, with ref access delivering only matching rows, filtered is 100 and the estimate is 118 rows flowing onward. It comes from index statistics and, in 8.0, from histograms if they exist; without histograms it is often a fixed guess.

"Why did the filesort disappear, and would it have disappeared with ORDER BY created_at ASC?"

It disappeared because the index (customer_id, created_at) stores each customer's entries in created_at order, so once the engine seeks to customer 42 it reads entries already sorted, and for DESC it reads them backward from the end of that customer's strip — MySQL 8.0 shows Backward index scan in Extra.

With ASC it reads forward, so yes, it disappears in both directions; a single-column ordering can always be served in either direction by one index.

What would bring filesort back is ordering by a column not in the index, or an ORDER BY over a range on the first column, such as customer_id IN (1, 2) ORDER BY created_at, where entries from two strips must be merged.

Q80. "Nested loop, hash join, merge join — explain each in plain words and tell me when each one wins."

Reveal answer

Strong answer A nested loop takes each row from the outer side and looks up matches on the inner side — fast when the outer side is small and the inner side has an index, because it is a handful of cheap probes; disastrous when the outer side unexpectedly has fifty thousand rows, because every one is a probe.

A hash join reads the smaller side once and builds an in-memory hash table on the join key, then streams the bigger side through it, probing per row — it wins for large inputs joined on equality with no useful index, costs memory for the hash table, and cannot handle inequality joins.

A merge join requires both sides sorted on the join key and zips them together in one coordinated pass — it wins when the inputs are already sorted, typically because indexes provide the order, and it is the gentle option for two huge sorted inputs.

Engine honesty: Postgres implements all three and switches based on estimates. MySQL historically had only nested loops; hash join arrived in 8.0.18, and MySQL still has no merge join — a genuine difference worth knowing in migrations.

Land it The planner's join choice is a bet on row counts — which is why a bad row estimate, like Q78's, does not just slow a scan but flips the entire join strategy.

Likely follow-ups
"A hash join spills to disk. What does that look like and what do you do?"

In a Postgres plan, the Hash node shows Batches: 8 instead of 1, and with BUFFERS, temp blocks written and read.

It means the build side did not fit in work_mem, so Postgres partitioned both inputs into batches by hash value, wrote all but the first to temporary files, and processed them one at a time — each batch is a pass over disk.

The fixes, in order: make the build side smaller by filtering earlier or projecting fewer columns, since Postgres hashes the whole row; make sure the smaller input is the one being hashed, which the planner does if its estimates are right; then raise work_mem for that session.

A large number of batches with small inputs also indicates a bad row estimate on the build side, which is the same statistics fix as always.

"When does the nested loop beat a hash join even for large inputs?"

When the outer side is small after filtering and the inner probe is a cheap indexed lookup, or when the query has a LIMIT and the plan can stop early.

A nested loop produces rows incrementally: with ORDER BY served by an index on the outer side and LIMIT 20, it probes the inner index twenty times and stops.

A hash join must first read the entire build side before producing any row, so LIMIT saves nothing. Nested loops also win when the join condition is not an equality, since hashing needs equality, and when memory is scarce.

That is why the planner's row estimate on the outer side is the whole game: at 8 rows the nested loop is perfect, at 48,000 it is a disaster, and the same query flips between the two on the estimate.

"MySQL had only nested loops for years. How did it get away with that?"

Through the block nested loop and index-driven joins.

For every join it required, in practice, an index on the inner table's join column, so each probe was a cheap B+tree seek — effectively an index nested loop, which is excellent for OLTP. For joins without an index it used block nested loop, buffering outer rows in the join_buffer_size and scanning the inner table once per buffer-full, which is slow but bounded.

The consequence was that MySQL applications learned to index every join column and avoid large analytical joins, and that culture still shows in how MySQL schemas are designed.

Hash join in 8.0.18 replaced block nested loop and made unindexed large joins reasonable, but the index-nested-loop remains the OLTP workhorse.

"How would you read a plan to see which join was picked and whether it was the right one?"

In Postgres, the node names say it: Nested Loop, Hash Join with a child Hash node, or Merge Join possibly with Sort children.

Then I check three things: the estimated versus actual rows on both inputs, because the choice was based on the estimates; for a nested loop, the inner node's loops count and per-loop time multiplied out; for a hash join, batches and memory; for a merge join, whether the sorts spilled.

In MySQL, EXPLAIN FORMAT=TREE shows Nested loop inner join or Inner hash join explicitly, and EXPLAIN ANALYZE adds actual rows and loops. If the actual input sizes would have favoured a different join, the fix is the estimate, not a hint.

Q81 · Scenario. "A dashboard query with WHERE tenant_id = ? ORDER BY created_at DESC LIMIT 20 takes 8 seconds and the plan shows it sorting 2 million rows. Fix it."

Reveal answer

Strong answer The shape of the failure: the engine finds all 2 million rows for the tenant, sorts every one of them by created_at, and then throws away all but 20. The LIMIT saves nothing, because a sort must see all its input before it knows which rows are the top 20.

  1. Confirm in the plan: Postgres shows a Sort node under the Limit (possibly external merge on disk); MySQL shows Using filesort.
  2. The fix is an index that delivers rows already in the requested order: (tenant_id, created_at). The equality on tenant_id pins one contiguous strip of the index, and within the strip entries are sorted by created_at — so the engine starts at the strip's end, reads 20 entries backward (or forward with an explicit DESC index), and stops. Two million sorted rows become 20 index reads.
  3. Verify: the Sort node vanishes — Postgres shows Limit → Index Scan Backward, MySQL's Extra loses the filesort — and runtime drops to single-digit milliseconds.
  4. The generalization worth saying: ORDER BY ... LIMIT n is only cheap when one index serves both the WHERE and the ORDER BY; if the sort column lives in a different index from the filter column, the engine must pick one and pay the sort or the filter in full.

Land it LIMIT can only stop early if the rows arrive pre-ordered — designing the index to serve filter and order together is what turns "sort 2M rows" into "read 20".

Likely follow-ups
"You added (tenant_id, created_at) and the plan still sorts. What are the likely causes?"

Four to check. The ORDER BY has an extra tiebreak column, ORDER BY created_at DESC, id DESC, that the index does not include; the fix is (tenant_id, created_at, id) so the full sort key is in the index.

The query uses IN or a range on tenant_id, so several strips must be merged and the engine sorts. The created_at expression differs from the column, such as ORDER BY created_at::date DESC or a COALESCE.

Or the planner estimates the tenant has few rows and decides a sort of a small set is cheaper than an index scan; that is fine if true, and if false it is a statistics problem.

I would also check that the direction matches: an all-ascending index serves DESC by backward scan, so direction alone is not it unless mixed.

"The dashboard also shows the total count of the tenant's rows next to the top twenty. What happens to that?"

The count is a separate, much more expensive query: SELECT COUNT(*) WHERE tenant_id = ? reads all two million index entries for that tenant, and the LIMIT trick cannot help it.

So the page goes from 20 index reads to 2 million reads again, just in a different statement.

The options are an approximate count from statistics if the number is decorative, a maintained counter per tenant updated transactionally or from events, or a cached count refreshed every minute.

If the count must be exact and live, at least make it an index-only scan on a narrow index so it reads a few thousand pages rather than the table, and cap the cost with a timeout.

The general lesson is that "top N" and "how many" are different problems with different costs.

"What would 8 seconds have cost at scale, and how would you have caught it before the dashboard was slow?"

An 8-second sort of two million rows is roughly two million row reads, a sort of perhaps 200 megabytes probably spilling to disk, and a connection held for 8 seconds, on every dashboard load.

At fifty tenants opening the dashboard once a minute that is four hundred CPU-seconds of sorting and hundreds of megabytes of temp I/O per minute, and under a burst the connection pool fills.

Catching it early: pg_stat_statements ordered by total time would have shown this fingerprint climbing as tenants grew; auto_explain would have logged the Sort node with its size; and a load test with one prod-sized tenant would have shown the plan on day one.

The query was fine at ten thousand rows, which is why staging never saw it.

Q82 · Scenario. "Your paginated API is fine on page 1 but times out around page 10,000 with LIMIT 20 OFFSET 200000. Why, and what is the fix?"

Reveal answer

Strong answer OFFSET does not skip — it produces and discards. To serve OFFSET 200000 LIMIT 20, the engine must generate the first 200,020 rows in order and throw away 200,000 of them; the work grows linearly with page number, so deep pages are slow by construction and the last page is the slowest query in the system.

  1. The fix is keyset pagination (also called seek pagination): instead of counting rows to skip, remember where the last page ended and seek directly there. The API returns the last row's (created_at, id) as a cursor, and the next page asks: WHERE (created_at, id) < (?, ?) ORDER BY created_at DESC, id DESC LIMIT 20. That row-value comparison — supported natively by Postgres and MySQL 8 — is a single index seek on (created_at, id), so page 10,000 costs the same as page 1.
  2. id is in the key as the tie-breaker: created_at alone is not unique, and without a unique total order rows can repeat or vanish at page boundaries.
  3. Trade-offs to state plainly: keyset cannot jump to an arbitrary page number, only forward and backward from a cursor — so the UI shifts to infinite scroll or next/previous; in exchange it is also stable under concurrent inserts, where OFFSET pages drift and show duplicates.
  4. If product genuinely requires "jump to page N", I would cap the depth (as most large sites do) rather than let OFFSET scale unboundedly.

Land it OFFSET is O(page number), keyset is O(1) — carry a cursor of the last seen key and turn "skip 200,000" into one index seek.

Likely follow-ups
"How do you page backward with keyset pagination?"

Reverse both the comparison and the sort, then flip the result. For a forward page ordered created_at DESC, id DESC with cursor (c, i), the previous page is WHERE (created_at, id) > (?, ?) ORDER BY created_at ASC, id ASC LIMIT 20, which seeks to the cursor and reads twenty rows moving toward newer entries, and then the application reverses the list to display it in the original order.

The same index serves it by scanning forward instead of backward. The API returns two cursors per page, the first and last row keys, so the client can go either way.

What keyset still cannot do is jump to page 500 directly, and for "go to page N" I offer an approximation or a capped OFFSET.

"The row-value comparison is not supported by my ORM. What is the expanded form, and does it use the index?"

The expansion of (created_at, id) < (?, ?) is created_at < ? OR (created_at = ? AND id < ?).

Both engines can use the composite index for it, but less cleanly: Postgres often turns it into a Bitmap Or or an index scan with a filter rather than a single range seek, and MySQL may do two range scans.

A form the planners handle well is created_at <= ? AND (created_at < ? OR id < ?), which starts with a single range on the leading column and filters the boundary inside it.

Native row-value comparison is supported by Postgres and by MySQL 8.0.16+ for index use, so where the ORM allows a native query fragment, I use the tuple form and verify in the plan that it is one range on the index.

"Why do OFFSET pages drift under concurrent inserts, and does keyset fully solve it?"

With OFFSET, the page boundary is a row count.

If ten new rows are inserted at the front of the ordering between page one and page two, page two's OFFSET 20 now skips ten rows that were on page one and repeats ten that the user already saw. Deletes cause rows to be skipped entirely.

Keyset anchors on the last seen key, so new rows inserted before the cursor do not shift what comes after it; the user sees every row that existed at the time they reach it, with no repeats.

What it does not solve is rows inserted after the cursor position in the ordering, which appear naturally, and rows updated so that their sort key moves across the cursor, which can appear twice or never; that is why the sort key should be immutable, like created_at plus id.

"Product insists on numbered pages. What compromise do you offer?"

Numbered pages up to a cap, keyset beyond. For the first hundred pages, OFFSET up to 2,000 rows is cheap on an indexed ordering, and the UI can show page numbers.

Beyond that, the UI offers next and previous only, or a date filter that lets users jump by time instead of by page number, which is what they usually want when they type page 10,000 anyway.

Search engines and large marketplaces all cap page depth for this reason.

If numbered deep pages are truly required, I precompute page boundaries — the key at every thousandth row — in a small table refreshed periodically, and "page 10,000" becomes a keyset seek from the nearest precomputed boundary plus a small offset. That keeps every page under a few thousand rows of work.

Q83 · Scenario. "Product wants a row count badge, but SELECT COUNT(*) on the 300-million-row table takes minutes. Why can't the database just know its row count, and what do you offer instead?"

Reveal answer

Strong answer The database cannot keep one true counter because of MVCC: with multi-version concurrency control, two concurrent transactions can legitimately see different row counts at the same instant — one sees rows a not-yet-committed transaction inserted, the other does not — so "the" count does not exist; only "the count visible to your snapshot" does, and that must be computed. InnoDB therefore scans for COUNT(*), choosing the smallest index to walk since any full index visits every row; the old "MyISAM was instant" memory is about a non-transactional engine that could afford a single counter. Postgres scans too, and additionally must check each tuple's visibility; a fresh visibility map lets it use an index-only scan, which helps but is still O(rows).

  1. If approximate is acceptable — and for a badge it almost always is — use the statistics: Postgres SELECT reltuples::bigint FROM pg_class WHERE relname = 'events' (maintained by vacuum and analyze), MySQL information_schema.TABLES.TABLE_ROWS. Both are estimates, honestly stated: they can drift several percent between refreshes.
  2. If exact-and-fast is truly required, maintain a counter deliberately — a counter table updated transactionally or from an event stream — and accept the write-side cost and contention design that implies.
  3. If the count has a WHERE, an index covering the predicate makes the scan proportional to matching rows only, which is often enough.

Land it Under MVCC an exact count is a per-snapshot computation, not a stored fact — so offer the estimate for decoration and a maintained counter only where exactness is a real requirement.

Likely follow-ups
"Design the exact counter table and explain how you avoid it becoming a hot spot."

row_counts(table_name TEXT, shard SMALLINT, delta BIGINT, PRIMARY KEY (table_name, shard)) with, say, thirty-two shard rows per table.

Every insert or delete transaction also runs UPDATE row_counts SET delta = delta + 1 WHERE table_name = 'events' AND shard = ? with a random shard, so contention spreads over thirty-two row locks and the counter stays transactionally consistent with the data — an aborted insert also aborts its increment.

Reading is SELECT SUM(delta), thirty-two rows. On Postgres the constant updates generate dead tuples, so autovacuum on this tiny table must be aggressive, or I periodically fold the shards into one row.

A trigger can do the increment automatically, at the cost of a per-row trigger call on the hot table.

"How accurate is reltuples, and when does it go badly wrong?"

It is updated by VACUUM, ANALYZE, and some DDL, and between updates it is a snapshot. On a steadily growing table it lags by whatever has been inserted since the last analyze, a few percent under autovacuum defaults.

It goes badly wrong right after a bulk load or bulk delete before autovacuum has run, where it can be off by an order of magnitude, and on a table that was just created or truncated, where it is minus one meaning unknown.

Since Postgres 14 the planner interpolates using the current page count from relpages and the actual file size, which helps. For a badge, a few percent is fine; for anything used in a decision, it is not.

MySQL's TABLE_ROWS is similar and additionally is a sample-based estimate, so it can vary between reads.

"Could the database maintain the count in a materialized view or via an index instead?"

A materialized view SELECT COUNT(*) FROM events works but is just a cached scan: refreshing it costs the full count every time, so it is a scheduled expensive query, acceptable if the refresh is hourly and the count can be that stale.

An index does not help directly because the index has as many entries as the table, but an index-only scan on the narrowest index reads far fewer pages than the heap, which turns minutes into seconds on a table with wide rows; on InnoDB the same happens automatically because COUNT(*) walks the smallest index.

Neither gives a constant-time count. The choices remain: estimate, maintained counter, or bounded scan, and I present them as a staleness-versus-cost menu for product to pick from.

Q84. "What is a correlated subquery, why is it slow, and how do you see the problem in the plan?"

Reveal answer

Strong answer A correlated subquery references a column of the outer query — for example SELECT * FROM products p WHERE price > (SELECT AVG(price) FROM products p2 WHERE p2.category = p.category).

Because the inner result depends on the current outer row, the naive execution runs the subquery once per outer row — a million rows means a million aggregate queries.

In the plan it is unmistakable: Postgres shows a SubPlan node whose loops equals the outer row count; MySQL labels it DEPENDENT SUBQUERY.

The rewrite computes each group's answer once and joins it back: JOIN (SELECT category, AVG(price) avg_price FROM products GROUP BY category) a ON a.category = p.category WHERE p.price > a.avg_price — one aggregation pass, one join, and the plan shows a hash join instead of a repeated SubPlan.

Honesty note: modern optimizers de-correlate many patterns automatically — IN becomes a semi-join, and so on — so the rule is not "never write subqueries" but "check whether the plan shows per-row re-execution".

Land it loops = outer row count on a SubPlan is the tell — compute once and join, and verify the optimizer did not already do it for you.

Likely follow-ups
"Which subquery shapes does the optimizer de-correlate automatically, and which does it not?"

Both engines turn IN (SELECT ...) and EXISTS (SELECT ... WHERE inner.x = outer.x) into semi-joins, so those are usually safe. Postgres also flattens simple subqueries in FROM and pulls up uncorrelated subqueries to run once as InitPlans.

What neither reliably de-correlates is a correlated scalar subquery in the SELECT list or in a comparison, like the average-per-category example, and NOT IN with nullable columns, which has NULL semantics that prevent the anti-join transformation — NOT EXISTS is the form that converts.

MySQL 8.0 added derived-table merging and semi-join for more shapes over the 8.0.x series, so the set grows with version, which is why the honest rule is to check the plan for a SubPlan or DEPENDENT SUBQUERY rather than memorise the list.

"The rewrite with a derived table aggregates the whole products table even when the outer query filters to one category. Is that a regression?"

It can be. The correlated version computes the average only for categories that appear in the outer rows, while the derived-table version computes every category's average first.

If the outer query has a filter like WHERE p.category = 'shoes', the derived table wastes work on all other categories unless the planner pushes the predicate down into it, which Postgres does for simple cases and MySQL does since 8.0.22.

If it does not, I repeat the filter inside the derived table, or switch to a window function: SELECT * FROM (SELECT p.*, AVG(price) OVER (PARTITION BY category) AS avg_price FROM products p WHERE category = 'shoes') t WHERE price > avg_price, which computes the average in one pass over exactly the filtered rows.

"How would LATERAL change this, and when is a per-row subquery actually the right plan?"

LATERAL makes the per-row execution explicit and lets the subquery return multiple rows and columns, so it is the tool when per-row work is genuinely what I want: the top three orders for each of twenty customers, where the inner query uses an index on (customer_id, created_at) with LIMIT 3.

That is twenty cheap index probes, far better than aggregating the whole orders table and filtering.

The rule is about the outer row count times the inner cost: a correlated subquery is right when the outer set is small and the inner is an indexed seek, and wrong when the outer set is large or the inner is an aggregate over many rows.

The plan's loops count times per-loop time tells me which case I am in.

Q85. "Is SELECT * actually harmful, or is that just style dogma?"

Reveal answer

Strong answer It has real, measurable costs — the answer is boring but concrete.

First, it defeats covering indexes: the moment the query needs every column, no index can satisfy it alone, so every row forces the second lookup — the clustered-index visit in InnoDB, the heap fetch in Postgres — and a query that could have been index-only never will be.

Second, it drags the widest payloads: large text and JSON columns, which Postgres stores out-of-line in TOAST — its overflow area for big values — get fetched and detoasted even when the caller wanted three fields.

Third, it inflates network transfer and JDBC-side memory, which at thousands of calls per second is real money and real GC pressure. Fourth, it creates schema coupling: added columns silently widen every SELECT * call site, and code that reads columns by position breaks.

The honest counterpoint: in ad-hoc analysis and debugging it is fine — the cost argument applies to hot application paths.

Land it Naming columns is not style — it is what makes covering indexes possible and keeps the wire and the heap out of queries that did not need them.

Likely follow-ups
"My ORM generates SELECT * for every entity load. What do I do about it?"

Use projections for the hot read paths and keep full-entity loading for writes.

In Spring Data JPA, an interface or record projection — interface OrderSummary { Long getId(); String getStatus(); BigDecimal getTotal(); } as the repository return type — generates a SELECT of just those columns, which can be index-only. JPQL constructor expressions do the same.

For large columns that are rarely needed, mark them @Basic(fetch = LAZY) with bytecode enhancement enabled, or move them to a separate table joined only when needed.

For writes, the ORM loads the full row because it needs the version and the unchanged columns for dirty checking, and that is acceptable because writes are by primary key.

The measurement that justifies the effort is bytes per query from pg_stat_statements or the network monitoring, not principle.

"Explain TOAST and why SELECT * hurts more on Postgres than MySQL for wide rows."

Postgres pages are 8 kilobytes and a row must fit on one page, so any value that would push the row past about 2 kilobytes is compressed and, if still too big, moved out of line into a TOAST table — the oversized attribute storage technique — with a pointer left in the row.

Reading that column then means extra page reads in the TOAST table and decompression. SELECT * forces all of that for every row, even when the caller only wanted the id and status; naming columns leaves the pointers untouched.

InnoDB's DYNAMIC row format also stores large values off-page, but its 16 kilobyte pages and in-page storage of values up to a threshold mean fewer rows overflow, and it does not compress by default.

The cost exists in both; it is just bigger and more common on Postgres.

"What is the schema-coupling failure with SELECT *? Give me a real one."

The classic is INSERT INTO archive SELECT * FROM orders, which works until someone adds a column to one table and not the other, and then fails or, worse, shifts columns if the types happen to be compatible.

Another is a view defined with SELECT * in Postgres, which captures the column list at creation time and silently does not include new columns, confusing everyone who reads the definition.

A third is application code that reads result columns by index, rs.getString(3), which breaks when a column is added in the middle.

And with a covering index, SELECT * means a new column added for one feature silently converts every existing index-only query into a heap-fetching one, a performance regression with no code change in the affected queries.

Q86 · Scenario. "The query is fast in staging and slow in production. Same schema, same indexes, same SQL. Give me your checklist."

Reveal answer

The real test Whether you know a plan is a function of data and environment, not just SQL text.

Strong answer "Same SQL" proves almost nothing, because the plan is chosen from statistics, data volume, and machine state — all of which differ. My checklist, in order:

  1. Get the real production plan with real parameters — EXPLAIN (ANALYZE, BUFFERS) at low-traffic time, or capture it passively with Postgres's auto_explain module / MySQL's slow query log. Diffing prod's plan against staging's usually ends the mystery immediately.
  2. Data volume: staging has 1% of prod's rows, and plans flip with scale — a nested loop that is perfect on 10,000 rows is a disaster on 100 million. This is the most common cause.
  3. Parameter skew: staging tests average tenants; production hammers the biggest one. Same plan, thousandfold different row counts — and per Q76, a cached generic plan can lock the wrong choice in.
  4. Statistics freshness on prod — estimate-versus-actual gaps in the plan, per Q70.
  5. Cache warmth and memory: staging's dataset fits entirely in the buffer pool or page cache, so everything is a memory read; prod misses to disk. BUFFERS output shows the read counts.
  6. Concurrency and locks: the query may be healthy but waiting — check pg_stat_activity wait events or InnoDB lock waits.
  7. Bloat and configuration drift: prod tables carry dead-row bloat staging never accumulates, and settings like work_mem or buffer pool size may genuinely differ.

Land it Staging validates correctness, not plans — only a prod-sized, prod-skewed dataset predicts prod behavior, and the actual production plan is where the investigation starts.

Likely follow-ups
"You get the production plan and it is identical to staging's. Now what?"

Then the plan is not the problem and I look at execution and environment. The same plan with BUFFERS can show far more reads in production because the working set does not fit in cache, so I compare shared hits versus reads.

Lock waits: the query might be healthy but queued behind a lock, which pg_stat_activity.wait_event shows.

Bloat: the same index scan over an index three times the size does three times the I/O. Configuration: work_mem, effective_cache_size, and random_page_cost may differ, and a sort that fits in memory on staging spills on prod.

Hardware: production may be on slower or shared storage, which pg_test_fsync and iostat show. And finally concurrency: one query in isolation is fast; five hundred of them a second contend for CPU, and the per-query time is a symptom of saturation.

"How would you make staging predictive of production plans without copying production data?"

Copy the statistics rather than the data. Postgres's pg_dump --statistics-only, new in version 18 as of Aug 2026, or the older approach of restoring pg_statistic rows via extensions, lets staging's planner see production's row counts and distributions so it chooses the same plans.

Alternatively, generate synthetic data at production volume and skew — tools like pgbench-style generators or in-house scripts that reproduce the tenant size distribution — because the shape matters more than the actual content. Refresh statistics after loading.

And test with production's parameter values, especially the largest tenant. Staging that has one percent of the rows with uniform distribution will never predict a plan flip, no matter how carefully the schema matches.

"Which single check would you run first if you had two minutes?"

EXPLAIN (ANALYZE, BUFFERS) on production with the real slow parameter values, captured from the slow log or pg_stat_statements. It answers three of the seven items at once: whether the plan differs from staging, whether estimates match actuals, and whether the time is in I/O or CPU.

Almost every "fast in staging" investigation I have run ended within that one output, usually at a nested loop over an unexpectedly large row count or a sort spilling to disk.

If that output looks healthy and the query is still slow in the application, the next two minutes go to pg_stat_activity during the slowness to see whether it is waiting on a lock or a connection rather than executing.

Drill · Workflow & hygiene

This group tests how you operate day to day — finding the queries that matter, changing schemas without outages, and knowing when an index is the wrong answer entirely.

Q87. "You join a team with a 'slow database'. Where do you start — how do you find the queries actually worth tuning?"

Reveal answer

Strong answer I start from measurement, never from guesses or from whichever query a developer complains about. In Postgres the tool is pg_stat_statements — an extension that aggregates every statement's executions, total time, and rows:

worst-queries.sql
-- Postgres: top offenders by TOTAL time, not mean
SELECT calls,
       round(total_exec_time)    AS total_ms,
       round(mean_exec_time, 1)  AS mean_ms,
       rows,
       left(query, 80)           AS query
FROM pg_stat_statements
ORDER BY total_exec_time DESC
LIMIT 10;

-- MySQL: slow_query_log + long_query_time, digested with
-- pt-query-digest, or query
-- performance_schema.events_statements_summary_by_digest
-- ordered by SUM_TIMER_WAIT.

The ranking choice is the senior detail: I sort by total time, because a 5 ms query called a million times an hour burns far more database capacity than a 2-second report run twice a day — sorting by mean time finds embarrassing queries, sorting by total time finds expensive ones. I look at both views: total time tells me what to tune for capacity, mean time (and p99, where tracked) tells me what users feel. On MySQL, the slow query log with a low long_query_time plus pt-query-digest gives the same grouped-by-fingerprint ranking. Only after this list exists do I start reading plans, top entry first.

Land it Tune the workload, not the anecdote — the statement ranked first by total time is where an hour of work buys the most capacity back.

Likely follow-ups
"pg_stat_statements is not installed. What does enabling it cost, and what do you set?"

It needs shared_preload_libraries = 'pg_stat_statements' and a restart, then CREATE EXTENSION pg_stat_statements in each database. The overhead is small — a few percent at most, mostly from hashing each query's parse tree to compute its fingerprint — and it is standard on every managed Postgres offering.

Settings: pg_stat_statements.max, default 5,000 distinct fingerprints, which I raise to 10,000 on a large application so rare queries are not evicted; pg_stat_statements.track = top to exclude statements inside functions unless I want them; and track_io_timing = on so the view also shows time spent in block reads.

Then I reset it after a deploy with pg_stat_statements_reset() so the ranking reflects the current code, and snapshot it daily to compute deltas.

"Total time ranks one query first — but it is a cheap query called a million times. Is tuning it worth it?"

Often yes, but in a different way. A five-millisecond query called a million times an hour is 1.4 hours of database time per hour; shaving it to two milliseconds returns nearly an hour of capacity, which is the same as removing a large report entirely.

But the cheaper fix is usually the call count: is it in a loop that should be a batch, is it an ORM N+1, can the result be cached for a second? Cutting a million calls to ten thousand by batching beats any index.

So for the top-by-total entry, my first question is "why so many calls", and only then "why so slow per call". The calls column and the rows-per-call ratio in pg_stat_statements tell me which conversation to have.

"How do you find N+1 query patterns from the database side rather than the code?"

They have a signature: a very high calls count, a tiny mean time, one row per call, and a fingerprint of the form SELECT ... WHERE id = $1 on a child entity, with a call rate that tracks another query's row count.

In pg_stat_statements, sorting by calls and looking at rows / calls near one on non-primary-key lookups finds them. Correlating in time helps: a burst of a thousand calls of the same fingerprint within milliseconds on one connection is one request's loop.

On MySQL, events_statements_summary_by_digest gives the same columns. Then I go to the code with the fingerprint in hand, and the fix is a join fetch, a batch IN query, or Hibernate's @BatchSize.

"What would you do differently on MySQL, where the digest table is less convenient?"

Use both sources. performance_schema.events_statements_summary_by_digest gives COUNT_STAR, SUM_TIMER_WAIT, SUM_ROWS_EXAMINED, and SUM_ROWS_SENT per fingerprint; ordering by SUM_TIMER_WAIT is the total-time ranking, and the ratio of rows examined to rows sent is a direct measure of wasted work that Postgres does not expose as neatly.

Its limit is performance_schema_digests_size, default 10,000, and it is reset on restart. For history, the slow query log with long_query_time = 0 for a sampled window, digested by pt-query-digest, gives per-fingerprint percentiles including p95, which the summary table lacks.

The sys.statement_analysis view wraps the digest table with readable columns and is my usual starting point.

Q88. "Walk me through your checklist before an index you designed actually ships to production."

Reveal answer

Strong answer My checklist:

  1. Capture the current plan with EXPLAIN ANALYZE on prod-sized, prod-skewed data — a laptop dataset proves nothing, per the staging trap.
  2. Check existing indexes first: often the right move is widening or reordering one rather than adding a fourteenth, and I check what my new index makes redundant so it can be dropped in the same change.
  3. Design deliberately: equality columns, then the range or order column, then covering columns — and justify each column's presence against the write cost it adds.
  4. Estimate the standing cost: extra work on every insert and on updates of the indexed columns, index size versus buffer pool, and build time on the real table.
  5. Build without blocking: CREATE INDEX CONCURRENTLY in Postgres, online DDL (ALGORITHM=INPLACE, LOCK=NONE) in MySQL.
  6. Verify after: the plan actually changed to use it, latency actually dropped in the metrics, and no neighboring query regressed — the planner reconsiders everything when a new index appears.
  7. Ship it as a migration with a documented rollback, and re-check idx_scan counters a couple of weeks later to confirm it is really being used.

Land it An index is a schema change with a permanent write tax — measure before, build online, verify after, and be as willing to drop one as to add one.

Likely follow-ups
"How can a new index make a neighbouring query slower?"

Because the planner reconsiders every query on the table, and a new index can look cheaper than it is. A query on WHERE status = ? ORDER BY created_at LIMIT 10 that used to use (status, created_at) might switch to a new index (created_at), scanning in date order and filtering status, if the planner estimates the status is common; for a rare status it then scans millions of rows.

Or a new partial index changes estimates for a predicate and flips a join order. It happens because the choice is by estimated cost, and estimates are imperfect.

So after the build I diff the plans of every query on the table from pg_stat_statements against the plans captured before, and watch their mean time for a day. On MySQL, the same with the digest table.

"What does 'estimate the build time on the real table' mean in practice, and how do you monitor the build?"

Roughly, an index build reads the whole table once and sorts the keys, so it takes about the time of a sequential scan plus a sort of the key size; a hundred-gigabyte table on a decent disk might take twenty to sixty minutes.

In Postgres I can watch it in pg_stat_progress_create_index, which shows the phase — building, waiting for writers, validating — and blocks done versus total. The concurrent build's waiting phases are where it stalls behind long transactions, so I check pg_stat_activity for old transactions before starting.

MySQL 8.0 shows progress in performance_schema.events_stages_current with the stage/innodb/alter table stages. I schedule the build for low traffic, and set maintenance_work_mem high for the session so the sort stays in memory.

"Why re-check idx_scan two weeks later rather than immediately?"

Because usage is periodic and plans are cached. Some queries run weekly or monthly, so a zero on day one means nothing; two weeks covers most business cycles and a month covers the rest.

Cached generic plans in existing connections may keep using the old plan until they are re-planned, which happens on statistics changes or connection recycling, so immediate counters can under-report.

And the index changes only appear in the planner's choices once statistics for the index exist, which needs an ANALYZE after the build on Postgres.

If after two weeks idx_scan is still near zero, the query it was built for is not using it, and either the plan differs from what I expected or the query changed; both are worth finding out, and an unused index is a pure cost.

Q89. "Why does CREATE INDEX CONCURRENTLY exist in Postgres, and what is the MySQL story for adding an index without an outage?"

Reveal answer

Strong answer A plain CREATE INDEX in Postgres takes a lock that permits reads but blocks all writes to the table for the entire build — minutes to hours on a big table, which on a hot table is an outage.

CREATE INDEX CONCURRENTLY avoids that: it scans the table twice and waits for in-flight transactions, allowing writes throughout.

The costs I would name: it is slower overall; it cannot run inside a transaction block (which matters for migration tools); and if it fails midway it leaves behind an INVALID index that still taxes writes and must be dropped and rebuilt — so check for invalid indexes after any failed build.

On MySQL, InnoDB's online DDL — data definition language, the schema-changing statements — handles ADD INDEX in place: I write ALTER TABLE ... ADD INDEX ..., ALGORITHM=INPLACE, LOCK=NONE so it fails loudly if the online path is unavailable rather than silently locking.

The MySQL trap is the metadata lock: the brief exclusive lock at the start and end of the ALTER queues behind any long-running transaction touching the table, and every query after it queues too — so I check for long transactions before running DDL, and at very large scale tools like gh-ost or pt-online-schema-change sidestep the whole class of problem.

Land it The index build itself is rarely the outage — the lock is; build concurrently or in-place, and clear the long-transaction runway before any DDL touches a hot table.

Likely follow-ups
"Why does CREATE INDEX CONCURRENTLY need two table scans and wait for transactions?"

Because rows can change while it runs. The first pass builds the index from a snapshot while writes continue, so rows inserted or updated during the scan are missing.

It then marks the index as existing but not yet valid for reads, so that from this point every new write also maintains it. The second pass finds the rows changed between the snapshot and now and adds them.

Then it must wait for every transaction that started before the index became visible to finish, because those transactions might have written rows without updating it. Only after that wait is the index marked valid.

Each wait is where a long-running transaction stalls the build indefinitely, which is why I check for old transactions first and why pg_stat_progress_create_index shows a "waiting for old snapshots" phase.

"How do you find and fix an INVALID index left by a failed build?"

SELECT indexrelid::regclass FROM pg_index WHERE NOT indisvalid lists them; \d table in psql also shows INVALID next to the index. An invalid index is maintained on every write, so it costs as much as a real one, but the planner never uses it.

The fix is either DROP INDEX CONCURRENTLY and rebuild, or since Postgres 12 REINDEX INDEX CONCURRENTLY idx_name, which rebuilds it in place and swaps. I add that check to the migration tool's post-run step and to a weekly catalog audit, because invalid indexes are silent.

The common causes are a unique index build that found duplicates, a build cancelled by a statement timeout, and a deploy that killed the session mid-build.

"Explain the MySQL metadata lock trap in a sequence, and what you set to avoid it."

Session A starts a transaction and runs a SELECT on orders, then goes idle, still holding a shared metadata lock on the table until it commits.

My ALTER TABLE orders ADD INDEX requests an exclusive metadata lock for its brief preparation phase and queues behind A. Every subsequent statement on orders from any session, even plain SELECTs, needs a shared metadata lock and queues behind my exclusive request, so the whole application stops on that table until A commits.

The protections: SET SESSION lock_wait_timeout = 5 before the ALTER so it gives up quickly instead of holding the queue, a check of information_schema.innodb_trx for old transactions first, and performance_schema.metadata_locks to see who holds what.

gh-ost avoids most of this by doing the swap in a controlled instant with the same timeout discipline.

"When is online DDL in MySQL not actually online?"

Several operations still need a table copy or a lock.

Changing a column's data type, adding a column in the middle in versions before 8.0.29, changing the primary key, converting character sets, and adding a FULLTEXT or spatial index when one does not exist all use ALGORITHM=COPY or take a lock, and specifying LOCK=NONE makes them fail rather than silently lock, which is the point of writing it.

Even inplace operations rebuild the table for some changes, such as adding a column before 8.0's instant ADD COLUMN, which doubles disk usage temporarily and generates lag on replicas, where the DDL is replayed after the primary finishes.

The replication delay is the part people forget: a one-hour online ALTER on the primary becomes one hour of replica lag when it replays there.

Q90 · Scenario. "Writes to a core table have slowed and you find it carries 14 indexes accumulated over five years. How do you decide what to remove — safely?"

Reveal answer

Strong answer Every one of those 14 indexes is updated on every insert, so pruning is a genuine write-latency fix, but it has to be evidence-driven:

  1. Find never-used indexes from the engine's own counters. Postgres: SELECT indexrelname, idx_scan FROM pg_stat_user_indexes WHERE relname = 'orders' ORDER BY idx_scan — idx_scan = 0 means no query has used it since statistics were last reset, so first check how long that window is. MySQL: sys.schema_unused_indexes, built on performance_schema usage counters, with the same caveat about server uptime.
  2. Find redundant duplicates by prefix analysis — (a) shadowed by (a, b), exact duplicates under different names. On MySQL, pt-duplicate-key-checker automates this; on Postgres a catalog query over pg_index does.
  3. Before dropping, check the blind spots: read replicas serve different queries and (in Postgres) keep their own usage counters, so I check every replica, not just the primary; monthly and quarterly jobs may use an index that looks dead for weeks; and unique indexes enforce constraints — they stay regardless of scan counts.
  4. Drop one at a time with the recreate statement ready. Postgres 12+ lets me rehearse safely: ALTER INDEX ... SET (deprecated) is not a thing, but marking it invisible-equivalent via begin; drop; explain; rollback; tests plans transactionally — and MySQL 8 has true ALTER TABLE ... ALTER INDEX ... INVISIBLE, which hides the index from the planner while still maintaining it: watch for regressions for a week, then drop for real.

Going deeper The Postgres rehearsal step needs to be stated precisely, because the shape in the answer above is easy to get wrong in production.

BEGIN; DROP INDEX idx; EXPLAIN ...; ROLLBACK; does show what the planner would choose without the index, but DROP INDEX without CONCURRENTLY takes an ACCESS EXCLUSIVE lock on the whole table for the length of that transaction, which blocks every read and write on the table while the rehearsal runs — a few seconds of outage on a hot table, and a long one if the transaction is left open.

It is a technique for a replica or a maintenance window, not for a busy primary.

Postgres has no native invisible-index flag as of Aug 2026; the pragmatic alternatives are the community-known catalog hack UPDATE pg_index SET indisvalid = false WHERE indexrelid = 'idx'::regclass, which makes the planner ignore the index while writes keep maintaining it and is reversible by setting it back to true, or the hypothetical-index extension hypopg used in reverse to compare plans.

On MySQL 8.0 the invisible index is the safe primitive: ALTER TABLE t ALTER INDEX idx INVISIBLE, watch the digest table for a week, then DROP INDEX.

The verification step in both engines is the same: compare the mean time of every query on the table from pg_stat_statements or events_statements_summary_by_digest before and after, and revert on any regression.

Land it Let usage counters nominate and let a reversible step — invisible in MySQL, transactional rehearsal in Postgres — confirm; the win is real, but only the evidence keeps it safe.

Likely follow-ups
"You dropped an index and a monthly report started timing out three weeks later. Walk me through the recovery and the lesson."

Recovery first: get the report's query from the slow log or pg_stat_statements, confirm the plan now scans, and rebuild the index online — CREATE INDEX CONCURRENTLY or ALTER TABLE ... ADD INDEX ... ALGORITHM=INPLACE, LOCK=NONE — from the DDL I saved before dropping, which is why the recreate statement is kept in the change ticket.

If the build takes hours and the report is due, run the report on a replica or with a raised timeout as a stopgap. The lesson is the observation window: three weeks was too short for a monthly job.

The remedy is to hide before dropping — invisible on MySQL, indisvalid on Postgres — for a full business cycle, and to grep the scheduled-job code for the table name as a manual check on top of the counters.

"The idx_scan counters were reset last week. How long do you wait, and how do you speed up the evidence?"

A full cycle of every workload that touches the table: at least a month, longer if there are quarterly jobs.

To speed it up, I look for the index's usage in places other than live counters: the query fingerprints in pg_stat_statements or the digest table, matched against the index's columns, tell me which queries could use it; the scheduled-job code and report definitions tell me which run rarely; and replicas' counters, which are separate in Postgres, tell me about read traffic routed there.

If all of those show nothing plausible, I hide the index rather than drop it, which is reversible in seconds, and let the calendar run.

The counters are the evidence that the index is used; they are not evidence that it is unused until enough time has passed.

"What ordering would you drop the fourteen in, and how many at once?"

Exact duplicates first, because they are free wins with no risk; then prefix-redundant indexes whose wider sibling is used; then indexes with zero scans over a full cycle; and I never touch unique indexes or those backing constraints without a separate correctness discussion.

One at a time on a hot table, with a day between, so a regression can be attributed to a single change and reverted. Each drop is a migration with the recreate statement in the down script.

The write-latency win is measurable after each: I watch insert p99 and the table's index write counts.

Pruning fourteen to six is typical and often recovers thirty to fifty percent of write cost on the table, but the evidence trail is what makes it safe, not the speed.

"What would you cut if you had one day and the writes are causing an incident right now?"

I would not drop anything blind in an incident.

In one day I can run the duplicate-key checker and drop exact duplicates, which is safe by construction, and I can make the clearly-redundant prefix indexes invisible on MySQL or invalid on Postgres, which removes their planner use but not their write cost — so it does not help the incident.

The write cost only drops when an index is actually dropped, and dropping needs the observation evidence. So for the incident itself I would look elsewhere: is the write slowness really the indexes, or is it lock waits, a full-scan UPDATE, or replication lag pausing commits?

If it truly is fourteen indexes, the honest one-day answer is exact duplicates gone, invisibility on the rest, and the drops scheduled with evidence.

Q91 · Scenario. "An index on a high-churn Postgres table has grown to three times the size of the data it indexes. What happened, and what do you do about it?"

Reveal answer

Strong answer That is index bloat — pages that belong to the index but hold mostly dead or empty space. It accumulates because B+tree pages split as data churns but never merge back: deletes leave gaps vacuum can reclaim as free space inside the index, yet the pages themselves stay allocated, and a page split caused by a long-gone workload is permanent. High-churn patterns — queue tables, rolling deletes by date on an index whose key keeps advancing — are the classic producers.

  1. Measure before acting: the pgstattuple extension's pgstatindex() reports avg_leaf_density — around 90% is healthy (matching the default fillfactor), while 20–30% confirms serious bloat worth fixing because it wastes cache and deepens scans.
  2. Fix: REINDEX INDEX CONCURRENTLY idx_name (Postgres 12+) rebuilds it compactly without blocking writes. Plain REINDEX blocks and is for maintenance windows only.
  3. Mitigate the recurrence: Postgres 14+ btree improvements (bottom-up deletion) reduce churn bloat considerably, so version matters; tuning autovacuum to keep up on that table helps too.
  4. MySQL side: InnoDB indexes fragment rather than bloat in the MVCC sense; OPTIMIZE TABLE — effectively an online table-and-index rebuild — compacts them.
  5. Honesty: I would not chase 100% density. Fill factor deliberately leaves slack so future inserts do not split pages immediately; rebuilding an index that is 85% dense buys nothing.

Land it B+trees split but never un-split, so churn ratchets size upward — measure density, rebuild concurrently when it is genuinely low, and let fillfactor keep its working slack.

Likely follow-ups
"You ran REINDEX CONCURRENTLY and the index is the same size a week later. What next?"

Then the rebuild treated a symptom and the producer is still running.

I would look at what churns the table: pg_stat_user_tables gives n_tup_upd, n_tup_del and n_tup_hot_upd, and if updates dominate with few HOT updates, every update is writing a new index entry because the updated row moved to a new page or an indexed column changed.

The fixes are a lower fillfactor on the table, around 70, so updated rows can stay on the same page and qualify as HOT updates that do not touch the index, and removing indexes on columns that change constantly.

Then I would check whether autovacuum is keeping up with last_autovacuum and dead tuple counts; if it is not, per-table settings such as autovacuum_vacuum_scale_factor = 0.02 make it run more often.

If the table is a queue, a queue table is the wrong tool and the real fix is a queue.

"Why do B-tree pages split but never merge? Is that a Postgres flaw?"

It is a deliberate trade in most B-tree implementations, not a flaw.

Merging two half-empty pages when a delete drops occupancy needs locks on both siblings and the parent, and it can flap: a page merges, the next insert splits it again, and the workload pays for both.

So Postgres only removes a page when it becomes completely empty and vacuum can unlink it, and it leaves partially empty pages alone. That is fine for tables where keys are reused, since the gaps refill.

It is bad for a monotonically advancing key with rolling deletes, because the old range never receives inserts again and its pages sit at low density forever. Postgres 14's bottom-up deletion helps a different case, duplicates from updates, by clearing dead entries before a split.

The design is reasonable; the operational duty it leaves you is to measure density and rebuild when a range has been abandoned.

"What does the bloated index actually cost at run time, in numbers?"

Three things.

Cache: the index takes three times the shared buffers it should, and every page it holds is a page of table data that got evicted, so the visible symptom is a lower buffer hit ratio in pg_statio_user_indexes and more reads from disk for unrelated queries.

I/O per scan: a range scan reads leaf pages in order, and at 30 percent density it reads three pages for the rows one page should hold, so a query that touched 10 leaf pages now touches 30.

Depth: a bloated tree occasionally gains a level, which adds one more page read to every lookup, though that is rare. Write amplification follows too, since each modified leaf is a full page in WAL on first touch after a checkpoint.

I would quantify with EXPLAIN (ANALYZE, BUFFERS) before and after the rebuild and compare shared hits and reads for the same query.

"REINDEX CONCURRENTLY failed halfway. What is left behind, and how do you clean up?"

An invalid index.

The concurrent rebuild creates a new index alongside the old one, and if it is cancelled, hits a deadlock, or the session drops, the new one stays in the catalog marked invalid, which means it is maintained on every write but never used for reads, so it is pure cost.

I would find it with SELECT indexrelid::regclass FROM pg_index WHERE NOT indisvalid, and the name typically ends in _ccnew. Cleanup is DROP INDEX CONCURRENTLY on the invalid one, then rerun the rebuild.

The common causes of failure are a long-running transaction holding a snapshot the rebuild must wait for, and lock timeouts, so before retrying I would check pg_stat_activity for old transactions and set lock_timeout on the rebuild session so it fails fast rather than blocking a queue of writers behind it.

"How would you keep this from being found by accident next time?"

With a scheduled check and a threshold. A weekly job runs pgstatindex on every index above a size floor, say 1 gigabyte, since small indexes do not matter, and records avg_leaf_density and size in a metrics table or pushes it to Prometheus.

An alert fires when density is below 50 percent and the index exceeds twice the size of the data it indexes, computed from pg_relation_size of the index against the table.

Because pgstatindex reads the whole index, I would run it on a replica or in a low-traffic window, or use the cheaper estimate from the pgstattuple_approx function.

The alert should link to a runbook that says when to rebuild, and the rebuild itself becomes a routine ticket rather than an emergency, which is the point.

Q92 · Scenario. "A cleanup job ran DELETE FROM events WHERE created_at < '2025-01-01' — 10 million rows in one statement. The app started timing out and replicas fell behind. Explain the damage and the right way to do it."

Reveal answer

Strong answer One giant transaction is the whole problem.

In InnoDB, every deleted row is recorded in the undo log — the journal that lets the transaction roll back and lets older transactions still see the rows — so 10 million deletes build a mountain of undo that the purge thread must digest, and if the statement is killed, rollback replays it all, often slower than the delete.

Row locks are held on everything touched until commit, which is what the app's timeouts were. In Postgres, the equivalent damage is a flood of WAL plus 10 million dead tuples for vacuum, and long snapshot pins that stall cleanup elsewhere.

Replicas lag for the same reason: replication ships the transaction as a unit, and replicas cannot apply a 10-million-row transaction incrementally — they stall, then apply it in one indigestible lump.

The fix is chunking — many small transactions:

chunked-delete.sql
-- MySQL: loop until affected rows = 0, commit each pass,
-- sleep ~100ms between passes
DELETE FROM events WHERE created_at < '2025-01-01' LIMIT 10000;

-- Postgres has no DELETE ... LIMIT; use ctid (the row's
-- physical address) via a subquery, same loop:
DELETE FROM events WHERE ctid IN (
  SELECT ctid FROM events
  WHERE created_at < '2025-01-01' LIMIT 10000);

Each chunk commits quickly, so locks are held for milliseconds, undo/WAL stays small, purge and vacuum keep pace, and replicas absorb bite-sized transactions — the sleep between passes is deliberately giving them and the app room to breathe. Prevention: for date-based retention, partition by time and DROP PARTITION — deleting a billion rows becomes a metadata operation.

Land it Databases digest many small transactions far better than one huge one — chunk with a limit, commit, sleep, repeat; and if the purge is calendar-shaped, partitioning deletes for free.

Likely follow-ups
"The chunked delete is running and replicas are still lagging. What next?"

Then the chunks are too big, the sleep is too short, or replication is the bottleneck for a different reason. I would check replica lag directly, Seconds_Behind_Source on MySQL or pg_stat_replication write and replay lag on Postgres, and correlate it with the loop's cadence.

If lag rises during each chunk and recovers during the sleep, I would halve the chunk to 2,000 rows and lengthen the sleep, or make the loop adaptive by reading lag before each pass and pausing when it exceeds a threshold, which is what tools like pt-archiver do with --check-slave-lag.

If lag rises steadily regardless, the replica is applying single-threaded and the deletes are one of several writers; on MySQL replica_parallel_workers and replica_parallel_type=LOGICAL_CLOCK let it apply in parallel. Postgres replays WAL in one process, so the only lever there is less WAL per second.

"Why can Postgres not do DELETE ... LIMIT, and does the ctid subquery have any risk?"

The SQL standard has no LIMIT on DELETE, and Postgres follows the standard here while MySQL added the extension.

The ctid workaround selects physical row addresses for a batch and deletes those, which is safe within one statement because the subquery and the delete see the same snapshot.

The risk is only if you fetch ctids in one statement and delete in another, since a concurrent update or vacuum can move a row and the ctid then points at a different tuple; keep it in one statement.

Two refinements: add an index on created_at so the subquery seeks instead of scanning, and order by created_at so deletes proceed through the index in order, which keeps the working set of pages small. Postgres 15 and later can also use DELETE ... WHERE id IN (SELECT id ... ORDER BY id LIMIT n) on the primary key, which many teams find clearer.

"How do you size the chunk and the sleep?"

By measurement, starting conservative.

I begin with 5,000 to 10,000 rows and 100 milliseconds and watch three numbers for a few minutes: chunk duration, which should stay under about 200 milliseconds so locks are short; replica lag, which should stay flat; and application p99, which should not move.

If all three are calm I double the chunk until one of them reacts, then back off.

The sleep is there to yield to the application and the replicas, and a useful rule is sleep roughly as long as the chunk took, so the delete uses no more than half the write bandwidth.

On InnoDB I also watch History list length in SHOW ENGINE INNODB STATUS, which is the undo backlog; if it climbs, purge is not keeping up and the loop needs to slow down. The whole job then takes longer, which is fine.

"The statement was already killed. What happens now, and can you speed the rollback?"

On InnoDB, the rollback undoes every change from the undo log and it is often slower than the forward delete, because it runs single-threaded and the pages it needs may have been evicted.

There is no safe way to skip it; killing the server mid-rollback just resumes the rollback at startup, holding the table back for the same time.

What you can do is stop making it worse: pause the application's writers to the table, raise innodb_purge_threads if the purge is the bottleneck afterwards, and wait. Progress is visible in SHOW ENGINE INNODB STATUS under the transaction as "rolling back" with a row count.

On Postgres, rollback is instant because dead tuples are simply left for vacuum, but the 10 million dead tuples still need a vacuum pass, and the long transaction has already held back cleanup across the database while it ran.

"How would you set up partitioning so this never has to be a delete?"

Range-partition by month on created_at: in Postgres, CREATE TABLE events (...) PARTITION BY RANGE (created_at) with one child table per month, created ahead by a scheduled job or by the pg_partman extension, and retention becomes DROP TABLE events_2024_12 or DETACH PARTITION ... CONCURRENTLY for a keep-then-archive step.

MySQL does the same with PARTITION BY RANGE (TO_DAYS(created_at)) and ALTER TABLE ... DROP PARTITION. Both are metadata operations that free the space without touching a row.

The constraints to know: the partition key must be part of every unique constraint, so a primary key on id alone becomes (id, created_at); and queries need created_at in their WHERE clause to prune, otherwise they scan every partition.

The migration to a partitioned table on a live system is itself a project, done by creating the new table and copying in chunks.

Q93. "Why is LIKE 'abc%' fine for an index but LIKE '%abc' fatal? And is the fine one always fine?"

Reveal answer

Strong answer The asymmetry is just sort order.

A B+tree keeps strings sorted left to right, so every string starting with abc lives in one contiguous stretch of the index — the engine rewrites LIKE 'abc%' into the range >= 'abc' AND < 'abd' and range-scans it.

A leading wildcard destroys that: strings ending in abc are scattered arbitrarily through the sorted order, so there is nowhere to seek — full scan, and the trigram/full-text answers from the search question apply instead. The "always fine?

" trap has a real answer: in Postgres, a plain btree serves LIKE 'abc%' only when the index sorts bytewise — the C collation.

Under a typical linguistic locale like en_US.UTF-8, the comparison rules do not guarantee the prefix-range equivalence, so the planner will not use the index for LIKE; the fix is a second index created with text_pattern_ops (or varchar_pattern_ops), which sorts for pattern matching.

MySQL's common collations do not have this trap for LIKE prefixes, so the surprise is Postgres-specific and worth knowing before it costs you an afternoon.

Land it A trailing wildcard is a disguised range scan and a leading one is a scattered search — and on Postgres, remember text_pattern_ops, or your "fine" prefix LIKE quietly full-scans anyway.

Likely follow-ups
"How do you tell which collation your columns are actually using, and what does text_pattern_ops cost?"

SHOW lc_collate gives the database default and SELECT datcollate FROM pg_database confirms per database; a column can override it, visible in \d+ table or pg_attribute.attcollation. If it says anything other than C or POSIX, a plain btree will not serve prefix LIKE.

The text_pattern_ops index costs the same disk and write overhead as any second btree on the column, and it cannot be used for ordinary ORDER BY or range comparisons under the linguistic collation, so you may end up with two indexes on one column.

As of Aug 2026 a cleaner option in Postgres 12 and later is a nondeterministic-free collation on the column itself, COLLATE "C", so one index serves both, at the price of bytewise sort order in the application, which for identifiers and emails is usually what you want anyway.

"What if the prefix is very short, like LIKE 'a%'? Is the index still used?"

The planner decides by selectivity, not by the presence of a wildcard.

A one-letter prefix matches a large share of rows, and the planner will estimate that share from the column's histogram and choose a sequential scan if the index would return, say, more than a few percent of the table, because random page reads for that many rows cost more than reading the heap in order.

So the index is available but not chosen, which is correct. I would verify with EXPLAIN on both a short and a long prefix and expect the plan to flip between Seq Scan and Index Scan.

If the application allows one-character searches, the honest fix is a product rule requiring three characters, or a trigram index with pg_trgm, which handles short and infix patterns at the cost of a larger index.

"Does the same rewrite apply to case-insensitive searches, ILIKE or LOWER?"

Not directly. ILIKE 'abc%' cannot use a plain btree at all, because the index is sorted case-sensitively and the matching rows are not contiguous.

The options are an expression index on lower(email) queried with lower(email) LIKE 'abc%', which needs the same text_pattern_ops consideration under a linguistic collation; the citext extension type, which compares case-insensitively but again cannot serve LIKE prefixes from a btree; or a trigram GIN index, which serves ILIKE with any wildcard placement and is the usual answer for search boxes.

MySQL's default collations are case-insensitive, so LIKE 'abc%' already matches both cases and uses the index, which is a convenience and a portability trap in the same feature. The rule is that the index must be sorted by exactly the expression the predicate compares.

"Where does the trigram index fit, and what does it cost compared with the btree?"

A trigram index from pg_trgm breaks each string into overlapping three-character pieces and stores an inverted list from each piece to the rows containing it, so any LIKE or ILIKE pattern with at least three consecutive literal characters can be answered by intersecting lists, then rechecking the candidates against the real pattern.

It serves leading wildcards, infix searches, and similarity queries.

The cost is size, typically two to four times the btree for the same column, slower writes because every insert updates many posting lists, and lookup times that depend on how common the trigrams are; a pattern like '%the%' matches almost everything and the recheck dominates.

I would use it for search boxes over names and descriptions, keep the btree for exact and prefix lookups on identifiers, and check the recheck count in EXPLAIN ANALYZE as the health signal.

Q94 · Scenario. "A Postgres report query's plan shows Sort Method: external merge Disk: 210MB. What does that line mean, and what are your options?"

Reveal answer

Strong answer It means the sort did not fit in memory. Postgres gives each sort or hash operation up to work_mem — the per-operation memory budget, default just 4 MB — and when the data exceeds it, the sort spills: it writes sorted runs to temporary files on disk and merges them, here 210 MB worth. Disk sorts are an order of magnitude slower than in-memory ones, so this line often is the runtime.

  1. Best option: make the sort disappear. If an index can deliver the rows in the required order — the WHERE-plus-ORDER-BY index from the LIMIT discussion — there is nothing to spill.
  2. Next: shrink the sorted set — sort after filtering and aggregation rather than before, and drop unneeded wide columns from what is being sorted.
  3. Only then: raise the budget, surgically. SET work_mem = '256MB' for the reporting session or role, not globally — the trap is that work_mem is per sort node, per query, per connection: 200 connections each running a query with two sorts at a global 256 MB is a recipe for the OOM killer. Session-scoped settings for the reporting role give the big sorts memory without arming that bomb.
  4. The MySQL parallel: sort_buffer_size bounds in-memory filesort; Using temporary plans spill to disk when implicit temp tables outgrow tmp_table_size/max_heap_table_size. Same triage: avoid, shrink, then fund.

Land it "External merge" means the memory budget lost to the data — the senior order is avoid the sort, shrink the sort, and only then raise work_mem, scoped to the session that needs it.

Likely follow-ups
"You raised work_mem for the reporting role and the sort still spills. What next?"

First I check the setting reached the session: SHOW work_mem inside the report's connection, because a pool that resets session state or a connection reused from a different role can silently drop it.

Then I read the plan for the actual size: EXPLAIN (ANALYZE, BUFFERS) shows the sort's memory or disk figure, and if the data is 800 megabytes, 256 will never do; the sort needs roughly the width of the sorted rows times the row count plus overhead.

Then I ask whether the sort input is wider than it needs to be, because sorting a hundred columns to return five is the usual reason; sorting only the key and an id, then joining back for the rest, cuts the sorted volume tenfold.

Parallel sort in Postgres 11 and later splits a large sort across workers, each with its own work_mem, if max_parallel_workers_per_gather allows. Only after those would I consider a larger budget.

"Why is work_mem per operation and not per query, and how do you compute the real worst case?"

Because the executor allocates memory node by node as the plan runs, and each sort, hash join, or hash aggregate node gets its own allowance; a plan with three such nodes can use three times work_mem, and with parallel workers each worker gets the allowance too.

The worst case is work_mem times the number of memory-using nodes times parallel workers times concurrent sessions. With 200 connections, a plan with two sorts, and two workers, 256 megabytes becomes potentially 200 gigabytes, which is why the global setting stays small.

In Postgres 13 and later, hash_mem_multiplier gives hash nodes a separate multiple, defaulting to 2, so hash joins get more room without raising sorts.

I would read EXPLAIN for the node count before deciding any value, and set it on the role with ALTER ROLE reporter SET work_mem = '256MB' so it applies only to that workload.

"How would you build the index that removes the sort, and what if the query has a filter and an order on different columns?"

The index must lead with the equality filter columns, then the ORDER BY columns in the same direction, so the index scan produces rows already in order and the planner drops the Sort node. For WHERE region = ? ORDER BY created_at DESC that is CREATE INDEX ON orders (region, created_at DESC).

If the filter is a range, such as a date window, and the order is on a different column, the index cannot serve both, because within a range the rows are ordered by the range column, not by the sort column; then the choice is to make the sort small by filtering tightly, or to accept the sort with enough memory.

A partial index, WHERE status = 'open', shrinks the sort input when the report only ever covers a subset. I would verify by checking that the new plan says Index Scan Backward with no Sort node and that the buffers read dropped.

"Where do the temp files go, and can they take down the server?"

Into base/pgsql_tmp under the data directory, or into the tablespaces listed in temp_tablespaces, which is worth setting to a separate volume so a runaway sort fills that disk rather than the one holding WAL and data.

A sort that spills gigabytes across many sessions can fill the volume, and if that volume is shared with WAL the server stops accepting writes, which is the failure to fear.

The guard is temp_file_limit, which caps the temporary space one session can use and cancels the query when exceeded; a value like 10 gigabytes is a sensible ceiling for a reporting role.

I would also enable log_temp_files = 0 so every spill is logged with its size, which is the cheapest way to find which queries need attention, and put a disk usage alert on the temp volume.

"What does the MySQL version of this triage look like in practice?"

EXPLAIN shows Using filesort when an ORDER BY cannot be satisfied by the index, and Using temporary when a GROUP BY or DISTINCT needs an intermediate table.

Whether the filesort spilled is visible in the session status counters Sort_merge_passes, which counts on-disk merge passes and should stay near zero, and Created_tmp_disk_tables for temp tables that outgrew memory.

The memory knobs are sort_buffer_size per session, which should not be set large globally for the same multiplication reason as work_mem, and tmp_table_size together with max_heap_table_size, the lower of which bounds in-memory temp tables. MySQL 8 uses the TempTable engine with temptable_max_ram as the global pool.

The order is the same: an index that delivers order, a smaller sorted set, then more memory for the session that needs it.

Q95. "What is your position on optimizer hints — FORCE INDEX and friends?"

Reveal answer

Strong answer Last resort, used with a written apology. The mechanics first: MySQL has FORCE INDEX/IGNORE INDEX plus a family of /*+ ... */ optimizer hints for join order and strategies.

Postgres deliberately ships no hints — the project's stance is that a wrong plan is a planner or statistics bug to be fixed, not painted over — and the pg_hint_plan extension fills the gap where operators disagree.

My reasoning for restraint: a hint freezes today's plan against today's data. Data grows and skews, and the hinted plan quietly becomes the wrong one — but now the planner is forbidden from saving you, and the failure is silent until it pages someone.

So my order of attack is: fix statistics (ANALYZE, extended statistics for correlated columns), fix the query shape, fix the index.

If a hint is genuinely the only bridge — say, waiting on an engine upgrade — I ship it with a comment explaining exactly why, a ticket to remove it, and a note in the runbook.

Land it A hint is a bet that the data will never change — take it only as a documented, ticketed bridge while the real cause gets fixed.

Likely follow-ups
"Give me a concrete case where the planner was wrong and statistics could not fix it."

Correlated columns with a skewed join. A query filtered on country = 'NL' and city = 'Amsterdam': the planner assumes the two predicates are independent and multiplies their selectivities, estimating far fewer rows than reality, and picks a nested loop that runs for minutes.

Extended statistics, CREATE STATISTICS ON country, city FROM addresses followed by ANALYZE, fix that case.

The one that resisted was a parameterised query where one parameter value matched 60 percent of the table and the rest matched a handful; a generic plan chosen after five executions was right for the common values and catastrophic for the big one.

The fix was not a hint but plan_cache_mode = force_custom_plan for that session, so each execution planned with the actual value. Hints would have frozen one of the two wrong choices.

"How do you make sure a hint you shipped actually gets removed?"

By making it impossible to forget. The hint sits next to a comment naming the ticket and the condition under which it should be removed, such as the upgrade to a specific engine version. The ticket has a due date and an owner.

A test in CI asserts the hinted query's plan shape, so if the planner starts choosing the right plan on its own after an upgrade, the test that checks the unhinted version passes and prompts the removal.

On MySQL, I would also add a monthly query in the review checklist: SELECT ... FROM performance_schema.events_statements_summary_by_digest WHERE DIGEST_TEXT LIKE '%FORCE INDEX%' to list hinted statements still running. For Postgres with pg_hint_plan, the hint table hint_plan.hints is itself a list to review.

A hint that outlives its ticket is a bug with a comment.

"What are the costs of running pg_hint_plan in production?"

It is an extension loaded through shared_preload_libraries, which means a restart to install and a compatibility check on every major version upgrade, since the extension must be released for the new version before you can move; that has delayed upgrades for teams I have seen.

It parses every statement for hint comments, which is a small but measurable overhead.

Hints in application code couple the code to the database engine and to the current table structure; drop or rename an index and the hint becomes a no-op with a warning nobody reads, or an error depending on settings.

And it hides planner problems that would otherwise be reported and fixed. The situations where it earns its place are a vendor application whose SQL you cannot change and a known regression in a specific version you are waiting to leave.

"The plan changed overnight with no deploy and a query got 50 times slower. Walk me through the triage before any hint."

A plan change without a code change comes from statistics, data volume crossing a threshold, or a configuration change.

I compare the plans first: pg_stat_statements shows the mean time jump, and if auto_explain is on with log_min_duration set, the log holds the slow plan; otherwise I run EXPLAIN ANALYZE now and compare with what the query used to do from a previous ticket or from a replica that has not been analysed.

Then I check pg_stat_user_tables.last_autoanalyze for the tables involved; a fresh analyse right before the change is the fingerprint of a statistics-driven flip, and a manual ANALYZE with a higher default_statistics_target on the skewed column often fixes it.

Then I check for recent index changes or a vacuum that changed the visibility map. A hint is the last move only if all of that leaves the planner still wrong.

Q96. "We store payloads in a JSON column and now need to query into them quickly. How do you index JSON in Postgres versus MySQL?"

Reveal answer

Strong answer The engines take opposite approaches.

Postgres indexes jsonb directly with a GIN index — the inverted index from the search discussion, here mapping keys and values to rows: CREATE INDEX ON events USING gin (payload jsonb_path_ops) serves containment queries like payload @> '{"type": "refund"}' across arbitrary keys.

For one known field queried with equality or ranges, a plain btree expression index — CREATE INDEX ON events ((payload->>'customer_id')) — is smaller and faster than GIN. MySQL cannot index a JSON column directly; the idiom is a generated column — a column computed from an expression — that extracts the field, with an ordinary index on it: ALTER TABLE events ADD COLUMN customer_id VARCHAR(36) AS (payload->>'$.customer_id'), ADD INDEX (customer_id); MySQL 8.0.17+ adds multi-valued indexes for JSON arrays.

The honest closing note both teams need: if a JSON field is filtered on in every hot query, it has earned promotion to a real, typed, constrained column — JSON is for the payload's long tail, not for your primary access paths.

Land it Postgres says "index the document" (GIN), MySQL says "extract then index" (generated column) — and both say a field you always query belongs in a real column.

Likely follow-ups
"What is the difference between jsonb_ops and jsonb_path_ops, and which do you choose?"

They are the two operator classes for a GIN index on jsonb. The default jsonb_ops indexes every key and every value as separate entries, so it supports the containment operator @> plus the key-existence operators ?, ?| and ?&.

jsonb_path_ops hashes each full path-to-value, so it supports only containment and the jsonpath operators, but the index is typically 20 to 30 percent smaller and containment lookups are faster because a query like {"type": "refund"} becomes one hash probe rather than two entries intersected.

I choose jsonb_path_ops when the queries are all containment on known shapes, which is most event tables, and jsonb_ops when the application asks "does this key exist" or searches values without knowing the key.

Both need a recheck on the heap, visible in EXPLAIN ANALYZE as Rows Removed by Index Recheck.

"How expensive is a GIN index to maintain on a table with heavy inserts?"

Expensive enough to plan for. Each inserted document adds an entry for every key and value, so a document with 40 fields is 40 posting-list updates.

Postgres softens that with the pending list: fastupdate, on by default, appends new entries to an unsorted buffer up to gin_pending_list_limit, 4 megabytes by default, and merges it into the main index later, either by vacuum or when the limit is hit.

The trap is that a lookup must also scan the pending list, so a full pending list makes reads slower, and the merge happens on the unlucky insert that crosses the limit, producing a latency spike.

For a heavy insert table I would raise the limit modestly, ensure autovacuum visits the table often so merges happen in the background, and measure with pgstatginindex, which reports the pending pages.

If writes dominate and queries are on two known fields, btree expression indexes are cheaper.

"What are the constraints on MySQL's generated column approach, and what about stored versus virtual?"

A virtual generated column is computed on read and takes no table space, but an index on it materialises the value in the index, so it can still be indexed since MySQL 5.7.

A stored generated column is written to the row and costs space but avoids recomputation and is required for some cases, such as being part of a primary key or for FULLTEXT. The expression must be deterministic, so no NOW() and no subqueries.

Extracting a JSON string yields a JSON-typed value that must be unquoted for a useful index, which is why the idiom uses ->> and casts to a typed column such as VARCHAR(36) or DECIMAL; a type mismatch between the column and the query's literal defeats the index silently.

Adding a virtual column is a metadata-only change, so it is instant online; adding the index is a normal online DDL. Multi-valued indexes for arrays require CAST(... AS UNSIGNED ARRAY) and serve MEMBER OF and JSON_CONTAINS.

"How do you verify the JSON index is actually used, and what query shapes defeat it?"

With EXPLAIN ANALYZE and by looking for a Bitmap Index Scan on the GIN index or an Index Scan on the expression index, with the recheck count.

What defeats a GIN containment index is using the wrong operator: payload->>'type' = 'refund' is an expression, not containment, so a GIN index on the column does nothing for it; it needs either the expression index on that exact expression or a rewrite to payload @> '{"type":"refund"}'.

Range comparisons on a JSON number, such as amount greater than 100, are not containment either and need an expression btree with a cast, ((payload->>'amount')::numeric), and the query must use the identical cast.

In MySQL, the generated column is used only when the query's expression matches the column definition character for character, or when the query references the column by name, which is the more robust way to write it.

"When would you keep the field in JSON instead of promoting it to a column?"

When the field is sparse, optional, or varies by event type, so a column would be null for most rows and the schema would grow a column per variant.

Also when the field is queried rarely, in ad hoc analysis rather than the hot path, since an expression index can serve occasional queries without changing the row shape.

And when the payload is owned by another system whose format changes without notice, so a typed column would break on the next version.

The promotion criteria I use are that the field appears in a hot query's WHERE or JOIN, needs a constraint or foreign key, or needs a type the database should enforce such as a date or a decimal.

Promotion is done by adding the column, backfilling in chunks from the JSON, dual-writing for a release, and then switching reads, which is the same expand-and-contract shape as any schema change.

Q97. "When does denormalizing, or a materialized view, beat adding more indexes?"

Reveal answer

Strong answer When the query's cost is in computation over many rows, not in finding rows.

An index makes locating rows cheap; it cannot make aggregating 50 million of them cheap — a dashboard that sums a year of orders by region touches most of the table no matter how it is indexed. At that point you precompute.

A materialized view is a query whose results are physically stored and refreshed on a schedule: in Postgres, CREATE MATERIALIZED VIEW ... ; REFRESH MATERIALIZED VIEW CONCURRENTLY ... — the CONCURRENTLY variant, which needs a unique index on the view, refreshes without blocking readers.

MySQL has no materialized views, so the same idea is a summary table maintained by a scheduled job, triggers, or application events.

The price is staleness: readers see data as of the last refresh, and that window must be an explicit product agreement — "revenue numbers are up to 15 minutes old" — not an accident someone discovers.

Denormalizing a hot column onto the read path is the same trade at row grain, paid for with dual-write consistency discipline.

Land it Indexes optimize finding; precomputation optimizes deriving — and the moment you precompute, staleness becomes a product decision that belongs in the requirements, not in the incident review.

Likely follow-ups
"REFRESH MATERIALIZED VIEW CONCURRENTLY is taking 40 minutes and the window is 15. What next?"

The concurrent refresh recomputes the whole view, diffs it against the old contents on the unique index, and applies the differences, so it is always slower than the query itself. If it cannot fit the window, the view is too big to rebuild wholesale.

The options, in order: make the underlying query faster with the same indexing and filtering work as any report; split the view into partitions by time so only the recent slice is refreshed, which Postgres does not support natively but a set of per-month views unioned by a plain view achieves; or replace the materialized view with an incrementally maintained summary table, updated by triggers or by the application on each write, or by a job that processes only rows changed since the last high-water mark.

As of Aug 2026 the pg_ivm extension provides incremental view maintenance for a restricted class of queries and is worth a look before building your own.

"How do you keep a denormalized column consistent when two code paths write the source?"

By putting the maintenance in the one place both paths must pass. The strongest option is a database trigger on the source table that updates the derived column in the same transaction, so consistency does not depend on which application path wrote.

The trade is that triggers are invisible to application developers and complicate bulk loads. The application option is a single repository method that owns the write and updates both, with a code review rule that forbids direct updates to the source elsewhere.

Either way, I add a reconciliation job that recomputes the derived value for a sample or for recently changed rows and reports mismatches as a metric, because dual-write bugs are found by measurement not by faith.

When the derived value is a count or a sum, a generated column or a materialized aggregate is preferable to hand-maintained arithmetic.

"What is the concrete cost of a materialized view beyond staleness?"

Storage equal to the result set plus its indexes; refresh load, which is a full query plus a diff every interval and competes with production traffic on the primary, since the refresh must run where the view lives; WAL volume, because the refresh rewrites the view and that is replicated to every replica; and a lock on the view during a non-concurrent refresh, which blocks readers for the duration.

There is also an operational cost: a materialized view depends on its source tables, so a column rename or type change in the source fails until the view is dropped and recreated, which surprises migrations.

And the unique index required for the concurrent refresh must be maintained. I would schedule the refresh off peak, monitor its duration as a metric with an alert when it approaches the interval, and document the dependency in the migration notes.

"How would you expose the staleness to the product so it is a decision rather than an accident?"

By making the freshness a value the API returns.

The refresh job records its completion time in a small table, or the view itself includes a refreshed_at column computed at refresh time, and the endpoint that serves the dashboard returns as_of in the response so the UI can display "updated 12 minutes ago".

The requirement is written as a number, such as data no older than 15 minutes during business hours, and an alert fires when the recorded age exceeds it, so a stuck refresh is an incident with a clear owner rather than a customer complaint.

For queries where a user has just written something and expects to see it, the read path checks whether the user's own last write is newer than the view's timestamp and, if so, reads the live tables for that user's slice. That is the read-your-writes pattern applied to precomputation.

Q98 · Scenario. "A team added five indexes to a slow search endpoint over two sprints and nothing improved. The query is WHERE upper(email) = ? OR phone = ? OR external_ref = ? with SELECT *. Diagnose."

Reveal answer

The real test Recognizing when the query, not the index inventory, is the problem — the "add an index" reflex versus reading the plan.

Strong answer Five indexes and no improvement means nobody read the plan — because the plan would have shown the indexes being ignored, and this query defeats them twice over:

  1. upper(email) wraps the column in a function, so the plain index on email is unusable for that branch — and one unusable branch of an OR forces a full scan for the whole predicate, since rows matching only that branch cannot be found any other way. The other four indexes never had a chance.
  2. So the fix is a rewrite, not a sixth index. Match the expression — an expression index on upper(email), or better, store emails normalized at write time and compare directly. Then split the OR into a UNION of three single-predicate branches, each a clean index seek. Replace SELECT * with the columns the endpoint returns, opening the door to covering.
  3. Then remove: several of the five accumulated indexes are now redundant, and each is a standing write tax — the cleanup is part of the fix.
  4. The process lesson I would state in the retro: "slow query" should trigger EXPLAIN ANALYZE first, always. Indexes added without reading a plan are guesses, and each wrong guess makes every write slower while fixing nothing.

Land it An index cannot rescue a query written so no index applies — read the plan, rewrite the predicate to be seekable, and only then decide what deserves indexing.

Likely follow-ups
"You rewrote it as a UNION and it is still slow. What next?"

I would read the new plan branch by branch.

UNION without ALL adds a sort or hash to remove duplicates across the three branches, and with SELECT * that deduplication is over wide rows; UNION ALL with a final DISTINCT ON the primary key, or simply accepting that a row matching two predicates appears twice and deduplicating in the application, removes it.

Then each branch: the upper(email) branch needs the expression index and the query must use the identical expression, including the same function and no extra cast; the phone branch may be defeated by a type mismatch if the parameter is bound as an integer against a text column; and external_ref may be low-cardinality with many nulls, where a partial index WHERE external_ref IS NOT NULL helps.

Finally the parameter binding: a prepared statement with a generic plan may not use the index at all, which EXPLAIN ANALYZE with real values would hide.

"Why can Postgres sometimes handle an OR across indexes, and when does it not?"

Postgres has BitmapOr: it can scan each usable index for its branch, build a bitmap of matching pages for each, OR the bitmaps together, and then read the heap once. So an OR where every branch has a usable index can be efficient without a rewrite.

The plan node to look for is BitmapOr under a Bitmap Heap Scan. It fails when any branch has no usable index, as with upper(email) and only a plain index, because then the whole thing must scan.

It is also less attractive when the branches return many rows, since the bitmap becomes lossy above work_mem and the heap scan must recheck every row on the flagged pages. MySQL has the equivalent, index_merge with Using union in the plan.

The UNION rewrite is still worth doing because it gives each branch its own plan and makes LIMIT and ORDER BY behave predictably.

"Which of the five indexes do you drop, and how do you do it safely?"

I would list them with pg_stat_user_indexes and its idx_scan counter reset at a known date, and with pg_index to spot duplicates and prefixes, since two indexes where one's columns are a leading prefix of the other's make the shorter one redundant for most queries.

Anything with zero scans across a full business cycle, including month-end, is a candidate.

Safely means one at a time: on Postgres 16 and later I can hide an index from the planner without dropping it, or on older versions I rename it to a marker and watch the slow query log for a week, and then DROP INDEX CONCURRENTLY.

MySQL 8 has invisible indexes, ALTER TABLE ... ALTER INDEX idx INVISIBLE, which is the same trial. Recreating an index on a large table takes time, so the trial period is the cheap insurance against a query that runs only quarterly.

"What is wrong with SELECT * here beyond covering, and how do you fix it with an ORM?"

Three things.

It pulls every column including any wide text or JSON payload, so each matching row is more bytes over the network and more memory in the application; it defeats covering, as the answer says; and it makes the query silently change behaviour when a column is added, which has broken deserialisation more than once.

With JPA the fix is a projection: a constructor expression SELECT new CustomerSummary(c.id, c.email, c.name) FROM Customer c WHERE ..., or a Spring Data interface projection, so the generated SQL names the columns. With MyBatis or jOOQ it is simply listing them.

I would also consider the endpoint's real need: a search returns a summary list, and the detail page fetches the full row by id, which is two cheap queries instead of one expensive one.

The verification is the plan showing an Index Only Scan for the branches that can now be covered.

"How do you make sure the retro lesson sticks?"

With a mechanism, not a slide. The pull request template for anything under the repository or migration directories gets a required field for the plan output of the affected query, before and after, pasted from EXPLAIN (ANALYZE, BUFFERS) against a database with production-like row counts.

A CI job runs the slow-query suite against a seeded database and fails if a query's buffer count regresses beyond a threshold, which catches the case where an index is removed or a rewrite loses its seek.

Index additions require the same evidence as any other change, including the write-cost line: how many writes per second the table takes and what one more index adds.

And the metric that made this incident visible, the endpoint's p99, gets an owner and an alert, so the next regression is caught in hours rather than sprints.

Q99. "Covering indexes are great — so why not just make every index cover everything?"

Reveal answer

Strong answer Because every column added to an index is paid for on every write and in every byte of cache, forever.

A "fat" index that covers everything approaches a second copy of the table: inserts write it in full, updates to any included column must maintain it, and it competes with the actual hot data for buffer pool space — you can make reads of one query faster while making the whole system's cache hit rate worse.

My judgment rule: covering is earned by measurement, not applied by default. I cover the two or three provably hottest queries — the ones at the top of the pg_stat_statements ranking — and leave the long tail to normal index-plus-row-fetch plans.

Mechanically, Postgres's INCLUDE clause helps contain the damage: included columns live only in leaf pages, keeping the searchable part of the tree compact; in MySQL, added columns widen the whole key, so the cost of fatness is higher and the bar should be too.

Land it A covering index is a hand-built read replica of part of your table — build a few where the read volume justifies the copy, not everywhere the idea would work.

Likely follow-ups
"Why is a Postgres index-only scan sometimes not index-only, and what do you do about it?"

Because Postgres keeps row visibility in the heap, not in the index.

An index entry cannot say whether the row is visible to the current transaction, so an index-only scan consults the visibility map, a bitmap with one bit per heap page saying every row on that page is visible to all transactions.

For pages where the bit is set, the heap is skipped; for pages where it is not, the executor fetches the heap row anyway.

That is the Heap Fetches line in EXPLAIN ANALYZE, and on a table with frequent writes it can be most rows, at which point the covering index gives you nothing.

Only vacuum sets the bits, so the fix is more frequent vacuum on that table, with autovacuum_vacuum_scale_factor lowered, and checking that Heap Fetches drops afterwards. MySQL does not have this problem because InnoDB stores versions in undo and the secondary index carries the primary key.

"How do INCLUDE columns behave differently from key columns, and are there limits?"

Included columns are stored only in leaf entries and are not part of the sort order, so they do not participate in searching, in uniqueness, or in the tree's internal pages; that keeps the upper levels small and lets a unique index cover extra columns without changing what is unique.

The limits are practical: an index entry must fit in about a third of a page, so wide included columns, such as long text, fail with an error at insert time; included columns cannot be expressions; and an update that changes an included column must update the index entry even though the key did not change, so the write cost is real.

MySQL has no INCLUDE, so the equivalent is adding the column to the key, which widens every level and affects uniqueness, which is why the bar for width should be higher there. SQL Server's INCLUDE is where the Postgres feature was borrowed from.

"How do you measure whether a covering index paid for itself?"

Before and after, on both sides of the trade. On the read side, the query's buffers and time from EXPLAIN (ANALYZE, BUFFERS), plus the plan node changing from Index Scan to Index Only Scan with low Heap Fetches, and the endpoint's p99 on the dashboard.

On the write side, the table's insert and update latency from the application's timer or from pg_stat_statements for the write statements, the index size from pg_relation_size, and the buffer cache hit ratio for the whole database, since a large new index evicts other data.

A covering index that cuts a top-ten query by 80 percent while adding two percent to writes is a clear win; one that speeds a query nobody runs while adding a gigabyte of cache pressure is a loss, and the same measurement shows it.

I record the numbers in the migration's description so the next person knows why the index exists.

"When would you pick a covering index over a materialized view or a cache?"

When the query is a lookup or a short range over a few rows, where the cost is finding and fetching rather than computing, and freshness must be immediate.

A covering index gives consistent results at transaction time with no refresh and no invalidation logic, which a cache and a materialized view both need.

A cache wins when the same key is read thousands of times per second and a stale answer for a few seconds is acceptable, because even an index-only scan costs a round trip and a few microseconds of CPU per read.

A materialized view wins when the query aggregates over many rows. The order I try is the index first, because it has the fewest moving parts, then the cache for pure hot-key traffic, then precomputation when the work is inherent.

I would not add a cache to a query that an index would fix, since the cache hides the fix.

Q100. "How do you manage index and schema changes as a team — what does good DDL hygiene look like to you?"

Reveal answer

Strong answer Every schema change lives in a versioned migration — Flyway or Liquibase in a Java shop — applied by the pipeline, never typed into a production console; the migration history is the only truthful answer to "what does prod's schema look like", and hand-applied changes are how staging and prod drift apart until a deploy fails mysteriously.

For each migration I think about the rollback before the roll-forward: dropping a new index is trivially reversible, but I stay aware that rolling back an index some fixed query now depends on re-creates the original incident — so "roll forward with a fix" is often the honest plan, written down in advance.

Two operational details seniors get right: CREATE INDEX CONCURRENTLY cannot run inside a transaction, and migration tools wrap migrations in transactions by default, so that migration must be explicitly marked non-transactional (and made idempotent, since a failed concurrent build leaves an invalid index behind).

And long builds on huge tables get scheduled and monitored as operations — announced, watched, and separated from application deploys — following expand-and-contract so code and schema never depend on landing in the same instant.

Land it Schema state you cannot reproduce from version control is an outage waiting for a trigger — migrations with rollback thinking are what make index work boring, and boring is the goal.

Likely follow-ups
"Show me exactly how you mark a concurrent index build in Flyway and Liquibase, and how you make it idempotent."

In Flyway a SQL migration runs in a transaction by default, and Postgres refuses CREATE INDEX CONCURRENTLY inside one, so the file needs -- flyway:executeInTransaction=false as its first line, or the global flyway.executeInTransaction=false, which I avoid because it changes every migration.

In Liquibase the changeset attribute is runInTransaction="false".

Idempotent means safe to rerun after a failure that left an invalid index: the statement becomes CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_name ON t (col), preceded by a step that drops the invalid leftover, DROP INDEX CONCURRENTLY IF EXISTS idx_name, guarded by a check on pg_index.indisvalid so a valid existing index is not dropped.

I would also set lock_timeout in the same migration so the build's brief exclusive locks fail fast rather than queueing behind a long transaction and blocking the application.

"What does expand and contract look like for renaming a column that the running application uses?"

Expand: add the new column, deploy application code that writes both old and new and reads the old, then backfill the new column in chunks so the table is never locked for long.

Switch: deploy code that reads the new column and still writes both, verify with a query that the two columns agree on a sample. Contract: deploy code that writes only the new column, then in a later migration drop the old one.

Each step is a separate release with a rollback path, and the schema is compatible with both the previous and the next application version at every point, which is what allows rolling deploys and instant rollbacks.

On Postgres, adding a nullable column with no default is a metadata change, and since version 11 adding one with a constant default is too; adding a NOT NULL constraint needs a validate step, ADD CONSTRAINT ... NOT VALID then VALIDATE CONSTRAINT.

"How do you stop a migration from locking the table for minutes in production?"

By knowing which statements take strong locks and by refusing to wait.

ALTER TABLE forms that rewrite the table, such as changing a column type, take an access-exclusive lock for the whole rewrite, and even a metadata-only change needs that lock briefly, which queues behind any running query on the table and then blocks every query behind it.

So every migration starts with SET lock_timeout = '5s', and a migration that fails on the timeout is retried in a quieter moment rather than allowed to stall the application. Rewrites are avoided by expand and contract, and new constraints use NOT VALID then VALIDATE.

On MySQL, ALGORITHM=INPLACE, LOCK=NONE on the ALTER asserts the operation is online and fails immediately if it is not, which is safer than discovering a copy. For very large tables, gh-ost or pt-online-schema-change do the change through a shadow table.

"How do you catch a dangerous migration in review before it reaches production?"

With a linter and a rehearsal. Tools such as squawk for Postgres and the strong-migrations pattern flag statements that take exclusive locks, add NOT NULL without a validate step, or build an index without CONCURRENTLY, and they run in CI on the migration files.

Then the pipeline applies every migration to a database restored from a recent production snapshot, or a subset with production-like row counts, and records how long each statement took and which locks it held, reading pg_locks during the run; a step over a threshold fails the build with the timing attached.

The review checklist asks for the rollback plan, the lock class, and whether the change is compatible with the currently deployed application version.

Migrations that touch a table above a size threshold get a scheduled window and a named operator watching, which is the part no tool replaces.

"Two engineers each wrote migration V42 on different branches. What happens, and how do you prevent it?"

Flyway applies versions in order and refuses to run a migration whose version is lower than the highest applied unless outOfOrder=true, so the second branch to merge fails at deploy with a validation error, or with duplicate-version detection if the numbers collide exactly.

Liquibase uses ids per file so collisions are on filenames instead.

Prevention is timestamp versions, V20260828143000__add_idx.sql, which almost never collide, plus a CI check that the branch's migrations sort after everything already on main; a simple script comparing the highest version in main with the lowest new one catches the case where a long-lived branch has an old timestamp.

Ordering still matters when two migrations touch the same table, so the pull request template asks whether another open change touches the same objects, and the deploy pipeline runs migrations from one place, never from two services sharing a database.

08 · DrillSchema Design, Scaling & Replication — Q101–Q150

This batch covers the questions that decide whether you can be trusted with the shape of the data itself: how you design tables, when you split them, when you copy them to more machines, and when you admit the relational database is the wrong tool. Interviewers use these to separate engineers who have operated databases from engineers who have only queried them. Every answer here is written to be said aloud, with the reasoning attached, because at the senior level the trade-off is the answer.

Drill · Schema design

These questions test whether your tables protect the business from bad data by design, or whether you rely on application code and hope.

Q101. "Walk me through first, second, and third normal form — but do it with a real table, not textbook definitions."

Reveal answer

The real test Whether you understand normalization as a tool for preventing update bugs, or whether you memorized definitions you cannot apply.

Strong answer I would evolve one orders table. Normalization is the process of restructuring tables so each fact is stored exactly once, which makes contradictory data impossible.

  • First normal form (1NF): imagine orders with a column items holding "laptop, mouse, cable" as one comma-separated string. Every cell must hold one atomic value, so I break the items out into an order_items table with one row per item. Now I can count, filter, and constrain items with plain SQL instead of string parsing.
  • Second normal form (2NF): suppose order_items is keyed by (order_id, product_id) and I also stored customer_name in it. That column depends only on order_id — part of the key, not the whole key. If the customer renames, I must update every item row and can miss some. I move customer facts up to orders.
  • Third normal form (3NF): suppose orders holds customer_id and also customer_city. City depends on the customer, not on the order — a dependency that passes through a non-key column. When the customer moves, old orders silently disagree with new ones. I move city into a customers table and keep only customer_id in orders.

Each step removes a place where the same fact could be written twice and drift apart — that drift is called an update anomaly.

Land it Normalization is not academic hygiene; it is the cheapest bug-prevention tool the database offers, and I normalize to 3NF by default and denormalize only with a measured reason.

Likely follow-ups
"You said you normalize to 3NF by default. What is Boyce–Codd normal form, and when does 3NF fail to catch a problem?"

Boyce–Codd normal form, or BCNF, is a slightly stricter version of 3NF. The rule is that every column that determines another column must itself be a candidate key.

3NF lets a non-key column depend on a key, but it still allows a case where part of a composite key depends on a non-key column. The classic example is a table of (student, course, instructor) where each instructor teaches exactly one course.

Instructor determines course, but instructor is not a key. 3NF accepts this table, and yet if the last student drops a course we lose the fact of which course that instructor teaches. BCNF splits it into (instructor, course) and (student, instructor).

In practice I rarely meet this case in business schemas, so I say 3NF as the default and BCNF when I notice a composite key with an internal dependency.

"Give me a concrete case where you deliberately broke 3NF and why."

A common one is storing the product price on the order line. Strictly, price depends on the product, not on the order line, so 3NF says keep it only in the products table.

But the price on an order is a historical fact: it is the price the customer agreed to at that moment. If the product price changes next week, the old order must not change with it.

So the copied column is not a redundant copy of one fact; it is a different fact, the price at time of sale. The second common case is a stored total for performance, as in the next question.

The rule I use is that denormalization is fine when the copy is a snapshot with its own meaning, or when I have measured a read cost and written down how the copy will be kept correct.

"How does normalization affect performance? People say normalized schemas are slow because of joins."

The join cost is real but usually small, because both InnoDB and Postgres join on indexed keys with nested-loop or hash joins that cost microseconds per row.

What normalization saves is often larger: rows are narrower, so more of them fit in the buffer pool or shared buffers, and updates touch one row instead of many. The slow cases are wide reports that join five or six tables and aggregate millions of rows.

For those I keep the normalized tables as the source of truth and build a reporting table or materialized view that is refreshed on a schedule.

I would rather pay for one extra join on the transactional path than debug drift across three copies of a customer's address.

"How would you check whether an existing schema has an update anomaly, without reading every line of code?"

I look for the same fact stored twice and then ask the database whether the copies agree. For example, if orders carry customer_city and customers also carry city, I run a query joining the two on customer_id and counting rows where the cities differ.

A non-zero count is a live anomaly. I do the same for any stored aggregate, such as comparing orders.total against the sum of order_items.

I also check for columns whose name repeats across tables, and for comma-separated values by searching for a comma in a column that should be atomic.

These checks take an afternoon and produce actual numbers, which is far more persuasive to a team than a lecture on normal forms.

Q102 · Scenario. "Your orders table carries a total column that should always equal the sum of its line items. Finance reports it drifts by a few rupees on some orders. Why does the column exist at all, and how do you keep it honest?"

Reveal answer

The real test Whether you understand deliberate denormalization: the read-path benefit, the update-anomaly price, and the mechanisms that pay it down.

Strong answer The column exists because someone denormalized on purpose: computing the sum on every read means joining and aggregating line items on every order-list page, and a stored total makes those reads one cheap row fetch. The price is exactly the bug we are seeing — two copies of one fact, and some code path updated the items without updating the total. I would work through it in order:

  1. Find the drift source. Search for every write path that touches order_items — including admin tools, bulk imports, and refund scripts — and check which ones recompute total. The one that does not is the bug.
  2. Decide the consistency mechanism. Three honest options. Application logic: update items and total in the same database transaction, ideally through one service method every caller must use — clear and debuggable, but every new code path can forget. A trigger — a small procedure the database runs automatically on each insert, update, or delete of order_items — cannot be bypassed, even by a manual SQL fix, but it hides logic inside the database where developers rarely look. Recompute on read: always derive the sum and drop the column, which is the only option with zero drift risk, at the cost of the read-path work we denormalized to avoid.
  3. Add a safety net either way. A nightly reconciliation job that compares total against SUM(line_amount) and alerts on mismatch turns silent corruption into a ticket.

My default: application logic inside one transaction, plus the reconciliation job; a trigger if out-of-band SQL writes are a real part of operations.

Land it Denormalization is borrowing read speed against consistency, and a senior always names the repayment plan — same-transaction updates plus a reconciliation check — before taking the loan.

Likely follow-ups
"You found the code path and fixed it. Finance says it still drifts. What next?"

Then I stop trusting my search and let the database tell me when the drift happens.

I add a temporary trigger on order_items that, after each insert, update, or delete, writes the order_id, the current total, the recomputed sum, the connection's user, and the application_name into a small drift_log table when the two disagree.

Within a day the log shows which user and which statement caused each mismatch. Often it is something outside the main service: a refund script run by support, a data import, or a rounding difference where one path rounds per line and another rounds the sum.

Rounding is a frequent hidden cause, so I also check that every path uses the same DECIMAL scale and rounding mode. Once the log is quiet for a week I remove the trigger or keep it as a permanent guard.

"Why not just use a generated column or a view for the total?"

A generated column cannot help here, because both MySQL and Postgres only allow generated columns to reference other columns in the same row, and the total depends on rows in a different table.

A view works: create a view orders_with_total that joins and sums the line items, and read from it. That removes drift completely, since there is no second copy.

The cost is that every read pays the aggregation, which is fine for a single order page and expensive for a list of a thousand orders.

A materialized view in Postgres gives a stored, indexable result, but it must be refreshed, and REFRESH MATERIALIZED VIEW CONCURRENTLY recomputes the whole thing, so it suits reporting, not a live order list.

So the honest options remain: view for correctness, stored column plus discipline for speed.

"Triggers versus application logic. Which would you actually choose, and what does the trigger cost?"

If I know that support staff and scripts write to order_items directly, I choose the trigger, because it is the only mechanism that covers every path.

The cost is measurable: each row change on order_items now runs an extra UPDATE on orders, which roughly doubles write work on that table and takes a row lock on the parent order for the rest of the transaction.

On a hot table that lock can create contention when many lines of the same order are inserted from separate transactions. There is also a debugging cost, because a developer reading the service code sees no total update and may add one, causing double work.

I mitigate that by documenting the trigger in the schema migration and adding a comment on the column. If all writes go through one service, I keep it in application code inside one transaction and rely on the reconciliation job.

"What does the nightly reconciliation job look like, and how do you keep it cheap on a large table?"

The core is one query: select order_id from orders joined to a grouped sum of order_items where orders.total differs from the sum.

On a large table I scope it to orders updated in the last two days using an index on updated_at, plus a full sweep once a week. I run it on a read replica so the primary never feels it.

The result goes to a small table with a timestamp, and an alert fires if the count is above zero. The job also writes a metric, so I can see the drift rate over time on a dashboard.

When the count is non-zero I do not auto-fix silently; I record the cases and repair them with a reviewed statement, because an auto-fix would hide the bug that is producing the drift.

Q103. "Surrogate keys versus natural keys — which do you use and why?"

Reveal answer

Strong answer A natural key is a real-world value that identifies the row — an email address, a national ID, an ISBN. A surrogate key is a meaningless identifier the system generates, like an auto-increment number. I default to surrogate keys for three concrete reasons.

First, natural keys change: users change email addresses, companies get renamed, and a primary key change ripples into every child table that references it as a foreign key — a column that must match a row in the parent table.

Second, natural keys are often composite and wide, and that whole width gets copied into every referencing table and every index on those references. Third, natural keys leak business assumptions — "email uniquely identifies a person" fails the day you support one person with two accounts.

The natural candidate still earns a UNIQUE constraint, because the business rule is real; it just should not be the join handle everything else hangs on.

Land it Surrogate key as the primary key, unique constraint on the natural key — you get stable joins and the business rule enforced, without betting your schema on the real world never changing.

Likely follow-ups
"Auto-increment or UUID for the surrogate key? Why?"

On a single primary I default to a BIGINT auto-increment, or an identity column in Postgres.

It is eight bytes, sorted by insertion time, so new rows land at the right edge of the clustered index in InnoDB and of the primary key B-tree in Postgres, which keeps inserts cache-friendly.

UUIDs are sixteen bytes, and a random UUIDv4 spreads inserts across the whole index, which hurts write throughput and cache locality, especially in InnoDB where the primary key is the physical row order.

If I need IDs generated by the application before the insert, or across multiple writers, I use UUIDv7, which puts a timestamp in the leading bits so values still arrive in near order.

Postgres 18, released in September 2025, has a built-in uuidv7() function as of Aug 2026.

"You said natural keys change. Give me a real example where a natural key looked stable and was not."

Email is the obvious one: a person changes jobs and wants their account under the new address. Less obvious is a country code, which teams treat as immutable; yet countries split, and ISO codes get retired. Phone numbers get reassigned to new people by carriers.

Even a government ID number can be reissued after fraud. In one system I saw, a product SKU was the primary key, and when the business re-coded its catalogue, every order line, inventory record, and report had to be rewritten in one weekend.

With a surrogate key that change is an UPDATE on one column in one table. The principle is that anything a human assigns can be changed by a human, so it should not be the value the database uses to link rows.

"Are there cases where you would use a natural or composite key as the primary key?"

Yes, for pure join tables and for immutable reference data.

A table linking users to roles, with columns (user_id, role_id), needs no separate ID; the composite key is the identity, it prevents duplicates, and in InnoDB it makes the row physically ordered by user_id, so "all roles for a user" is one range scan.

Reference tables such as currency codes, where the value is defined by an external standard and never changes, can also use the code directly. The test is whether the key is short, never edited, and never referenced by many child tables.

If a child table would have to copy a three-column composite key, I go back to a surrogate.

"What is the cost of a wide primary key in InnoDB specifically?"

In InnoDB the table is stored as a B-tree ordered by the primary key, and every secondary index stores the primary key value as its pointer to the row. So a 40-byte composite primary key is copied into every entry of every secondary index.

A table with five secondary indexes and a hundred million rows carries five hundred million copies of that key. That inflates index size, reduces how many entries fit per 16 KB page, and lowers the buffer pool hit rate.

A secondary index lookup also has to do a second descent into the primary key tree using that value. An eight-byte BIGINT keeps all of that small.

Postgres does not cluster by primary key, so the effect is weaker there, but the unique index on the key still grows.

Q104 · Scenario. "A security review flags that your order IDs are sequential — /orders/48211 — so anyone can enumerate them and estimate your sales volume. A teammate proposes switching the primary key to random UUIDs. What do you say?"

Reveal answer

The real test Whether you can separate the exposure problem from the key-design problem instead of solving one by creating another.

Strong answer The finding is real — sequential IDs let outsiders count your orders and guess valid URLs — but swapping the primary key to a random UUID (universally unique identifier, a 128-bit random value) overcorrects. In one line, because the deep dive belongs to indexing: primary-key order is physical storage order in InnoDB and insert order in every B-tree index, so fully random keys scatter every insert across the whole index and wreck cache locality. My actual proposal, in order of preference:

  1. Keep the internal auto-increment primary key and add a separate public identifier — a random token column with a unique index. URLs use the token; joins and foreign keys keep the compact ordered key. This fixes enumeration without touching storage behavior.
  2. If we genuinely need globally generated IDs — multiple writers, future sharding, IDs minted before insert — use UUIDv7, the newer UUID version whose leading bits are a timestamp, so values are time-ordered and insert near the right edge of the index like an auto-increment does, while still being unguessable in the low bits.
  3. Never UUIDv4 as an InnoDB primary key on a hot table; random 128-bit keys as the clustering key is the known worst case.

I would also note UUIDs are sixteen bytes against eight for a bigint, and in InnoDB the primary key is duplicated inside every secondary index, so the size tax multiplies.

Land it Enumeration is an exposure problem — solve it at the URL with a public token or UUIDv7, not by making every index pay for randomness forever.

Likely follow-ups
"Show me how you would generate and store the public token. How long does it need to be?"

I generate it in the application from a cryptographically secure random source, for example Java's SecureRandom producing 16 bytes, encoded as base62 or base32 so it fits in a URL without escaping.

Sixteen random bytes is 128 bits, which makes guessing a valid one effectively impossible even at millions of requests per second. I store it in a column such as public_id CHAR(22) with a unique index, and the API looks up by that column.

The unique index doubles as the guard against the tiny chance of a collision: the insert fails and the application generates a new token. I never expose the internal integer ID anywhere, including in logs sent to customers, otherwise the enumeration risk quietly returns.

"Explain exactly why UUIDv4 as an InnoDB primary key is bad. Numbers, please."

InnoDB stores the table itself in primary key order. With auto-increment, every insert goes to the last page, which is in memory, so a million inserts touch a few hundred pages. With random UUIDv4, each insert lands on a random page somewhere in the whole tree.

On a table whose index is 50 GB with a 20 GB buffer pool, most inserts miss the cache, read a page from disk, modify it, and later flush it, so one insert becomes two random I/O operations.

Pages also split constantly because inserts arrive in the middle, leaving pages half full, so the index takes roughly 1.5 times the space. The size tax stacks on top: 16 bytes instead of 8, copied into every secondary index.

Benchmarks routinely show several times lower insert throughput for UUIDv4 versus sequential keys on large InnoDB tables.

"Is the enumeration issue really a problem if the endpoint checks authorization?"

Authorization removes the data-leak part, since an attacker cannot open someone else's order.

It does not remove the information leak: the ID itself reveals your order volume, and the growth rate between two dates reveals your sales trend, which is the kind of thing competitors and investors would love.

Sequential IDs also make mistakes cheap to exploit; if one endpoint forgets the ownership check, an attacker can walk every ID in minutes. With random tokens, the same bug is still a bug, but exploiting it requires guessing tokens, which is infeasible.

So I treat authorization as necessary and the public token as defense in depth, and I would still make the change.

"The team went ahead and switched the primary key to UUIDv4 last year. How do you undo that safely?"

I would not rip out the UUID, because every foreign key references it. Instead I add a new BIGINT column, populate it from a sequence in batches, add a unique index on it, and then point the physical ordering at it.

In InnoDB that means making the BIGINT the primary key and the UUID a unique secondary key, which is a full table rebuild, so I do it with gh-ost or pt-online-schema-change to avoid locking.

Foreign keys can keep referencing the UUID column in the short term, since a unique index is enough to be a foreign key target, and I migrate them table by table.

If the table is small enough that the pain is not measurable, I leave it alone and only change the default for new tables, because a migration without a measured benefit is just risk.

Q105 · Scenario. "Finance says invoice totals are off by one or two paise on roughly one order in a thousand. The amounts are stored as FLOAT. Explain what is happening and how you fix it."

Reveal answer

The real test Whether you know why binary floating point cannot represent money, and whether your fix covers the Java side too.

Strong answer FLOAT and DOUBLE store numbers in binary fractions, and most decimal fractions have no exact binary form — 0.1 in binary is an infinitely repeating pattern that gets cut off. Each stored price is therefore off by a tiny amount, and sums, tax multiplications, and discounts accumulate those errors until a paisa appears or disappears. This is not a bug in the code; it is the data type doing exactly what it is defined to do.

  1. Fix the schema: change the columns to DECIMAL(19,4) in MySQL or NUMERIC(19,4) in Postgres — fixed-point types that store exact decimal digits, so 0.10 is exactly 0.10. The alternative with the same guarantee is storing integer minor units — paise or cents — in a BIGINT.
  2. Fix the Java side: map the column to BigDecimal, never double, or the driver converts the exact value back into the broken representation. Comparisons use compareTo, and every division states a rounding mode explicitly, such as RoundingMode.HALF_EVEN, so rounding is a business decision instead of an accident.
  3. Migrate carefully: the existing floats are already polluted, so I would reconcile against the source of truth — payment-gateway records — during the type migration rather than blindly casting.

Land it Money is decimal by law and binary floats are approximations by design — DECIMAL or integer minor units in the database, BigDecimal in Java, and the pennies stop wandering.

Likely follow-ups
"Why DECIMAL(19,4) and not DECIMAL(10,2)? Where do the numbers come from?"

The precision, 19, is the total number of digits, and the scale, 4, is how many sit after the decimal point.

Nineteen digits gives room for amounts in the quadrillions, which covers any real currency sum, including currencies like the Indonesian rupiah where a normal invoice already has ten digits.

Four decimal places matter because intermediate calculations, such as tax at 18 percent on a unit price times a quantity, produce fractions of a paisa, and rounding at two places on every step would compound error.

So I keep four places in storage and round to two only at the point where a money amount is presented or charged. A DECIMAL(19,4) in MySQL takes nine bytes, so the extra safety is nearly free compared with the four bytes of a FLOAT.

"Integer minor units versus DECIMAL. Which do you actually prefer, and why?"

For a single-currency system I like integer minor units, storing 12345 for 123.45 rupees, because a BIGINT is eight bytes, arithmetic is exact and fast, and there is no rounding to configure.

The weaknesses appear with multiple currencies, because the Japanese yen has zero minor units, the Bahraini dinar has three, and a column of integers no longer says what it means without a currency code beside it.

Percentage calculations also require care, since 12345 times 18 divided by 100 produces a fraction. DECIMAL keeps the value self-describing and handles fractional intermediates.

So my rule is integers when there is one currency and the model is simple, DECIMAL(19,4) when currencies vary or the domain has percentages and proration, and in both cases a currency column next to the amount.

"How do you migrate the existing FLOAT column without stopping writes?"

I use expand and contract. First I add amount_new DECIMAL(19,4), which is an instant metadata change on modern Postgres and MySQL. Then I deploy application code that writes both columns.

Then a batch job walks the table by primary key in chunks of ten thousand rows, setting amount_new to the value rounded to two places, but for anything financially important I reconcile against the payment gateway's records rather than trusting the float.

Then I switch reads to the new column, watch for a few days, and finally drop the old column in its own migration.

During the backfill I also produce a report of rows where the rounded float disagrees with the gateway by more than a paisa, because those are the invoices finance already noticed.

"Does the same problem exist in Java if the column is DECIMAL but the code uses double?"

Yes, and it is the more common way the bug comes back. The JDBC driver reads DECIMAL as BigDecimal, but if the entity field is declared double, the ORM converts it and the value becomes a binary approximation again.

Then the code adds, multiplies by a tax rate, and writes the result back, and the database stores the rounded garbage exactly.

So the type discipline has to run end to end: BigDecimal in the entity, BigDecimal in the DTO, and a rounding mode stated in every division and multiplication.

I add a unit test that multiplies 0.1 by 3 and expects 0.3, which fails with double and passes with BigDecimal, so the rule is enforced by the build rather than by memory.

Q106. "How do you store timestamps correctly? Compare MySQL's TIMESTAMP and DATETIME, and tell me what you use in Postgres."

Reveal answer

Strong answer The rule is: store the absolute instant in UTC — Coordinated Universal Time, the zone-free reference clock — and convert to local time only at the display edge. The engines differ in how much they help.

In MySQL, TIMESTAMP converts values to UTC on write and back to the session's time zone on read, which is the behavior you want, but it is stored in 32 bits and runs out in January 2038, and its implicit conversion surprises people when session zones differ.

DATETIME stores exactly the wall-clock digits you give it, with no zone attached and a much wider range — safe only if the application guarantees every writer sends UTC. In Postgres, timestamptz — "timestamp with time zone" — is the correct default: despite its name it stores no zone; it normalizes every value to a UTC instant and renders it in the client's zone.

Plain timestamp stores ambiguous wall-clock digits and is the source of the classic "off by five and a half hours" bug. In Java I keep these as Instant or OffsetDateTime, never LocalDateTime, for the same reason.

Land it One convention — UTC instants in the database, timestamptz in Postgres, UTC-disciplined DATETIME in modern MySQL — and time-zone bugs become a formatting concern instead of a data-corruption concern.

Likely follow-ups
"When do you actually want to store a local wall-clock time instead of a UTC instant?"

For future events that are defined by local rules, such as "the meeting is at 9am Mumbai time next March.

" If I convert that to a UTC instant today, and India or the meeting's country changes its daylight-saving rules before March, my stored instant is now wrong by an hour.

The correct model is a local date-time plus a named zone, such as Asia/Kolkata, stored as two columns, and the conversion to an instant happens at query time using the current zone rules.

Postgres timestamp without time zone plus a separate zone column is right for this. Everything that already happened, such as order created_at or login time, is an instant and belongs in timestamptz or a UTC DATETIME.

"Show me how MySQL's TIMESTAMP conversion goes wrong in practice."

MySQL converts TIMESTAMP values using the session's time_zone variable on both write and read.

Suppose the application servers connect with time_zone set to +05:30 and a cron job connects with the default, which is the server's SYSTEM zone, often UTC. The cron job reads 2026-08-28 09:00 while the app reads the same row as 14:30, and a report that mixes both sources is off by five and a half hours.

Worse, the JDBC driver has its own serverTimezone or connectionTimeZone property that can shift values again.

The fix is to set time_zone to '+00:00' on every connection, for example in the JDBC URL or pool init SQL, and set the Java default zone to UTC on all servers, so every path agrees.

"What happens to TIMESTAMP columns in 2038 and what do you do about it?"

MySQL's TIMESTAMP stores seconds since 1970 in a 32-bit unsigned value, so the last representable instant is 03:14:07 UTC on 19 January 2038.

As of Aug 2026 the column type still has that ceiling in MySQL 8.4; the 8.0.28 change that widened things applied to functions like FROM_UNIXTIME, not to the column. An INSERT of a later value fails or becomes zero depending on SQL mode.

For any column that may hold future dates, such as subscription end dates or bond maturities, I use DATETIME today.

For historical event columns the deadline is twelve years away, but a table that big is slow to alter, so I put the migration on the roadmap now rather than in 2037.

"How do you index and query by local day when the column stores UTC instants?"

The wrong way is WHERE DATE(created_at) = '2026-08-28', which wraps the column in a function and prevents index use on both engines.

The right way is a range on the raw column: WHERE created_at >= '2026-08-28 00:00 Asia/Kolkata' AND created_at < '2026-08-29 00:00 Asia/Kolkata', where the application or Postgres computes those two instants.

In Postgres I can write the boundaries as timestamptz literals with a zone name and the planner uses the B-tree index normally.

If a query really needs grouping by local day, I compute the local date in a generated column or an expression index, such as an index on (created_at AT TIME ZONE 'Asia/Kolkata')::date in Postgres, and make sure the query uses the identical expression.

Q107. "Your schema review shows VARCHAR(255) on every string column and a status column stored as free text. What would you push back on, and what are the options for the status column?"

Reveal answer

The real test Whether you treat column definitions as documented business rules or as boilerplate.

Strong answer VARCHAR(255) everywhere is dishonest typing. The declared length is a constraint that documents the business rule, so a two-letter country code should say VARCHAR(2) — anything longer is corrupt data I want rejected at the boundary.

In Postgres the length changes nothing about storage, so honesty is free.

In MySQL, declared length still decides how much memory sort buffers and in-memory temporary tables reserve per row, and how much of the column fits under index length limits, so padding every column to 255 has a real cost. For the status column, three options in ranking order:

  • A CHECK constraint — a rule the database verifies on every write, like CHECK (status IN ('placed','paid','shipped')) — is my default for a small, stable set: visible in the schema, cheap, and changed with a quick migration. MySQL enforces CHECK from 8.0.16.
  • A lookup table with a foreign key wins when statuses carry their own data — display names, ordering, an active flag — or when the business adds values often, because adding a row beats altering a constraint.
  • MySQL's ENUM type bakes the value list into the column definition, so every change is an ALTER TABLE, and Postgres enum types accept new values but resist removal and reordering — I avoid both for anything a product manager might touch.

Land it Column types are the schema telling the truth about the business — honest lengths, CHECK for small stable sets, a lookup table once values carry data or churn.

Likely follow-ups
"You said the length matters in MySQL. Be specific: where does VARCHAR(255) cost memory?"

MySQL's on-disk storage is honest, since a VARCHAR stores only the bytes present. The cost is in memory structures that must assume the maximum.

When a query needs an internal temporary table, for example for GROUP BY or a derived table, the in-memory engine allocates fixed-width rows sized at the declared maximum, so a VARCHAR(255) in utf8mb4 reserves up to 1020 bytes per row even if every value is two characters.

Sort buffers do the same. That makes temporary tables spill to disk far sooner, and it also affects index size limits, because a utf8mb4 VARCHAR(255) needs 1020 bytes of key, above the 767-byte limit that older row formats enforced. Honest lengths mean fewer disk-spilled temporary tables and smaller keys.

"How do you change a CHECK constraint on a large live table when the business adds a new status?"

In Postgres I add the new constraint as NOT VALID, which is instant because it applies only to new rows, then drop the old constraint, then run VALIDATE CONSTRAINT, which scans the table with a lock that does not block reads or writes.

All three steps are ordinary migrations.

In MySQL, ALTER TABLE ADD CONSTRAINT with CHECK is a metadata operation when the existing rows already satisfy it, but MySQL validates existing rows during the ALTER, so it scans the table; on a large table I would run it with ALGORITHM=INPLACE, LOCK=NONE and outside peak hours.

If statuses change often enough that this ceremony is annoying, that is the signal that the lookup table option was right and I migrate to it.

"Postgres enums. What exactly is the limitation, and how do you work around it?"

A Postgres enum type is an ordered list of labels stored as four-byte values. You can add a label with ALTER TYPE ... ADD VALUE, and since Postgres 12 that can run inside a transaction, though the new value cannot be used in that same transaction.

You cannot remove a label at all, and you cannot reorder existing labels without recreating the type. Renaming a label is possible.

So an enum that gains values is fine, and an enum that loses or reorders values requires creating a new type, altering the column with a USING cast, and dropping the old type, which rewrites the column.

For that reason I use enums for things like weekday names that are fixed by nature, and CHECK constraints or lookup tables for business states.

"What about TEXT versus VARCHAR in Postgres? Is there any performance difference?"

None in storage or speed. In Postgres, varchar(n), varchar, and text are the same variable-length type underneath; the only difference is that varchar(n) adds a length check on write.

Values over about two kilobytes are compressed and moved out of line by TOAST regardless of which name you used. So the choice is purely about documentation and constraint.

Many Postgres teams use text everywhere and add CHECK (length(col) <= 100) when a limit matters, which has the advantage that changing the limit is a constraint change, not a type change.

In MySQL the story differs: TEXT columns are stored off-page and cannot be fully indexed, so VARCHAR is the right choice for anything you filter or index on.

Q108 · Scenario. "A report queries WHERE status != 'cancelled' and finance complains the totals are short. Some rows have a NULL status. What is going on?"

Reveal answer

The real test Whether you actually understand three-valued logic, or just avoid NULLs superstitiously.

Strong answer SQL comparisons use three-valued logic: an expression can be TRUE, FALSE, or UNKNOWN, and NULL means "value not known". Comparing anything to NULL — even NULL != 'cancelled' — yields UNKNOWN, because you cannot say whether an unknown value differs from 'cancelled'. A WHERE clause keeps only rows where the condition is TRUE, so UNKNOWN rows are silently dropped. The NULL-status rows are neither matched nor excluded; they simply vanish from the report, which is why the totals are short.

  1. Immediate fix: write the intent explicitly — WHERE status IS DISTINCT FROM 'cancelled' in Postgres, which treats NULL as a comparable value, or the portable WHERE (status <> 'cancelled' OR status IS NULL). MySQL's NULL-safe operator <=> covers equality checks the same way.
  2. Check the aggregates too: COUNT(*) counts rows, but COUNT(status) counts only non-NULL values, and AVG, SUM, MIN, MAX all ignore NULLs — the same report can disagree with itself depending on which column was counted.
  3. Mention the cousin trap: NOT IN (subquery) returns no rows at all if the subquery yields even one NULL, for the same UNKNOWN reason — NOT EXISTS is the safe form.
  4. Prevent it: if "no status" is not a meaningful business state, make the column NOT NULL with an explicit default, so the question can never arise.

Land it NULL is "unknown", not "empty", and every comparison against unknown is unknown — so I either model the state explicitly with NOT NULL, or write predicates that name NULL on purpose.

Likely follow-ups
"How do NULLs behave in a unique index? Can I have two rows with a NULL email?"

In both MySQL and Postgres, by default, yes. A unique index treats each NULL as distinct from every other NULL, because NULL equals NULL is unknown, not true. So a unique index on email allows any number of rows with NULL email.

That is sometimes exactly what you want, which is why the soft-delete trick with a nullable generated column works. When you do not want it, Postgres 15 added UNIQUE NULLS NOT DISTINCT, which treats all NULLs as one value and allows only a single NULL row.

MySQL has no equivalent flag, so you either make the column NOT NULL or add a generated column that substitutes a sentinel. The SQL Server behavior is different again, which trips people migrating between engines.

"Does making the column NOT NULL with a default cost anything on a big table?"

Two separate steps have different costs. Setting a default is a metadata change. Setting NOT NULL requires proving no NULLs exist.

In Postgres, ALTER COLUMN SET NOT NULL takes an ACCESS EXCLUSIVE lock and scans the whole table, unless a validated CHECK (col IS NOT NULL) constraint already exists, in which case Postgres 12 and later skip the scan.

So on a live table I first UPDATE the NULL rows in batches, then add the CHECK as NOT VALID, then VALIDATE CONSTRAINT, then SET NOT NULL, which is now instant.

In MySQL, changing nullability is an INPLACE rebuild of the table, so on a large table I use gh-ost or pt-online-schema-change, or accept the rebuild during a quiet window.

"Why does NOT IN behave badly with NULLs? Walk me through the logic."

WHERE x NOT IN (1, 2, NULL) expands to x <> 1 AND x <> 2 AND x <> NULL. The last comparison is UNKNOWN for every x, and TRUE AND UNKNOWN is UNKNOWN, so the whole predicate is UNKNOWN for every row and no row is returned.

With a subquery that happens to contain one NULL, the whole query silently returns nothing, which people mistake for "no matches." NOT EXISTS is written as a correlated check: NOT EXISTS (SELECT 1 FROM t2 WHERE t2.id = t1.id).

A NULL id in t2 never equals anything, so it just does not match, and the rows behave as expected. Both engines also optimize NOT EXISTS into an anti-join, which is usually faster than NOT IN on large sets.

"How do you handle NULL in ORDER BY and in aggregates in a report that has to be consistent?"

Postgres sorts NULLs last in ascending order and first in descending, while MySQL sorts NULLs first in ascending, so the same query gives a different order on each engine.

I state it explicitly in Postgres with NULLS FIRST or NULLS LAST, and in MySQL I use ORDER BY col IS NULL, col to get the same effect.

For aggregates, I decide up front what NULL means in each column and encode it with COALESCE, for example SUM(COALESCE(discount, 0)). For counting, I use COUNT(*) for rows and COUNT(col) only when I mean "rows where col is known.

" I write those decisions in the report's SQL as comments, because the next person will otherwise change one and break the totals again.

Q109 · Scenario. "Your signup service checks whether an email exists and inserts only if it does not. You still have duplicate accounts in production. The team wants to fix it with a distributed lock. What do you tell them?"

Reveal answer

The real test Whether you know why the database, not the application, is the last line of defense for integrity.

Strong answer The duplicates come from a check-then-act race: two signup requests for the same email run concurrently, both SELECT and find nothing, both INSERT, and both succeed. No amount of application-side checking closes that window, because the check and the insert are separate steps and other threads act between them. A distributed lock reimplements — slowly and fragilely — what the database already does atomically.

  1. The fix is a unique constraint: UNIQUE (email) makes the database itself reject the second insert; the uniqueness check and the write are one atomic operation inside the engine, so there is no window. The application catches the violation — or uses INSERT ... ON CONFLICT DO NOTHING in Postgres — and returns "account already exists".
  2. Generalize the lesson: constraints are the only race-free validation you have. Foreign keys are the same story against orphan rows — application code that "always deletes children first" eventually meets a crash, a retry, or a manual script that does not, and the foreign key is what refuses the orphan.
  3. Be honest about the cost: every foreign key check reads the parent row and takes locks on it, so at extreme write rates — bulk loads, tens of thousands of inserts a second — some teams drop FKs and rely on reconciliation jobs. That is a legitimate trade made with open eyes, not a default.

Application validation still belongs — for friendly error messages and cheap early rejection — but it is UX, not integrity.

Land it Validate in the app for the user's sake, constrain in the database for the truth's sake — only the constraint is atomic with the write.

Likely follow-ups
"Emails are case-insensitive. How do you make the unique constraint respect that?"

In Postgres I create the unique index on an expression, CREATE UNIQUE INDEX ON users (lower(email)), and make every lookup use lower(email) too so the index is used. The alternative is the citext extension, a case-insensitive text type that makes equality and uniqueness ignore case automatically.

In MySQL the default collations for utf8mb4, such as utf8mb4_0900_ai_ci, are already case-insensitive, so a plain unique index on the column treats Bob@x.com and bob@x.com as duplicates; if the column was created with a _bin collation you would need to change it.

I also trim whitespace and normalize the address at the application boundary before the insert, since the constraint can only enforce what it can see.

"You added the unique constraint. How do you handle the violation in Java cleanly?"

Two approaches. The portable one catches the exception: with Spring the driver error is translated into DataIntegrityViolationException, and I map that to an "account already exists" response.

The catch is that the failed insert aborted the current Postgres transaction, so any other work in that transaction is lost; I keep the insert in its own small transaction. The cleaner approach avoids the exception: in Postgres, INSERT ...

ON CONFLICT (email) DO NOTHING RETURNING id returns no row when the email exists, and in MySQL INSERT IGNORE or INSERT ... ON DUPLICATE KEY UPDATE id = id does the same. The row count tells me whether a new account was created.

I still keep the pre-check for the friendly error message, but the constraint is what prevents duplicates.

"Foreign keys cost locks, you said. Explain that cost concretely, and when it bites."

When you insert a child row, the engine must confirm the parent exists and must stop it from being deleted before the child commits.

In Postgres that takes a FOR KEY SHARE lock on the parent row, and in InnoDB a shared record lock on the parent's index entry. Those are lightweight and do not block ordinary reads or updates of non-key columns. They bite in two cases.

First, a hot parent row, such as one tenant or one product that thousands of children reference per second, becomes a lock hotspot, and any UPDATE of its primary key or any DELETE waits on all of them.

Second, bulk loads: loading fifty million child rows means fifty million parent lookups, which can double load time. Both are real but rare, and the cure for the second is to load with constraints deferred or disabled, then validate.

"How do you add a unique constraint to a table that already has duplicates, without downtime?"

First I find the duplicates with a GROUP BY email HAVING COUNT(*) > 1 and decide with the business which row survives, usually the oldest or the one with recent activity, then merge or mark the others in batches.

Then I build the index without blocking writes: CREATE UNIQUE INDEX CONCURRENTLY in Postgres, which fails cleanly if a new duplicate appears during the build, leaving an invalid index I drop and retry.

In MySQL, ADD UNIQUE INDEX runs as an online INPLACE operation that allows concurrent writes. If new duplicates keep sneaking in during cleanup, I deploy the ON CONFLICT DO NOTHING insert first so the application stops producing them, then finish the cleanup, then add the index.

Q110 · Scenario. "You use soft delete — a deleted_at column — on users. A deleted user tries to re-register and gets 'email already taken'. Walk me through the trade-offs of soft delete and how you fix this."

Reveal answer

The real test Whether you have lived with soft delete long enough to know its costs, not just its convenience.

Strong answer Soft delete keeps the row and marks it dead with a timestamp instead of removing it — easy undelete, history preserved, foreign keys never break. The bill arrives later, and this bug is the classic line item: the UNIQUE (email) constraint still sees the dead row, so the returning user collides with their own ghost.

  1. The clean fix in Postgres is a partial unique index — an index built only over rows matching a condition: CREATE UNIQUE INDEX ON users (email) WHERE deleted_at IS NULL. Uniqueness now applies to living rows only. The mechanics of partial indexes belong to the index drill; here it is simply the right tool.
  2. MySQL has no partial indexes, so the standard workaround is a unique index over (email, deleted_at) with a fixed sentinel value for "alive" — or a generated column that is the email when alive and NULL when deleted, since NULLs never collide in a unique index.
  3. Name the other costs: every query forever needs deleted_at IS NULL — one forgotten filter and deleted users appear in exports; tables and indexes bloat with rows nobody reads; and privacy law may demand real erasure, which soft delete quietly fails.
  4. Offer the alternative: hard delete plus an audit or archive table — move the row to users_archive in the same transaction. The live table stays clean and honest, and history lives where history belongs.

Land it Soft delete trades a simple write for a tax on every future query and constraint — I take it only when undelete is a real product feature, and otherwise archive-and-delete.

Likely follow-ups
"Show me the MySQL generated-column trick exactly."

I add a virtual generated column that equals the email only for live rows: ALTER TABLE users ADD COLUMN email_live VARCHAR(320) AS (IF(deleted_at IS NULL, email, NULL)) VIRTUAL, then ADD UNIQUE INDEX (email_live).

A live row has email_live equal to its email, so two live rows with the same email collide.

A deleted row has NULL, and NULLs never collide in a unique index, so any number of deleted rows may share the address, and a returning user can register again.

The index is built on the virtual column's computed values, so it costs the same as a normal index. The application keeps writing the email column and never touches email_live. This needs MySQL 5.7 or later, which as of Aug 2026 every supported version is.

"How do you stop developers forgetting the deleted_at IS NULL filter?"

Two layers. In the database I create a view, users_active, defined as SELECT ... FROM users WHERE deleted_at IS NULL, and grant the application role access to the view instead of the base table, so a forgotten filter is impossible rather than merely discouraged.

In the ORM I add the framework's soft-delete filter, such as Hibernate's @SQLRestriction or @Where clause on the entity, so generated queries include it automatically. The remaining hole is native SQL and reporting tools, which the view covers.

I also add a test that scans the codebase for queries against the raw table name outside the repository layer. Postgres row-level security can do the same job as the view with a policy, which is elegant but harder to debug.

"What about foreign keys and cascades? If a user is soft-deleted, what happens to their orders?"

Nothing happens automatically, which is both the benefit and the trap. ON DELETE CASCADE only fires on a real DELETE, so soft-deleting a user leaves every order pointing at a row that the application considers gone.

Every join then has to decide whether to show orders of deleted users, and each screen decides differently.

The honest fix is to define the rule per relationship and enforce it in one place: for orders, keep them visible because they are financial records; for a user's sessions or notifications, soft-delete them in the same transaction.

With hard delete plus an archive table the question is answered by the foreign key definition, which is one more reason I prefer that design when undelete is not a real feature.

"Privacy law says erase the user. How does soft delete cope, and what would you do?"

Soft delete alone fails the requirement, because the data is still there.

The common compromise is anonymization: on a deletion request, overwrite the personal columns, such as name, email, and phone, with fixed placeholders or a hash, keep the row and its ID so financial history stays intact, and set deleted_at.

The order records remain but no longer identify a person. Backups still contain the old values, so the policy must state the backup retention period, after which the data is genuinely gone.

I also make sure the anonymization runs through the same replicated path as any other write so replicas and the search index update. If the business needs true erasure, hard delete with an archive table that itself gets purged is the cleaner design.

Q111 · Scenario. "Your ORM created a comments table with commentable_type and commentable_id so comments can attach to posts, photos, or products. Your DBA refuses to approve it. Why, and what would you do instead?"

Reveal answer

The real test Whether you recognize the polymorphic-association pattern as a framework convenience the database cannot defend.

Strong answer This is a polymorphic association — one foreign-key-shaped column pair that points at a different table depending on a type discriminator.

The DBA's objection is that it is not actually a foreign key: no constraint can say "commentable_id references posts when type is 'Post' but photos when type is 'Photo'", so the database cannot enforce integrity at all.

Delete a photo and its comments become orphans silently; a typo in the type column creates rows pointing nowhere; joins need a CASE or a UNION per target table and the optimizer cannot help. Honest alternatives, in the order I would offer them:

  • Exclusive arc: one nullable foreign key per parent — post_id, photo_id, product_id — with a CHECK constraint that exactly one is non-null. Real FKs, real cascades, works well when parent types are few and stable.
  • A table per relationship: post_comments, photo_comments — duplicated structure, perfect integrity, sensible when the comment schemas may diverge anyway.
  • Accept the pattern knowingly: keep the polymorphic table, enforce integrity in the application, and run a scheduled orphan-sweep job — a legitimate choice at high parent-type churn, but it must be chosen, not defaulted into by the ORM.

Land it A relationship the database cannot constrain is a bug factory on a timer — with few parent types I take the exclusive arc and keep real foreign keys.

Likely follow-ups
"Write the exclusive-arc CHECK constraint for me. How does it behave on both engines?"

The constraint counts non-null parents and requires exactly one: CHECK ((post_id IS NOT NULL)::int + (photo_id IS NOT NULL)::int + (product_id IS NOT NULL)::int = 1) in Postgres, and in MySQL the same idea as CHECK ((post_id IS NOT NULL) + (photo_id IS NOT NULL) + (product_id IS NOT NULL) = 1), since MySQL treats booleans as integers.

Each of the three columns is a normal foreign key with ON DELETE CASCADE, so deleting a photo removes its comments. Postgres has enforced CHECK constraints forever; MySQL enforces them from 8.0.16, which as of Aug 2026 is every supported version.

Indexing is per column, which is actually better for queries like "comments on photo 42" than a combined (type, id) index.

"The product now has fifteen commentable types and adds one a month. Does the exclusive arc still hold up?"

No, at that churn the arc becomes fifteen nullable columns and a monthly migration, which is the point where I would flip the design.

The cleanest relational answer is a supertype table: create a commentable table with its own ID, and give every post, photo, and product a commentable_id that references it, created in the same transaction as the parent. Comments then reference commentable.id with one real foreign key.

Adding a new type costs no schema change on comments, integrity is enforced, and the type is discoverable through the supertype row. The price is one extra insert per parent and one extra join to reach the parent's own table.

That is a fair trade against fifteen columns or an unconstrained polymorphic pair.

"How do you migrate an existing polymorphic table to the exclusive arc without downtime?"

Expand first: add post_id, photo_id, and product_id as nullable columns with no foreign keys yet, which is instant.

Backfill in batches by primary key, setting the right column from commentable_type and commentable_id, and log any row whose target does not exist, because those orphans are the bug the DBA was worried about.

Deploy application code that writes both the old pair and the new columns. Then add the foreign keys as NOT VALID in Postgres and VALIDATE them, which does not block writes; in MySQL, adding a foreign key checks existing rows but is an INPLACE operation.

Add the CHECK constraint the same way. Switch reads to the new columns, bake for a week, then drop the old pair in a final migration.

"Is there ever a good reason to keep the polymorphic pattern?"

Yes, when the parent types are many, change often, and integrity is not business-critical.

An activity feed or an audit log that records "something of type X with ID Y was touched" is a good example: the referenced row may legitimately be gone later, and the log should keep the record anyway, so a foreign key would actually be wrong.

The same is true for tagging systems that attach labels to any object.

In those cases I keep the type and ID pair, put a composite index on it, run a periodic orphan report so drift is visible, and write in the schema documentation that this table is deliberately unconstrained.

The failure is not the pattern itself; it is using it for data whose consistency matters without saying so.

Q112. "Product wants 'flexible custom fields' per customer. One engineer proposes an entity–attribute–value table, another a jsonb column. How do you judge this?"

Reveal answer

The real test Whether you can tell a managed escape hatch from an anti-pattern that dissolves the schema entirely.

Strong answer EAV — entity–attribute–value — stores each field as its own row: (entity_id, attr_name, attr_value), with the value usually a string.

It looks flexible and destroys nearly everything the database offers: no types, so dates and numbers become strings; no constraints, so nothing is required or validated; reading one object means pivoting dozens of rows, and filtering on three attributes becomes a three-way self-join the optimizer prices badly.

I have seen EAV tables become the slowest, least trusted data in a company, and I would reject it for general use.

A jsonb column — Postgres's binary JSON type, which MySQL matches with its JSON type — is the managed version of the same idea: the ragged attributes live in one document per row, values keep JSON types, a GIN index can make containment queries fast, and Postgres can even apply a CHECK against a JSON schema.

My rule: every field you filter on, join on, constrain, or report on becomes a real column; the genuinely variable per-customer tail goes in jsonb; and when a JSON field starts appearing in WHERE clauses regularly, that is the signal to promote it to a column.

Land it Columns for what the business queries, jsonb for the ragged tail, EAV essentially never — flexibility you cannot type or constrain is just deferred debugging.

Likely follow-ups
"How do you index jsonb for these custom fields, and what can the index answer?"

A GIN index, which is an inverted index mapping each key and value to the rows containing it, is the standard choice: CREATE INDEX ON customers USING gin (custom_fields).

With the default operator class it answers containment queries such as custom_fields @> '{"tier": "gold"}' and key-existence queries with the ? operator. The jsonb_path_ops variant is smaller and faster for containment only.

For one specific field queried with range conditions, such as a numeric credit limit, I build a B-tree expression index on ((custom_fields->>'credit_limit')::numeric). MySQL does the same with a generated column extracted from the JSON plus an ordinary index, or a multi-valued index for arrays since 8.0.17.

What GIN cannot do is order or range-scan, which is the signal to promote the field to a real column.

"What are the write and storage costs of jsonb compared with columns?"

Every update of a jsonb value rewrites the entire document, because Postgres creates a new row version; changing one key in a 5 KB document writes 5 KB plus WAL, whereas updating one integer column writes far less.

Large documents are compressed and stored out of line by TOAST, which adds a fetch when any key is read.

Key names are stored in every row, so a document with fifty keys repeats fifty strings per row, which makes jsonb typically two to three times larger than the same data as columns.

GIN indexes are also expensive to maintain on frequent updates, though the fastupdate pending list softens that. So jsonb is right for a sparsely populated tail that changes rarely, and wrong for hot, dense, frequently updated data.

"How do you validate the shape of the JSON so it does not become a garbage column?"

In Postgres I add a CHECK constraint using the pg_jsonschema extension, or, without extensions, a CHECK that tests required keys and types, for example CHECK (jsonb_typeof(custom_fields->'credit_limit') = 'number'). MySQL has JSON_SCHEMA_VALID built in since 8.0.17, so CHECK (JSON_SCHEMA_VALID(@schema, custom_fields)) enforces a JSON Schema on write.

The schema itself lives in version control next to the migrations, and the application validates against the same schema before sending the write, so users get a friendly error and the database is the backstop.

I also keep an allow-list of field names per tenant in a small table, which stops the column from collecting typos like "creditLimit" and "credit_limit" side by side.

"The customer now wants to filter and sort their list by three custom fields. What do you do?"

That is the promotion signal. Sorting through jsonb needs an expression index per field and still cannot combine three of them in one composite index, so the query will sort in memory.

I would add three real columns, backfill them from the JSON in batches, and keep the JSON as the write source during a dual-write period.

If the fields are per-tenant and different for every customer, a middle path is a typed side table with one row per (customer, field_name) and separate typed value columns, which is a controlled EAV limited to indexed, sortable fields.

The general answer is that the moment a field participates in WHERE or ORDER BY on a hot list, it earns a column.

Q113. "When would you split one wide table into two with a one-to-one relationship? Isn't that just extra joins?"

Reveal answer

Strong answer The join is a cost, so the split has to buy something physical, and it usually buys two things.

First, hot versus cold columns: if users has ten small columns read on every request and also a large bio, a settings blob, and an onboarding questionnaire read once a month, every page the database caches carries the cold bytes too, so fewer hot rows fit in memory — the buffer pool in InnoDB, shared buffers in Postgres — and cache hit rate drops.

Moving the cold, wide columns to user_profiles keeps hot rows dense, and honesty requires noting Postgres already offloads very large values automatically through TOAST — its out-of-line storage for oversized columns — so the split matters most for medium-width columns and for InnoDB. Second, update churn separation: a last_seen_at column updated on every request forces row rewrites — and in Postgres, whole new row versions — onto the same rows that carry stable profile data, inflating write amplification and vacuum work.

Splitting the churning counter into its own narrow table confines that churn. If neither memory density nor churn is measurably hurting, I keep the single table and skip the join.

Land it A 1:1 split is a physical optimization, not a modeling style — I make it when hot-path cache density or update churn shows up in measurements, and not before.

Likely follow-ups
"How would you measure that the split actually helped?"

Before and after, I compare three numbers. First, the average row width from pg_stats or from SHOW TABLE STATUS in MySQL, which tells me how many rows fit in a page.

Second, the per-table cache hit rate: pg_statio_user_tables shows heap_blks_hit against heap_blks_read for the users table, and InnoDB exposes buffer pool page counts per table through information_schema.INNODB_BUFFER_PAGE. Third, the p99 latency of the hot query from pg_stat_statements or performance_schema.

If the split worked, heap reads per hot query drop, the hit rate rises, and p99 falls. If the join added latency and the hit rate barely moved, the cold columns were not the problem and I revert. Measuring is cheap because both tables exist during the migration.

"Does Postgres HOT updates change your view on the churn argument?"

It sharpens it. A HOT update, heap-only tuple, lets Postgres write the new row version on the same page without touching any index, but only if no indexed column changed and the page has free space.

So a last_seen_at counter on the wide users row can be HOT as long as last_seen_at is not indexed and the page has room, which the fillfactor setting controls.

The problem is that wide rows fill pages, leaving no room for new versions, so updates spill to other pages and every index gets a new entry. Moving the counter to a narrow table with fillfactor 70 keeps updates HOT and cheap.

So the churn argument still holds, but the first thing I try is unindexing the counter and lowering fillfactor before splitting.

"What are the pitfalls of the one-to-one split for the application?"

The main one is optionality: if user_profiles may not exist yet for a user, every read needs a LEFT JOIN and every write needs an upsert, and ORMs handle optional one-to-one relations badly, often issuing a second query per row.

I avoid that by inserting the profile row in the same transaction as the user, so the relation is always present and the join can be inner.

The second pitfall is lazy loading, which turns a list of a hundred users into a hundred profile queries; the fix is a fetch join or an explicit batch query.

The third is that the shared primary key must be the foreign key with ON DELETE CASCADE so the two rows live and die together. None of these are hard, but they must be decided when the split is made.

Q114 · Scenario. "An auditor asks who changed a product's price last March and what it was before. You have no answer. What are the options for change history, and which would you build?"

Reveal answer

The real test Whether you know the three audit patterns and what each one honestly captures and misses.

Strong answer Three patterns, with different blind spots:

  • Trigger-based history: a database trigger copies the old row into products_history on every UPDATE or DELETE. Its strength is completeness — it captures every change, including a manual SQL fix at 2am that bypasses the application. Its weakness is context: the database does not know which human or request caused the change, so you must pass the actor in through a session variable, and the logic lives where developers rarely look.
  • Application-level audit events: the service writes an audit record — actor, reason, request ID, before and after values — in the same transaction as the change. Rich context, visible code, but it records only changes that go through the application; the 2am SQL fix is invisible, which is exactly what an auditor worries about.
  • Temporal tables, honestly: the SQL standard's system-versioned tables keep every row version with validity timestamps automatically. MariaDB ships this natively; MySQL and Postgres do not, so you emulate it with triggers or extensions — meaning "the database does it for free" is not quite true on either engine we run.

I would build both ends: a trigger (or change-data-capture feed, which the replication section covers) for complete row history, plus application audit events for intent and actor. Storage is append-only and cheap; missing history is unrecoverable.

Land it Triggers capture everything but know nothing about why; the app knows why but misses out-of-band changes — an audit story that satisfies an auditor needs both.

Likely follow-ups
"How do you get the acting user into a trigger-based history row?"

The application sets a session variable at the start of each request, and the trigger reads it.

In Postgres that is SET LOCAL app.actor_id = '42' inside the transaction, and the trigger calls current_setting('app.actor_id', true), where the second argument makes it return NULL instead of erroring when unset.

SET LOCAL scopes the value to the transaction, which matters with connection pooling, because a plain SET would leak to the next request on the same connection. In MySQL the same trick uses a user variable, SET @actor_id = 42, read inside the trigger.

If the variable is missing, the trigger records the database user and application_name instead, so a manual fix by a DBA is attributed to that DBA's login. This is a strong reason for per-person database accounts on production.

"What does the trigger cost on a hot table, and how do you keep the history table from becoming the biggest table in the database?"

The trigger adds one INSERT per UPDATE or DELETE, so write cost roughly doubles on that table and the history table grows by one row per change; on a table updated a thousand times a second that is 86 million rows a day.

I make the history table narrow by storing only the old values of changed columns as jsonb rather than the full row, partition it by month so retention is a partition drop, and index only (record_id, changed_at) so writes stay cheap.

The write latency cost is usually under a millisecond, but on truly hot tables I switch to change data capture from the WAL or binlog, which costs the primary nothing and lands the same history in a separate store.

"Does CDC give you the same completeness as triggers, and what does it miss?"

CDC reads the replication log, so it sees every committed change from every path, the same completeness as a trigger, and it adds nothing to the primary's write latency. What it misses is context and timing.

The log carries the row images and the transaction ID but not the application actor, unless the application writes a small audit row in the same transaction that the CDC consumer can pair up.

It is also asynchronous: the history arrives some milliseconds to seconds after the commit, so an "as of now" audit query must tolerate that lag. And if the connector's replication slot is dropped or lags, history has a gap, so slot health becomes an alert.

For an auditor, a trigger in the same transaction is the stronger guarantee; for scale, CDC wins.

"How do you answer 'what was the price on 3 March' efficiently from the history table?"

I store validity ranges rather than only change events: each history row has valid_from and valid_to, and the current row has valid_to NULL or infinity.

The query is then a single range condition: WHERE product_id = 7 AND valid_from <= '2026-03-03' AND (valid_to > '2026-03-03' OR valid_to IS NULL).

In Postgres I use a tstzrange column with a GiST index and the containment operator, and an exclusion constraint that forbids overlapping ranges for the same product, which guarantees the history is consistent.

MySQL lacks range types, so I use two timestamp columns with a composite index on (product_id, valid_from). Closing the previous range happens in the trigger at the same time the new one opens, in the same transaction.

Drill · Partitioning & sharding

This group tests whether you know exactly which problem each way of splitting data solves — and, just as importantly, which problems it does not.

Q115. "What is table partitioning — and, more importantly, what is it not?"

Reveal answer

The real test Whether you can draw the line between partitioning and sharding without being prompted.

Strong answer Partitioning splits one logical table into several physical pieces on the same server, divided by a rule on a chosen column — the partition key — such as one partition per month of created_at.

The application still queries one table name; the engine routes reads and writes to the right pieces underneath.

What it is not: it is not sharding, because every byte still lives on one machine, sharing one CPU, one buffer pool, and one disk — it adds zero write capacity and zero storage headroom beyond that box.

It is not a substitute for indexes — a query that misses an index is still slow inside its partition.

And it is not free speed for general queries; a query that cannot be narrowed to specific partitions may actually do more work than before, because the engine now visits many smaller structures.

What it genuinely buys is manageability of very large tables: dropping old data instantly, pruning time-scoped scans, and keeping maintenance operations scoped to one piece at a time.

Land it Partitioning is a data-lifecycle and pruning tool on one machine — the moment the machine itself is the limit, the conversation changes to sharding.

Likely follow-ups
"At what table size do you start considering partitioning?"

I do not use size alone; I use maintenance pain.

The trigger is when a routine operation on the table no longer fits its window: a VACUUM that takes hours, an index build that takes a day, a retention DELETE that lags replicas, or a backup restore dominated by one table.

In practice that tends to appear somewhere between a few hundred million rows and a few billion, or around several hundred gigabytes, depending on hardware. Below that, indexes and good queries solve every performance problem partitioning could, with none of the constraint limitations.

So my answer is: partition when the data has a natural lifecycle you want to drop by chunk, or when maintenance on the whole table has become the bottleneck, and not before.

"How do I convert an existing large unpartitioned table to a partitioned one without downtime?"

In Postgres, I create the new partitioned parent with the same columns, and then attach the existing table as the first partition covering all historical data with ATTACH PARTITION, which needs a CHECK constraint proving the rows fit so the attach does not scan.

New monthly partitions are created ahead. The rename swap of old table and new parent happens in one transaction and takes a brief lock. Afterwards I can gradually move rows out of the giant historical partition into monthly ones if I need finer pruning.

In MySQL, converting requires a table rebuild, so I use pt-online-schema-change with the PARTITION BY clause or build a partitioned copy and backfill. Either way the application sees one table name throughout.

"Does partitioning help write throughput at all?"

Slightly and indirectly, not fundamentally. Each partition has its own smaller indexes, so B-tree inserts descend shallower trees and the hot right-edge page of a time partition stays in memory, which can help insert-heavy tables.

VACUUM in Postgres runs per partition, so cleanup keeps up more easily and can run in parallel across partitions. But the writes still land on one server's disk and WAL, so total write capacity is unchanged.

If someone expects partitioning to fix a saturated primary, they will be disappointed; the honest tools for that are faster storage, batching, and eventually sharding.

"What do you have to change in the application when you partition?"

Ideally nothing, but three things commonly bite. First, the primary key now includes the partition key, so ORMs that assume a single ID column need the composite key mapped, and foreign keys from other tables must reference both columns.

Second, queries that should prune must filter on the partition key with a plain comparison, so a lookup by order ID alone must either add a date range or accept a fan-out across partitions.

Third, in Postgres, an UPDATE that changes the partition key moves the row between partitions, which works since version 11 but is implemented as a DELETE plus INSERT, so triggers and RETURNING behave differently.

I audit the hot queries for pruning with EXPLAIN before the switch rather than after.

Q116 · Scenario. "You have an orders table partitioned into 60 monthly partitions. Show me a query that benefits, prove the benefit, and show me one that gets no help at all."

Reveal answer

The real test Whether you understand partition pruning mechanically — the planner can skip partitions only when the filter speaks the partition key's language.

Strong answer Partition pruning means the planner compares the query's filter against each partition's boundary rule and skips every partition that cannot contain matching rows. A two-month date-range query therefore touches 2 partitions out of 60 — the other 58 are never opened, never read, never even planned in modern Postgres.

partition-pruning.sql
CREATE TABLE orders (
    id          bigint GENERATED ALWAYS AS IDENTITY,
    created_at  timestamptz NOT NULL,
    customer_id bigint NOT NULL,
    total       numeric(19,4) NOT NULL,
    PRIMARY KEY (id, created_at)   -- partition key must be in the PK
) PARTITION BY RANGE (created_at);

CREATE TABLE orders_2026_07 PARTITION OF orders
    FOR VALUES FROM ('2026-07-01') TO ('2026-08-01');
-- ... 59 more monthly partitions

EXPLAIN SELECT * FROM orders
WHERE created_at >= '2026-07-01' AND created_at < '2026-09-01';
--  Append
--    ->  Index Scan ... on orders_2026_07
--    ->  Index Scan ... on orders_2026_08
--  (the other 58 partitions do not appear in the plan)

EXPLAIN SELECT * FROM orders WHERE customer_id = 42;
--  Append with all 60 partitions listed: no pruning possible

The second query is the honest half of the answer: it filters on customer_id, which says nothing about created_at, so every partition might hold matching rows and the planner must probe all 60 — sixty separate index lookups instead of one. Pruning also fails when the filter wraps the key in a function like date(created_at), or in MySQL when the partition function cannot be inverted from the predicate. The design lesson: partition by the column your big queries already filter on, or accept that those queries fan out.

Land it Pruning is a planning-time filter match against partition boundaries — queries that constrain the partition key fly, and every other query quietly pays a sixty-way tax.

Likely follow-ups
"The date comes from a bind parameter, not a literal. Does pruning still happen?"

Yes, but at a different stage. Postgres has plan-time pruning for literals and execution-time pruning for values that are only known when the query runs, such as bind parameters in a prepared statement or values from a subquery.

Since Postgres 11, the plan lists all partitions but the executor skips the ones that cannot match, and EXPLAIN ANALYZE shows this as "Subplans Removed: 58".

With the JDBC driver, statements become server-side prepared after five executions, and a generic plan may be used, which is exactly when run-time pruning matters. In MySQL, pruning happens at optimization for each execution with the actual parameter value, so it behaves like a literal.

The way to verify is EXPLAIN ANALYZE with the real parameter, never a hand-edited literal.

"How does the customer_id lookup perform after partitioning compared with before, and how do you fix it?"

Before, it was one B-tree descent, about four page reads. After, it is sixty descents, one per partition, so roughly two hundred and forty page reads, plus the planner overhead of sixty plan nodes.

Most of those pages are index roots that stay cached, so the latency might go from half a millisecond to five milliseconds, which is fine for an admin screen and terrible for a hot endpoint.

The fixes are to add a date bound when the application knows one, such as "orders in the last year" for a customer page, or to keep a small unpartitioned lookup table of (customer_id, order_id, created_at) so the application first finds the partition key and then queries the pruned partition.

If the customer_id lookup is the dominant access path, the partition key was chosen wrongly.

"Show me the DDL and pruning behavior for MySQL instead of Postgres."

In MySQL 8 the table is created with PARTITION BY RANGE (TO_DAYS(created_at)) or, cleaner, RANGE COLUMNS(created_at), with partitions defined as VALUES LESS THAN ('2026-08-01') and so on. A final MAXVALUE partition catches anything beyond the defined ranges.

EXPLAIN shows a partitions column listing exactly which partitions were selected, so a two-month query shows p202607,p202608 and the customer lookup shows all sixty.

MySQL prunes range predicates on the raw column with RANGE COLUMNS, and with TO_DAYS it can prune because the function is known to be monotonic; a custom function or an expression like DATE_FORMAT defeats it.

The other MySQL rule to remember is that every unique key, including the primary key, must include the partition column.

"What happens to a query that filters on the partition key but uses OR, IN, or a BETWEEN that spans everything?"

OR and IN lists of dates prune fine; each value or range is checked against the boundaries and the union of matching partitions is used.

A BETWEEN spanning five years simply selects all sixty partitions, which is correct but gives no benefit, and the plan becomes an Append over sixty index scans, sorted with a merge if the query has ORDER BY created_at.

Where pruning silently fails is a type mismatch, such as comparing a timestamptz partition key against a text value with an implicit cast, or wrapping the key in a function like date_trunc.

The check is always the same: run EXPLAIN and count the partitions in the plan. If it says sixty and I expected two, the predicate is not in the partition key's language.

Q117 · Scenario. "Compliance says you must purge order events older than two years from a 4-billion-row table. Last time, the DELETE ran for a week and caused replication lag. What is the right design?"

Reveal answer

The real test Whether you know that retention is the single strongest reason to partition, and why DELETE is the wrong verb at this scale.

Strong answer A giant DELETE is expensive in every layer at once, and walking through why is the answer:

  1. Every deleted row is individually located, locked, and logged. In Postgres, DELETE only marks rows dead — VACUUM, the background reclaimer, must later revisit them, and until it does the table and indexes stay bloated. In InnoDB, the old row versions pile into undo history that the purge thread must chew through.
  2. Every one of those billions of changes streams through the replication log, so replicas fall hours behind — exactly the lag we saw.
  3. Index maintenance multiplies the cost by the number of indexes.

The right design is range partitioning by month on the event timestamp.

Then retention becomes DROP PARTITION in MySQL, or DETACH PARTITION then drop in Postgres — a metadata operation that unlinks one physical table in milliseconds, generating no per-row work, no dead tuples, no vacuum debt, and almost nothing to replicate.

The week-long job becomes a monthly cron entry that finishes before you can read its log line.

For the existing unpartitioned table, I would migrate by creating the partitioned table alongside, backfilling in batches, and swapping names in a short window — and until then, delete in small batches of ten to fifty thousand rows with pauses, to keep replicas breathing.

Going deeper Two mechanical details make the partition-drop story airtight.

In Postgres, DETACH PARTITION normally needs an ACCESS EXCLUSIVE lock on the parent, which briefly blocks every query on the whole table; since Postgres 14, DETACH PARTITION CONCURRENTLY takes a weaker lock and waits for in-flight queries in two steps, so the drop causes no outage even under load.

In MySQL, DROP PARTITION is fast but still needs the metadata lock, so a long-running SELECT on the table will make it wait and queue everything behind it, and I set lock_wait_timeout to a few seconds around it exactly as I would for any DDL. For the interim batched DELETE on the unpartitioned table, the loop is DELETE ...

WHERE id IN (SELECT id FROM t WHERE created_at < cutoff ORDER BY id LIMIT 20000) in Postgres, or DELETE ... ORDER BY id LIMIT 20000 in MySQL, with a sleep between batches that grows when replica lag rises.

Land it If data has a scheduled death, give it a partition to die in — dropping a partition is a metadata flick, while DELETE pays per row across the table, the log, and every replica.

Likely follow-ups
"Compliance also says purge, but finance wants aggregate history kept. How do you reconcile that?"

I split retention into raw and derived. Before dropping a partition, a job computes the aggregates finance needs, such as daily totals per merchant and per event type, into a small summary table that is not subject to the purge, because it contains no personal data.

Then the partition is detached and dropped. The summary job runs a month before the drop so there is time to spot a failure. Finance's reports move to the summary table, which is also far faster for them.

If compliance requires proof of deletion, the job records the partition name, row count, and drop timestamp in an audit table. This satisfies both sides: the personal records are gone on schedule, and the numbers survive.

"You dropped a partition and then discovered a downstream job still needed it. What now?"

A drop is irreversible, so recovery comes from the backup: I restore last night's base backup to a side instance, replay WAL up to just before the drop, and copy the partition's rows back as a new table, then attach it as a partition again.

That takes hours for a large database, which is why my drop procedure detaches first, keeps the detached table for a grace period of a week or two, and only then drops it. A detached partition is an ordinary table that costs nothing but disk.

I also make the drop job check a registry of known consumers before running, and I announce the retention schedule where the downstream teams can see it, because the process failure here is that a consumer existed that the purge did not know about.

"Postgres: after a big DELETE in the batched interim approach, why does the table not get smaller, and how do you handle that?"

DELETE marks rows dead; VACUUM later makes their space reusable but does not return it to the operating system, except for empty pages at the very end of the file.

So a table that lost half its rows keeps its size, and new inserts fill the holes over time. If disk space is the goal, the options are pg_repack, which rebuilds the table online, or VACUUM FULL, which locks it.

With the interim batched delete I run VACUUM after each large group of batches so dead space is reused promptly, and I accept the file size until the partitioned design replaces the table. Indexes bloat the same way, and REINDEX CONCURRENTLY fixes them online.

This is the reason partition drop is so much better: it deletes a whole file.

"What do you do about foreign keys pointing at the events table when you drop a partition?"

In Postgres, foreign keys referencing a partitioned table are supported since version 12, but dropping a partition with referencing rows elsewhere fails, because those rows would become orphans.

So the referencing tables must be partitioned the same way and dropped in step, or the reference must be dropped.

For an events table, referencing rows are rare and usually belong to the same lifecycle, so I partition them identically and drop both partitions in one transaction.

MySQL does not allow foreign keys on partitioned tables at all, which is a real limitation that must be stated when proposing partitioning; integrity is then enforced by the application and an orphan check. This is one of the questions I answer before partitioning, not after.

Q118 · Scenario. "You partitioned orders by created_at, and now ALTER TABLE ... ADD UNIQUE (order_number) fails on both MySQL and Postgres. Why, and what do you do?"

Reveal answer

The real test Whether you know the unique-constraint limitation of partitioned tables and its architectural consequence, not just the error message.

Strong answer Both engines enforce uniqueness with an index, and on a partitioned table every index is local — one separate index per partition.

A unique index on order_number alone could only guarantee "unique within July" and "unique within August"; nothing checks across partitions, because no single index sees all the rows.

So both MySQL and Postgres enforce the same rule: every unique constraint, the primary key included, must contain the partition key.

That is why the primary key in a time-partitioned table ends up as (id, created_at) — a shape that surprises people until they see the mechanism. My options, in order:

  • Accept the composite constraint — UNIQUE (order_number, created_at) — and guarantee global uniqueness at generation time instead: order numbers minted from a sequence or an ID service are unique by construction, so the weaker constraint is a backstop, not the defense.
  • Keep a small unpartitioned side table — just order_number with a true unique index — inserted in the same transaction, if the business absolutely requires the database to enforce global uniqueness. It reintroduces a hot central table, which is part of the price.
  • Reconsider the partition key if the unique column is also the natural access path — sometimes partitioning by hash of order_number fits the workload better than time.

Land it Local indexes can only promise local uniqueness — so on partitioned tables, global uniqueness moves from the constraint to the generator, and I say that trade out loud before partitioning.

Likely follow-ups
"Order numbers are minted from a sequence, you said. Is a Postgres sequence really gap-free and unique?"

Unique yes, gap-free no. A sequence hands out values without transactional rollback, so if a transaction takes number 1001 and then aborts, 1001 is never reused, and the next order gets 1002.

Sequences also cache values per session when CACHE is set above one, so values can appear out of order across connections. Uniqueness is guaranteed because the sequence is a single counter with an atomic increment, which is what we need for the global-uniqueness argument.

If the business needs gap-free numbering for invoices, which tax rules sometimes demand, that is a separate mechanism: a counter row updated in the same transaction, which serializes inserts. MySQL's AUTO_INCREMENT behaves the same way, including gaps on rollback.

"What if order_number is the column the customer-service team searches by constantly?"

Then every search fans out across sixty local indexes, which works but costs sixty index descents.

The pragmatic fix is to embed the partition key in the number itself, for example prefixing the order number with the year and month, so the application can derive the date range and add it to the query.

Many companies already have order numbers like 2026-08-000123 for this reason. Failing that, a small unpartitioned lookup table mapping order_number to created_at makes every search two cheap lookups.

And if the dominant access is by order number and time-scoped queries are rare, partitioning by hash of order_number rather than by time is the right design, at the cost of losing drop-by-month retention.

"The side table for global uniqueness. What exactly does it look like and what does it cost?"

It is a table with one column, order_number, with a primary key, and nothing else. Every order insert first inserts the number there in the same transaction; a duplicate fails the transaction before any order row exists.

Cost: one extra insert per order, and one extra index that grows by one entry per order, which is small because the table is narrow, perhaps 40 bytes per row.

The real cost is that it is a single hot B-tree receiving every insert, which is fine up to many thousands of inserts per second but is exactly the central structure partitioning was meant to avoid. It also needs its own retention if orders are purged.

I use it only when the business insists on the database enforcing global uniqueness rather than the generator.

Q119. "Why not just partition by day and keep ten years of partitions? What actually goes wrong with thousands of partitions?"

Reveal answer

Strong answer Ten years of daily partitions is about 3,650 physical tables pretending to be one, and the overhead is real on both engines.

Planning cost grows with partition count: the planner must consider boundaries, and for queries that cannot prune it builds a plan node per partition — modern Postgres handles thousands far better than version 10 did, but planning time and memory still scale with the count, and it must lock and track metadata for every partition a query might touch.

Each partition carries its own set of indexes, its own statistics to maintain, and its own files — file handles and cache entries multiply.

Operational surface multiplies the same way: 3,650 partitions times five indexes is over eighteen thousand objects in monitoring, backups, and schema migrations, and an ALTER that touches them all takes correspondingly long.

My guidance is to size partitions by the retention and pruning granularity you actually use: if you drop data monthly and query in day-to-month ranges, monthly partitions — dozens to low hundreds — give you all the benefit.

I go daily only for extreme ingest where a single month would be unmanageably large, and then keep the retention window short.

Land it Partition count is an ongoing tax on planning and operations — choose the coarsest granularity that still serves your drop schedule and your pruning, which is usually monthly.

Likely follow-ups
"How would you measure the planning overhead of many partitions?"

EXPLAIN (ANALYZE) prints Planning Time and Execution Time separately. I run the hot query against a copy of the table with 60 partitions and with 3,650, and compare.

For a query that prunes to one partition, planning stays fast in modern Postgres because pruning happens before most of the planning work, so I expect under a millisecond in both cases.

For a query that cannot prune, planning time grows roughly linearly with partition count, and I have seen tens of milliseconds at a few thousand partitions, which dwarfs a sub-millisecond execution.

I also watch memory: each partition's relation cache entry and statistics are loaded into every backend's memory, so a thousand partitions times hundreds of connections adds up. In MySQL, the equivalent check is the optimizer trace and the open_files_limit.

"What Postgres settings or features affect the practical limit?"

Three matter. enable_partition_pruning must be on, which is the default.

The lock limit: each partition a query touches needs a lock, and max_locks_per_transaction, default 64 per connection, is shared across a lock table sized from that, so a query touching two thousand partitions can fail with "out of shared memory" until that value is raised.

And the version: Postgres 12 made pruning and locking scale to thousands of partitions, and later versions improved planning for non-pruned queries and added partition-wise joins and aggregates.

As of Aug 2026, with Postgres 16 or newer, a few thousand partitions is workable if most queries prune; tens of thousands is where I would say no.

"Who creates the future partitions, and what happens when nobody does?"

In Postgres, an insert whose key matches no partition fails with a partition-not-found error, unless a DEFAULT partition exists, in which case the row goes there and later has to be moved out with a lock. So partition creation is an operational duty.

I automate it with pg_partman, an extension that creates partitions ahead of time on a schedule and can also detach old ones, or with a simple cron job that creates the next three months and alerts if fewer than two future partitions exist.

In MySQL, the equivalent failure is a row that falls outside every VALUES LESS THAN range, which errors unless a MAXVALUE partition exists; the pattern is to keep a MAXVALUE partition and use REORGANIZE PARTITION to split new months out of it before they fill.

Q120. "Range, list, and hash partitioning — give me the one-line use case for each."

Reveal answer

Strong answer Range divides by ordered intervals — almost always time — and is the default choice because it gives both pruning for time-scoped queries and instant retention through dropping the oldest partition.

List divides by explicit named values, such as one partition per country or per product line; it fits a small, stable set of categories that operations wants to manage separately, and it fails when the value set churns.

Hash runs the key through a hash function to spread rows evenly across N partitions; it is what you use when there is no natural range and the goal is simply to keep any one partition — and its indexes and vacuum runs — from growing monstrous.

The honest caveat on hash: because neighboring values land in different partitions, range predicates cannot prune, so you keep pruning only for exact-key lookups; and hash partitioning gives you no cheap retention story, since old and new rows are mixed everywhere.

Land it Range for time and retention, list for a handful of named categories, hash for even spread when nothing orders the data — and hash surrenders both range pruning and cheap purging, so it is the last resort, not the first.

Likely follow-ups
"Can you combine them? Give me a real subpartitioning case."

Yes. Postgres allows a partition to itself be partitioned, and MySQL has explicit subpartitioning.

The common case is range by month at the top and hash by tenant or device below, so time-scoped queries prune to a month and then, if they name a tenant, to one hash bucket inside it, while retention still drops a whole month.

A telemetry table with a billion rows a month benefits because each month becomes sixteen pieces small enough for vacuum and index builds to finish quickly.

The cost is the partition count multiplying, sixty months times sixteen buckets is 960 tables, and the operational tooling must create the tree correctly each month. I only subpartition when a single monthly partition is itself unmanageably large.

"When would list partitioning by tenant be a mistake?"

When tenants are numerous or arrive constantly. Each new tenant then needs a new partition created before its first insert, or a DEFAULT partition catches it and later has to be split out under a lock.

With ten thousand tenants the partition count itself becomes the problem from the previous question. List partitioning by tenant fits a handful of large, stable groups, such as five regions or three product lines that legally or operationally need separate storage.

For many small tenants the right tool is a plain tenant_id column with a leading position in the indexes, which gives locality without the operational duty, and hash partitioning only if the table's size alone demands splitting.

"With hash partitioning, what happens when you need more partitions?"

In Postgres, hash partitions are defined with a modulus and remainder, and changing the modulus means every row's bucket changes, so you effectively rebuild: create a new partitioned table with the new modulus, copy the data, and swap. There is no in-place split.

MySQL allows ALTER TABLE ... ADD PARTITION on hash tables, but under the hood it redistributes all rows, which is a full rewrite with a lock. This is the same remapping problem as modulo sharding.

So I choose the hash partition count generously up front, for example 32 or 64, sized to what the table will be in three years, because the cost of too many small partitions is much lower than the cost of a rebuild later.

Q121. "Do MySQL or Postgres have global indexes on partitioned tables? What are the practical consequences?"

Reveal answer

The real test Whether you know the storage-level fact that quietly shapes every partitioned design.

Strong answer No — neither engine has a true global index, meaning a single index structure spanning all partitions of a partitioned table.

Everything is local: each partition owns its own copy of each index, and what Postgres calls a "partitioned index" is just a template that guarantees a matching local index exists on every partition.

Some commercial databases, Oracle among them, do offer global indexes; on our engines the absence has three practical consequences. First, the unique-constraint rule we discussed: uniqueness can only be enforced where one index sees all candidate rows, so every unique key must include the partition key.

Second, any lookup that does not constrain the partition key must probe one local index per partition — sixty small index descents instead of one, which is cheap per probe but adds up on hot paths and shows up as a wide Append of index scans in the plan.

Third, there is an upside: local indexes live and die with their partition, so dropping a partition drops its index slices instantly, with none of the global-index cleanup that makes partition maintenance painful elsewhere.

Land it All-local indexes are why partitioned uniqueness is constrained and non-key lookups fan out — and also why partition drops stay instant, which is the trade the engines chose on purpose.

Likely follow-ups
"How do you create an index on a partitioned table without locking all sixty partitions at once?"

In Postgres, CREATE INDEX on the parent builds the index on every partition in one command, but as of Aug 2026 it cannot run CONCURRENTLY, so it locks writes on each partition in turn.

The workaround is to create the index on the parent with the ONLY keyword, which registers it as invalid, then run CREATE INDEX CONCURRENTLY on each partition separately, and finally ALTER INDEX ...

ATTACH PARTITION each one; when all sixty are attached the parent index becomes valid. It is tedious but scriptable.

In MySQL, ADD INDEX on a partitioned table runs online across all partitions as one INPLACE operation, holding a metadata lock only briefly, so the native command is usually fine.

"Does the lack of global indexes affect foreign keys pointing at the partitioned table?"

Yes, for the same reason. A foreign key needs a unique index on the referenced columns, and the only unique indexes available include the partition key.

So a child table cannot reference orders by id alone; it must carry both id and created_at and reference the composite key. In Postgres that works since version 12.

It means every child row stores an extra eight-byte timestamp and every join names two columns, which ORMs handle awkwardly.

MySQL does not support foreign keys on partitioned tables at all as of Aug 2026, so partitioning a MySQL table means dropping every foreign key that references it. I state that up front, because teams discover it in the migration and are surprised.

"Are there Postgres extensions or other databases that give global indexes, and would you use them?"

Oracle and SQL Server support global indexes natively, and they pay for it with slow partition drops, because dropping a partition invalidates or must clean the global index.

In the Postgres ecosystem there is no supported global index extension I would run in production as of Aug 2026; some forks have attempted it. Distributed databases such as CockroachDB or Spanner index globally because their architecture already treats every index as a distributed table.

So on our engines I design around the limitation with the composite key and generation-time uniqueness rather than looking for a plug-in.

If the workload truly needs a global unique index over a huge table, that is evidence the table is better served unpartitioned or by a different partition key.

Q122. "Sharding, partitioning, replication — thirty seconds, what does each one actually scale?"

Reveal answer

Strong answer Partitioning splits one table into pieces on the same server — it scales manageability: pruning, instant retention, bounded maintenance — but not capacity, because one machine still holds everything.

Replication copies the same full dataset to additional servers — it scales reads, since replicas can serve queries, and it buys availability, since a replica can be promoted when the primary dies — but not writes and not storage, because every server holds and applies every write.

Sharding splits the dataset itself across servers, each owning a disjoint subset keyed by a shard key — it is the only one of the three that scales write throughput and total data size, and it charges the highest price: routing logic, cross-shard queries, and migrations forever after.

Real systems compose them: each shard is typically a replicated primary with its own replicas, and its largest tables may be partitioned internally for retention.

Land it Partitioning scales maintenance, replication scales reads and survival, sharding scales writes and data — and you reach for them in exactly that order of desperation.

Likely follow-ups
"Why does replication not scale writes? Every replica has the same CPU."

Because every replica must apply every write. If the primary handles ten thousand writes a second, each replica also applies ten thousand writes a second just to stay current, so adding replicas adds copies of the same write work rather than dividing it.

The replica's write capacity is spent keeping up, and only its spare capacity serves reads. Worse, the replica's apply is often less parallel than the primary's original execution, so a replica can fall behind a primary that is not even saturated.

The only way to divide write work is to give each server a different subset of the data, which is sharding. Replication also does not add storage, since every node holds the full dataset.

"Give me the order you would actually apply them to a growing system, with the signal for each."

First, when reads dominate and the primary's CPU is busy serving them, add a replica and route read-only traffic there; the signal is high read share in pg_stat_statements or performance_schema.

Second, when a few tables dominate maintenance and have a lifecycle, partition them; the signal is vacuum, index builds, or retention deletes overrunning their windows.

Third, when the working set no longer fits memory or writes saturate the primary, scale vertically first because it is a reboot, not a rewrite. Fourth, extract independent write-heavy data such as events into their own store.

Fifth, shard, when a single primary's write throughput or storage is the proven ceiling. Each step is reversible except the last, which is why it is last.

"How do the three compose in a real deployment? Draw it in words."

Picture four shards. Each shard is a primary with two replicas, so replication gives each shard read scale and failover. Inside each primary, the orders and events tables are partitioned by month, so each shard drops old data by partition.

A routing layer maps tenant to shard through a directory table. Backups run per shard from a replica, and each shard has its own failover manager. A cross-shard query goes through a scatter-gather service or a warehouse fed by CDC from all shards.

So a single logical database becomes twelve servers, four failover groups, and one routing service, which is the operational bill sharding presents, and why the previous steps come first.

Q123 · Scenario. "You must shard a multi-tenant SaaS product's database. What shard key do you pick, and what do you do when one enterprise customer is a hundred times bigger than everyone else?"

Reveal answer

The real test Whether you can pick the natural key for the workload and then survive its failure mode — the whale tenant.

Strong answer For multi-tenant SaaS — software-as-a-service where many customer organizations share one system — tenant_id is the natural shard key, because almost every query in such a product is already scoped to one tenant.

That makes nearly all traffic single-shard: a tenant's users, orders, and settings co-locate, joins within a tenant stay local, and per-tenant isolation, backup, and even compliance placement fall out naturally.

The failure mode is the whale tenant: one customer so large that whichever shard holds them runs hot while others idle — hashing does not save you, because a single key's data cannot be split by a better hash. Mitigations, in the order I would apply them:

  1. Use a directory, not a formula: keep a small tenant-to-shard mapping table instead of hash(tenant_id) % N. Placement becomes a routing decision you can change per tenant, which enables everything below.
  2. Give whales dedicated shards: move the elephant to its own hardware via the directory. Operationally simple, and it doubles as an enterprise-tier selling point.
  3. Sub-shard the whale if one machine still cannot hold it: split that tenant's data by a secondary key — user or region — accepting that this one tenant's queries now fan out.
  4. Balance the rest by weight, not count: place tenants by observed load so mid-size customers do not accidentally stack on one shard.

Land it Shard by tenant_id through a mapping directory, because the directory is what lets you answer the whale question with a placement change instead of a re-architecture.

Likely follow-ups
"How do you move a tenant from one shard to another while it is live?"

The directory is what makes it possible.

I mark the tenant as migrating in the directory, start dual-writing its rows to both shards, copy the tenant's historical data in batches, ordered by primary key, from the old shard to the new one, then re-copy rows changed since the copy started, using an updated_at column or CDC. Then I compare row counts and checksums per table.

Then I flip the directory entry to the new shard, which every router picks up within seconds because the directory is cached with a short TTL, and I stop dual-writing.

For a large tenant the copy runs hours; the flip itself is a brief write pause of a few seconds, done at that tenant's quiet time. The old rows are deleted after a grace period.

"Where does the directory live, and what happens when it goes down?"

The directory is tiny, one row per tenant, so it lives in its own small highly available database, or in a coordination store, and every router caches it in memory with a refresh every few seconds.

A router that cannot reach the directory keeps using its cached map, so a directory outage only blocks new tenants and pending moves, not existing traffic.

The cache must never be longer-lived than a migration flip tolerates; during a move, the router checks the directory version before writing. I also snapshot the directory into each shard's metadata so a shard can be identified even if the directory database is lost.

The one failure I design out is a stale cache writing to the old shard after a flip, which is why moves involve a short write pause.

"The whale tenant is on its own shard and still too big for one box. What now?"

Then that tenant gets a second-level shard key, which is a different design for one customer.

I pick a key that keeps most of their queries local, usually a business unit or a region within the enterprise, and the directory entry for that tenant points to a list of sub-shards with their own routing rule.

Their cross-unit queries now fan out, and I tell the customer's integration team that reports spanning the whole enterprise come from a reporting replica or a warehouse.

Before doing that I check whether the whale's size is really data or just retention, because archiving their old records often shrinks them back into one machine. Sub-sharding one tenant is expensive engineering, so it has to be justified by that tenant's revenue.

"What would you shard by for a consumer app with no tenants, say a social network?"

By user_id, because the dominant queries are a user's own timeline, settings, and posts, so a user's data co-locates and most requests stay on one shard. The problem is the social graph: a feed built from friends' posts touches many shards.

The standard answer is to precompute the feed, writing each new post into the feed of each follower at write time, so reads are single-shard, and to treat celebrity accounts with millions of followers as a special case merged at read time.

Reference data like hashtags gets its own store. The shard key choice is always the same question: what does the hot path filter on, and can I make everything the hot path needs live under that key.

Q124. "Hash sharding versus range sharding — what is the actual trade?"

Reveal answer

Strong answer The trade is locality versus hotspots. Hash sharding runs the shard key through a hash function, so keys spread evenly and no shard becomes hot from key patterns — new signups, sequential IDs, a viral customer's neighbors all scatter.

The cost is that related keys land on different shards: a range query, "all orders this week," must ask every shard and merge.

Range sharding assigns contiguous key ranges to shards, so range scans and ordered reads stay on one or two shards, and splitting a busy range into two is a natural growth operation.

The cost is the hotspot: if the key is time-like or monotonically increasing, the newest range takes every insert while old ranges cool into dead weight — the classic "last shard on fire" pattern.

So the decision comes from the access pattern: keys queried by exact identity with no meaningful order want hash; keys queried in ranges want range sharding plus a deliberate plan for the hot tail, such as prefixing the key with a coarse hash to spread the newest writes.

Land it Hash buys even load by destroying order; range preserves order and pays in hotspots — pick by whether your queries need neighbors to live together.

Likely follow-ups
"Explain the 'prefix the key with a coarse hash' trick concretely."

Suppose the key is a timestamp and range sharding sends all new writes to the last range. I prepend a small bucket number derived from a hash of some attribute, say hash(device_id) modulo 16, so keys look like 07-2026-08-28T10:00.

Now the newest writes spread across sixteen ranges instead of one, and each of the sixteen ranges still holds contiguous time within its bucket. A range query for one device knows its bucket and scans one range.

A range query across all devices scans sixteen ranges and merges, which is the price. This is exactly how Cassandra and DynamoDB users avoid hot partitions with time-based keys, and it is a sensible pattern for a hand-built range-sharded MySQL or Postgres fleet too.

"How does range sharding handle splitting a hot shard, and what does that operation cost?"

The hot range is cut at a midpoint key: rows above the cut move to a new shard while the router is updated to send the two halves to two places.

Mechanically that is the same dual-write, backfill, verify, and flip sequence as any migration, applied to half of one shard. The advantage over hash sharding is that only the rows in the split range move, and neighbors stay neighbors.

The cost is that a hot range is hot precisely while you are trying to split it, so the copy competes with production traffic, and if the heat is on the newest keys, the new half is immediately hot again.

Distributed databases automate this as range splitting; on a hand-built system it is a runbook someone executes.

"Which one do CockroachDB and Spanner use, and why does that matter for me?"

Both use range sharding of the sorted key space, with automatic splitting and moving of ranges.

That gives them efficient ordered scans and the ability to place related keys together, and it also gives them the same hotspot problem: a table whose primary key is a timestamp or a sequential integer writes to one range on one node.

That is why their documentation tells you to use UUIDs or hash-sharded indexes for such keys.

It matters because a team migrating from a single Postgres with auto-increment keys to a distributed database often carries the sequential-key habit with them and hits a write hotspot in the first week. Knowing which strategy the engine uses tells you which keys to avoid.

Q125 · Scenario. "The week after sharding by tenant_id, the ops dashboard broke — it joined orders against users across all tenants. Why did it break, and what are the realistic options?"

Reveal answer

The real test Whether you understand that sharding kills the general-purpose JOIN and can enumerate what replaces it.

Strong answer It broke because a JOIN is an engine-internal operation, and after sharding the two sides of that join live in different databases on different machines — no engine executes a join across servers for you. Any query not scoped to one shard key value stops being a query and becomes a distributed operation you must build. The realistic options:

  1. Scatter-gather: the routing layer fans the query out to every shard and merges results in the application. Fine for rare admin screens; each such query costs N shard round-trips, and sorting or paginating across the merged set is on you.
  2. App-side joins: fetch order rows from the relevant shards, collect the user IDs, batch-fetch users, and stitch in memory — a hand-written hash join. Works, but every "join" is now code to maintain.
  3. Duplicate reference data everywhere: small, slow-changing tables — plans, countries, feature flags — get replicated to every shard so local joins keep working. Cheap and very common; needs a sync mechanism.
  4. Denormalize into the sharded rows: store the user's display name on the order at write time, accepting staleness on rename.
  5. The right home for this dashboard: stream changes into a warehouse or read store where cross-tenant analytics run freely — cross-shard reporting is an analytics workload, and moving it off the shards is usually the honest fix.

Land it Sharding trades away the general JOIN for write scale — in-tenant queries stay cheap, and everything cross-shard must be redesigned as fan-out, duplication, or analytics elsewhere, so the dashboard moves to the warehouse.

Likely follow-ups
"How do you paginate a scatter-gather result sorted by created_at across eight shards?"

Offset pagination is the trap, because page 100 of the merged result requires each shard to return its first 100 pages and the router to discard almost all of it.

The workable approach is keyset pagination: the client passes the created_at and id of the last row it saw, each shard runs WHERE (created_at, id) < (:last_ts, :last_id) ORDER BY created_at DESC, id DESC LIMIT 50, and the router merges eight sorted streams of fifty and returns the top fifty.

Each page costs eight small indexed queries regardless of depth. The merge is a simple k-way merge in memory. Counting total rows across shards is a separate expensive fan-out, so I show "next" and "previous" rather than page numbers.

"How do you keep the replicated reference tables in sync on every shard?"

The reference tables are owned by one place, usually a small central database, and every change flows outward.

The simplest mechanism is logical replication: in Postgres, the central database publishes the plans and countries tables and each shard subscribes, so changes arrive within seconds with no application code.

In MySQL, replication filters can replicate just those tables to each shard, or a job applies changes from a CDC stream. The rule is that shards never write to reference tables locally, which I enforce with permissions on the shard-side role.

Latency of a few seconds is fine because reference data changes rarely; the risk is a subscription silently breaking, so I monitor lag per subscription and alert on it.

"The dashboard is needed today and the warehouse is a quarter away. What is the fastest safe bridge?"

A read replica of each shard plus a small aggregation service. The dashboard queries hit the replicas, never the primaries, so a slow report cannot hurt checkout.

The service issues the same query to all eight replicas in parallel, merges in memory, and caches the result for a few minutes, because a dashboard tolerates staleness. For joins across orders and users, the service does the app-side join in batches.

That is a few hundred lines of code and can be built in days.

In Postgres there is an even faster bridge: postgres_fdw, the foreign data wrapper that lets one database query tables on another server, so a single reporting database can define eight foreign tables and UNION them, letting the dashboard keep its SQL.

"Is there a design that would have kept this dashboard working after sharding, without a warehouse?"

Yes, if the dashboard's questions had been known and were aggregate in nature.

Each shard could maintain rollup tables, such as orders per hour per plan, updated by a scheduled job or a trigger, and a tiny central database could collect those rollups from every shard every few minutes. The dashboard then reads one small table.

This works when the report is a fixed set of aggregates and fails when analysts want ad hoc joins, which is why the warehouse eventually wins.

The broader lesson is that sharding requires an inventory of every cross-entity query in the system before the cut, and the dashboard was missed because it lived in a different team's repository.

Q126 · Scenario. "You sharded with hash(user_id) % 8 and now need 16 shards. Someone points out this remaps most keys. Explain the problem and how you would actually reshard."

Reveal answer

The real test Whether you can explain consistent hashing in plain words and outline a zero-downtime migration.

Strong answer With modulo placement, changing N changes almost every key's answer: going from % 8 to % 16 reassigns roughly half of all users, so "add capacity" means "move half the data while serving traffic." Two placement schemes avoid that trap.

Consistent hashing, in one plain paragraph: imagine the hash output space bent into a circle; each shard is placed at points on the circle, each key hashes to a point, and a key belongs to the next shard clockwise from it.

Adding a shard inserts new points that capture only the arcs just before them, so only about 1/Nth of keys move and everything else stays put — each shard gets many points ("virtual nodes") so the arcs average out evenly.

The virtual bucket pattern is the version I prefer for databases: hash every key into a fixed number of buckets, say 4,096, and keep a small bucket-to-shard mapping table; resharding is reassigning some bucket numbers to the new shard, and the unit of migration is a bucket, not a key. Either way, the online migration runs the same play:

  1. Dual-write: writes for moving buckets go to both old and new shards.
  2. Backfill: copy historical rows for those buckets; re-copy anything changed during the copy.
  3. Verify: checksum or row-count comparison between old and new.
  4. Cut reads over bucket by bucket, watch error rates, then stop the old writes and delete the old copies.

Land it Never bind placement to a formula containing N — hash into fixed buckets, map buckets to shards, and resharding becomes a routine dual-write-and-backfill instead of a company-wide event.

Likely follow-ups
"Why 4,096 buckets and not 16 or a million?"

The bucket count sets the finest unit of rebalancing and the size of the mapping table. With 16 buckets and 8 shards, each shard owns two buckets, so the smallest move is one eighth of all data, which is too coarse.

With a million buckets, the mapping table is a million rows that every router must cache and consult, and migrations must track a million states.

A few thousand buckets means each of 8 shards owns about 512, and moving to 16 shards moves 256 buckets per new shard in units small enough to migrate one at a time in minutes.

The number should comfortably exceed the largest shard count you can imagine, multiplied by a factor of ten or more for balancing granularity. Powers of two are convenient but not required.

"During dual-write, a write to the old shard succeeds and the write to the new shard fails. What happens?"

The two shards are now inconsistent for that row, and no distributed transaction fixes it cheaply.

My rule is that the old shard remains the source of truth until cutover, so the write returns success to the user based on the old shard, and the failed new-shard write is recorded in a repair queue.

The backfill job's final re-copy pass, which re-reads every row changed since the copy began, will fix the new shard anyway, and the verification step of checksums per bucket will catch anything it missed.

If the new shard fails frequently, I pause the migration rather than accumulate a large repair backlog. The important design decision is that dual-write is best effort on the new side, and correctness is restored by copy-then-verify, not by hoping both writes succeed.

"How do you verify a bucket is identical on both shards without comparing every row byte by byte?"

I compute an aggregate fingerprint per bucket on each side and compare. For example, SELECT count(*), sum(hashtext(row::text)) or in MySQL a BIT_XOR of CRC32 over the concatenated row, restricted to the bucket's keys. If counts and fingerprints match, the bucket is treated as identical.

If they differ, I narrow down by primary key ranges, which is a binary search for the mismatched rows, and then compare those rows directly. This runs on replicas, not primaries.

Writes continue during verification, so I compare a bucket only after its writes are briefly paused or by comparing as-of a specific point using updated_at less than a cutoff. Percona's pt-table-checksum does exactly this for MySQL replication and is worth borrowing from.

"What would you do differently if you were designing sharding from scratch today?"

I would put a tenant or user identifier on every row from the first day and route through a virtual bucket directory from the first shard, even when there is only one shard, so resharding is a routine operation instead of a project.

I would generate IDs with UUIDv7 or a Snowflake scheme from the start so no auto-increment remapping is ever needed. I would build the router as a library with a single entry point that every query passes through, so cross-shard queries are impossible to write accidentally.

And I would seriously price a distributed SQL database or a managed sharding layer such as Vitess for MySQL or Citus for Postgres, because as of Aug 2026 those tools do the bucket mapping and online moves for you.

Q127. "Once you shard, what happens to auto-increment IDs, and what do you use instead?"

Reveal answer

Strong answer Auto-increment breaks because each shard keeps its own counter, so shard 1 and shard 2 both happily issue ID 1001 — collisions the moment IDs meet in a shared cache, an event stream, or a merged report. The replacements, with their trades:

  • Snowflake-style IDs: a 64-bit number packing a millisecond timestamp, a node identifier, and a per-node sequence. Time-ordered, compact, no coordination on the hot path; the price is assigning node IDs and caring about clock sanity.
  • UUIDv7: the time-ordered UUID — timestamp in the high bits, randomness below — needs no infrastructure at all and stays index-friendly because values arrive in near-time order; the price is sixteen bytes instead of eight.
  • Per-shard ranges or offsets: MySQL's auto_increment_increment and auto_increment_offset give shard k the sequence k, k+N, k+2N…, or a coordinator hands out large blocks. Simple, keeps bigints, but couples ID space to shard count — which stings exactly when you reshard.
  • A central ticket server hands out IDs from one counter: globally ordered, but a single point of failure and a latency stop on every insert — I avoid it.

My default is Snowflake-style or UUIDv7, decided by whether eight-byte keys and existing tooling matter more than zero-infrastructure generation.

Land it The moment there are two counters there are collisions — so IDs must carry time plus node identity, and Snowflake-style or UUIDv7 gives you that without a coordinator in the write path.

Likely follow-ups
"Explain the Snowflake layout exactly and what happens when the clock goes backwards."

A Snowflake ID is a 64-bit integer: one sign bit unused, 41 bits of milliseconds since a custom epoch, which lasts about 69 years, 10 bits of node ID for up to 1,024 generators, and 12 bits of sequence for up to 4,096 IDs per millisecond per node.

If the sequence overflows in one millisecond, the generator waits for the next millisecond.

If the system clock moves backwards, for example after an NTP correction, the generator would mint duplicates, so it must refuse to generate until the clock passes the last timestamp it used, or fail loudly.

That is why the answer says clock sanity matters: generators track the last timestamp, and operations disables aggressive clock stepping on those hosts. Node IDs come from configuration or a coordination service at startup.

"How do you sort and page by time if IDs are UUIDv7? And is UUIDv7 really monotonic?"

UUIDv7 puts a 48-bit millisecond timestamp in the high bits, so ordering by the UUID column orders by creation time to millisecond precision, and keyset pagination on the ID works.

Within the same millisecond the remaining bits are random, so two IDs from the same millisecond are in arbitrary order, and IDs from different nodes with slightly different clocks can be out of order by a few milliseconds.

The standard allows an optional sub-millisecond counter in twelve bits for monotonicity within a node, which the Postgres 18 uuidv7() function uses as of Aug 2026.

So it is near-ordered, good enough for index locality, and not a strict global sequence; if the business needs strict order, that is a separate sequence column.

"Does using 16-byte UUIDs as primary keys hurt on Postgres as much as on InnoDB?"

Less, but not zero. Postgres stores the heap in insertion order, not primary key order, so a random UUID does not scatter the table itself, only the primary key index.

That index still suffers random inserts with UUIDv4, with page splits and poor cache locality, and Postgres has native uuid type storage of 16 bytes rather than the 36-character text some teams mistakenly use. With UUIDv7 the index inserts go to the right edge again.

Secondary indexes in Postgres point to physical row locations, not to the primary key, so the size tax does not multiply through them as it does in InnoDB. So on Postgres, UUIDv7 primary keys are a reasonable default; on InnoDB I still prefer a BIGINT and expose a UUID as a secondary identifier.

Q128. "How do you handle a transaction that spans two shards?"

Reveal answer

The real test Whether your first move is avoiding the distributed transaction rather than implementing one.

Strong answer My honest first answer is: I design so it almost never happens.

The classic mechanism, two-phase commit — a coordinator asks every shard to prepare, then tells all to commit — gives atomicity but holds locks across a network round-trip and blocks everyone if the coordinator dies mid-flight, which is why high-scale shops largely refuse it on hot paths.

Avoidance is a data-modeling job: everything one business transaction touches shares a shard key, so an order and its order_lines carry the same tenant_id or user_id and commit together as one ordinary local ACID transaction — atomic, consistent, isolated, durable — on one shard.

Choosing the shard key to match transactional boundaries is most of the craft of sharding.

For genuinely cross-shard workflows — moving credits between two users on different shards — I use a saga: a sequence of local transactions where each step has a compensating action that undoes it if a later step fails, giving eventual atomicity without cross-shard locks.

The mechanics of sagas and the outbox pattern belong to the transactions drill; here the point is that they are a workflow tool, not a default.

Land it The senior move is choosing a shard key that keeps each business transaction on one shard — sagas for the rare true cross-shard flow, and two-phase commit almost never.

Likely follow-ups
"Walk me through the credit transfer saga step by step, including a failure."

Step one, on shard A, in a local transaction: deduct 100 from user A's balance and insert a transfer record with status pending and a unique transfer ID. Step two, on shard B: credit 100 to user B, recording the same transfer ID in a processed-transfers table so a retry cannot credit twice.

Step three, on shard A: mark the transfer completed. If step two fails permanently, for example user B is closed, the compensating action runs on shard A: refund the 100 and mark the transfer failed.

Each step is idempotent through the transfer ID, and a coordinator, which can be a job table polled by workers, drives the steps and retries. The user may briefly see money leave A before it arrives at B, and the product must accept that pending state.

"Why is two-phase commit so disliked? What actually goes wrong?"

In two-phase commit, the coordinator asks each participant to prepare, and each participant writes its changes durably and holds all locks, promising it can commit.

If the coordinator crashes after participants prepared but before it sends commit, every participant is stuck holding locks on those rows until the coordinator returns, which could be minutes, and nothing else can touch those rows.

Postgres exposes this as prepared transactions in pg_prepared_xacts, which also block vacuum and wraparound cleanup while they linger. The protocol also adds two network round-trips to every commit.

So it is correct but fragile and slow, and the blocking behavior under coordinator failure is why systems at scale prefer sagas, which never hold locks across the network.

"How does the outbox pattern fit with sharding?"

The outbox pattern writes an event row into an outbox table in the same local transaction as the business change, so the event exists if and only if the change committed. A relay process then reads the outbox and publishes to a message broker.

With sharding, each shard has its own outbox table and its own relay, and the transfer saga's step two is triggered by the event from shard A's outbox rather than by a direct synchronous call.

That makes the saga resilient: if shard B is down, the event waits in the broker and is processed later. The consumer on shard B uses the transfer ID for idempotency because the broker delivers at least once. So outbox is the transport that makes sagas reliable across shards.

Q129. "Our startup has 200,000 users and the CTO wants to shard 'before it's too late'. What do you advise?"

Reveal answer

The real test The judgment question — whether you know sharding is a last resort and can name the ladder of steps before it.

Strong answer I would advise against it, with numbers.

A single well-tuned Postgres or MySQL primary on modern hardware — dozens of cores, hundreds of gigabytes of RAM, NVMe storage — sustains tens of thousands of transactions per second, and with good indexes, connection pooling, and read replicas that carries most businesses to millions of users.

At 200,000 users we are nowhere near the wall, and sharding is not insurance you buy early: it is permanent complexity — routing, resharding, the death of cross-shard joins and transactions — that taxes every feature forever.

The ladder before sharding, in order: measure and fix the queries and indexes; add caching for the hot read paths; scale the primary vertically; move reads to replicas; archive or partition away cold data; extract a genuinely independent write-heavy workload — events, logs — into its own store.

Shard only when the evidence says a single primary truly cannot cope: sustained write throughput beyond one machine's ceiling, or a working set that no longer fits any buyable box.

What I would do "before it's too late" is the cheap preparation: keep tenant_id on every row and avoid patterns that assume one database, so that if the day comes, sharding is a migration and not a rewrite.

Land it Shard when measurements prove a single primary cannot carry the writes or the working set — until then, buy the bigger box and keep the shard key in the schema as cheap insurance.

Likely follow-ups
"What are the concrete measurements that would tell you a single primary really is at its limit?"

Four signals, all trending, none a single spike. First, write throughput: WAL or binlog generated per second approaching what the storage can fsync, visible as commit latency rising while CPU is not saturated.

Second, the working set: buffer pool or shared buffers hit ratio drifting down month over month on the largest instance available, meaning the hot data no longer fits any buyable RAM. Third, replication: replicas unable to keep up with the primary's write rate even with parallel apply, since a replica that cannot keep up cannot fail over.

Fourth, maintenance: vacuum or purge falling behind at peak despite tuning. If those are true on the biggest instance class, sharding is justified. If any one is false, there is a cheaper step left.

"The CTO says the cloud provider's biggest instance is expensive. Compare that with sharding costs honestly."

As of Aug 2026, a top-end cloud database instance with around 128 vCPUs and a terabyte of RAM costs on the order of tens of thousands of dollars a month.

Sharding costs engineering time: a routing layer, resharding tooling, the rewrite of every cross-entity query, per-shard operations, and ongoing complexity tax on every feature, which is realistically two to four senior engineers for a year and a permanent slowdown afterwards.

That is easily half a million dollars in the first year before the servers. So the bigger box is cheaper until its price exceeds a few engineers' salaries, and it buys time to grow into the sharding decision with real data.

I would show the CTO both numbers side by side rather than argue in principle.

"What is the cheap preparation you would actually do now, specifically?"

Five things. Put tenant_id or user_id on every table, including child tables that could technically derive it via a join, and include it as the leading column of the main indexes.

Generate IDs with UUIDv7 or a Snowflake scheme rather than auto-increment so keys are globally unique already. Route all database access through one data-access layer so a router can be inserted later. Avoid cross-tenant joins and cross-tenant transactions in application code, and lint for them.

And move analytics to a replica or a warehouse now so no reporting query depends on a single database.

Each of these is good practice on its own, and together they turn a future shard into a migration measured in weeks rather than a rewrite measured in years.

Drill · Replication & failover

These questions test whether you understand what asynchronous copies of your data can and cannot promise — especially in the minute after the primary dies.

Q130. "Explain how asynchronous replication actually works — MySQL and Postgres — in plain words."

Reveal answer

Strong answer Both engines replicate by shipping their change journal, not by re-running your application's SQL against a second server. In MySQL, the primary appends every committed change to the binlog — the binary log, an ordered record of all modifications.

A replica runs an I/O thread that connects to the primary, streams binlog events, and writes them to a local copy called the relay log; separate applier threads then read the relay log and apply the changes to the replica's own tables.

In Postgres, the journal is the WAL — the write-ahead log, the same crash-recovery record every commit already flushes — and a standby holds a replication connection over which the primary streams WAL as it is produced, while the standby continuously replays it, essentially performing crash recovery forever.

"Asynchronous" is the crucial word: the primary acknowledges your commit as soon as its own log is durable, without waiting for any replica to receive or apply it.

That keeps commits fast and keeps replicas from ever slowing the primary — and it means every replica is always some distance behind, which is the lag and data-loss story the next questions dig into.

Land it Replication is log shipping — binlog to relay log in MySQL, streamed WAL replay in Postgres — and because the primary never waits, "committed" and "on the replica" are two different events separated by lag.

Likely follow-ups
"What is a GTID and why does it matter for replication operations?"

A GTID, global transaction identifier, is a unique label MySQL attaches to every committed transaction, made of the originating server's UUID plus a sequence number, such as 3E11FA47-...:23.

With GTIDs, a replica tracks the set of transactions it has applied rather than a file name and byte offset in the binlog. That makes failover much simpler: a replica can be pointed at any new primary with CHANGE REPLICATION SOURCE TO ...

SOURCE_AUTO_POSITION = 1 and the servers work out what is missing. It also makes it safe to detect errant transactions, which are writes that happened on a replica but not the primary.

Postgres does not have GTIDs; its equivalent bookmark is the LSN, log sequence number, a byte position in the WAL stream, plus the timeline ID that changes on each promotion.

"What is a replication slot in Postgres, and what is the danger of using one?"

A replication slot is a named bookmark on the primary that records how far a specific consumer, a standby or a logical decoding client, has confirmed receiving WAL. The primary promises not to recycle any WAL beyond that point, so a standby that goes offline for an hour can reconnect and catch up without needing a full rebuild.

The danger is the same promise: if the consumer disappears and the slot is never dropped, WAL accumulates until the disk fills. Since Postgres 13, max_slot_wal_keep_size caps the retention, after which the slot is marked lost and the standby must be rebuilt.

I always monitor slot lag with pg_replication_slots and alert on inactive slots.

"What is the difference between physical and logical replication in Postgres, and when do you use each?"

Physical replication streams the raw WAL bytes, so the standby is a block-for-block copy of the primary, same major version, same everything, and it can be promoted to replace the primary.

Logical replication decodes the WAL into row-level changes and publishes chosen tables through a publication that subscribers apply as ordinary inserts, updates, and deletes.

Logical works across major versions, can replicate a subset of tables, and the subscriber can have extra indexes or tables, but it does not replicate DDL, it does not replicate sequence values so those must be reset after a switchover, and the subscriber cannot serve as a failover target for the whole cluster.

So physical is for standbys and failover, logical is for major version upgrades, selective sharing of reference tables, and feeding CDC consumers.

"What guarantees ordering and consistency on the replica? Could a replica ever show a state the primary never had?"

With physical replication in Postgres, no: the standby replays WAL records in exactly the order the primary wrote them, so at any instant the standby is a state the primary passed through, just older.

With MySQL row-based replication and a single applier thread, the same is true at transaction boundaries.

With parallel appliers it becomes subtle: transactions that did not conflict on the primary may be applied in a different order on the replica, so a reader could momentarily see transaction B's effects without A's.

MySQL offers replica_preserve_commit_order = ON, which is the default since 8.0.27, to make the replica commit in the primary's order even when it applies in parallel. I keep that on so that replica reads never show a state the primary never had.

Q131 · Scenario. "Every night during a batch job your replica falls thirty minutes behind, and Seconds_Behind_Master flaps between 0 and huge numbers. Explain the causes and how you would measure lag honestly."

Reveal answer

The real test Whether you know why replicas fall behind mechanically and why the famous lag metric lies.

Strong answer The structural cause: the primary executes writes with many concurrent sessions, but the replica historically applied them in a single thread, so one applier races the sum of all primary write traffic.

A nightly batch is the worst case — it also arrives as huge transactions, and a replica cannot begin applying a transaction until it is complete, so one hour-long bulk update stalls everything queued behind it.

Add weaker replica hardware or a replica also serving heavy reads, and thirty minutes is easy. Diagnosis and fix in order:

  1. Measure honestly. Seconds_Behind_Master is the timestamp gap of the event currently being applied — when the applier idles between events it reads 0 even mid-catch-up, and it goes NULL when the I/O thread stalls, hence the flapping. The trustworthy measure is a heartbeat table: write NOW() on the primary every second and read it on the replica; the difference is true lag. In Postgres, pg_stat_replication on the primary shows each standby's received, flushed, and replayed WAL positions — pg_wal_lsn_diff turns those into bytes of lag — and pg_last_xact_replay_timestamp() on the standby gives the time version.
  2. Shrink the transactions. Chunk the batch into commits of ten to fifty thousand rows so the replica pipelines them instead of swallowing one boulder.
  3. Parallelize the apply. MySQL's replica_parallel_workers with dependency tracking lets the replica apply non-conflicting transactions concurrently — the standard modern fix. Postgres physical replay is a single process, so shrinking transactions and faster storage matter more there.
  4. Right-size the replica — it must match the primary's write hardware, not just its read load.

Land it Lag is one applier chasing the whole primary through its biggest transactions — measure it with a heartbeat, not Seconds_Behind_Master, and fix it by shrinking transactions and parallelizing the apply.

Likely follow-ups
"You enabled parallel apply and the lag barely improved. Why, and what next?"

Parallel apply only helps when the primary's transactions are independent of each other. MySQL's dependency tracking, set by replica_parallel_type = LOGICAL_CLOCK with binlog_transaction_dependency_tracking = WRITESET on the primary, lets the replica run transactions concurrently only if they touched different rows.

A nightly batch that updates the same few tables in one long stream is inherently serial, so eight workers sit idle behind one.

The next step is on the primary side: split the batch into many small independent transactions, ideally interleaved by key so writesets do not overlap, and run several batch threads in parallel on the primary so the replica gets parallelizable work.

I would also check the replica's disk: if it is a smaller instance with slower storage, the applier is I/O bound and workers do not help.

"Show me the heartbeat table setup concretely on both engines."

On the primary, a table heartbeat with columns id and ts, one row, updated every second by a tiny cron or a systemd timer: UPDATE heartbeat SET ts = now() WHERE id = 1.

On each replica, a monitoring query SELECT now() - ts FROM heartbeat gives the true lag as a duration, provided the clocks are synchronized with NTP. Percona's pt-heartbeat does this for MySQL and also records the primary's server ID for chained topologies.

In Postgres the same table works, and the built-in alternative is comparing pg_last_xact_replay_timestamp() on the standby with now(), which is only accurate when the primary is writing; on an idle primary it grows even with no lag, which is exactly the flapping problem in reverse.

The heartbeat write solves that by ensuring a write exists every second.

"What does the batch job look like when it is written correctly?"

It walks the table by primary key range rather than by OFFSET, updates a bounded chunk of ten to fifty thousand rows, commits, and then checks lag before the next chunk.

The lag check reads the heartbeat table on the slowest replica, or in Postgres pg_stat_replication's replay_lag column on the primary. If lag exceeds a threshold, say five seconds, the job sleeps and retries, so it is a feedback loop, not a fixed sleep.

Each chunk is idempotent, so a crash halfway is restartable from the last committed key, which it records in a progress table. It runs under a dedicated database role with a statement timeout so a single chunk cannot become a giant transaction by accident.

Logging the rows per second and the lag per chunk gives a graph that makes the next tuning obvious.

"How do you set an alert on replication lag that does not page people every night?"

I alert on the business consequence, not the raw number. If the product tolerates thirty seconds of stale reads, the page fires when heartbeat lag exceeds thirty seconds for more than two minutes on any replica that serves user traffic.

The reporting replica that is allowed to lag gets a much higher threshold, perhaps an hour, and a ticket rather than a page.

During the known batch window, the routing layer already sends freshness-critical reads to the primary, so lag on the replica is expected and the threshold is raised by a scheduled silence.

Separately, a lag that is still growing an hour after the batch finished is a different alert, because it means the replica cannot catch up at all and failover capacity is at risk.

Q132 · Scenario. "A user updates their profile, the next page load reads from a replica, and their old name is back. Support calls it 'the ghost bug'. Give me the fixes, ranked."

Reveal answer

The real test Whether you know the read-your-writes consistency patterns and their operational cost, not just "read from primary".

Strong answer This is a missing read-your-writes guarantee: the write went to the primary, the next read went to a replica that had not applied it yet, and asynchronous replication promises exactly nothing about that window. Fixes, ranked by cost-effectiveness:

  1. Sticky window after writes: after a session performs any write, route that session's reads to the primary for a short window — a few seconds beyond your measured p99 replication lag. Cheap, simple, and it removes the bug for the person who just wrote, which is who notices.
  2. Primary reads for freshness-critical paths: some reads — own profile after edit, account balance, anything immediately following a mutation in one flow — are declared primary-only permanently. Deliberate and narrow, so the primary's read load stays bounded.
  3. Causal tokens for correctness under scale: record the primary's position after the write — the GTID, MySQL's global transaction identifier, or the LSN, Postgres's log sequence number — and on the next read either pick a replica that has applied past that position (WAIT_FOR_EXECUTED_GTID_SET in MySQL) or fall back to primary. Precise, but now your data layer tracks positions.
ReadYourWritesRouter.java
// Option 1: sticky window. After any write, pin this session to primary.
void afterWrite(HttpSession session) {
    session.setAttribute("lastWriteAt", Instant.now());
}

DataSource route(HttpSession session, boolean freshnessCritical) {
    Instant lastWrite = (Instant) session.getAttribute("lastWriteAt");
    boolean recentlyWrote = lastWrite != null
        && lastWrite.isAfter(Instant.now().minus(STICKY_WINDOW));
    return (freshnessCritical || recentlyWrote) ? primary : replica;
}
// STICKY_WINDOW = a few seconds beyond measured p99 replication lag

Land it Replicas trade freshness for read scale — the fix is routing policy, and a sticky window after writes buys ninety percent of the guarantee for five percent of the effort.

Likely follow-ups
"The sticky window is in the HTTP session. What if the user has two browser tabs or the request hits a different app server?"

If the session is stored server-side and shared, for example in Redis, every app server sees the same lastWriteAt and the approach holds.

If sessions are per-server or the client is stateless, I move the marker to the client: after a write, the response sets a cookie such as db_fresh_until with a timestamp a few seconds ahead, and a filter on every request routes reads to the primary while that cookie is in the future.

Multiple tabs share the cookie, so they all see the fresh data. The cookie is not sensitive, since it only affects routing, and it expires by itself.

For API clients that do not keep cookies, the same value travels in a response header that the client echoes back.

"Show me how the LSN or GTID approach works in code on Postgres."

After the write commits, on the primary I run SELECT pg_current_wal_insert_lsn() and store that value with the session or cookie.

On the next read, before using a replica, I run SELECT pg_last_wal_replay_lsn() on the candidate replica and compare with pg_wal_lsn_diff(replay, stored); if the replica is at or past the stored position, its data includes the write and I use it, otherwise I fall back to the primary or try another replica.

That is two cheap queries per routed read, so I cache each replica's replay position for a few hundred milliseconds. In MySQL, the primary returns @@global.gtid_executed after the write and the replica can block with SELECT WAIT_FOR_EXECUTED_GTID_SET('uuid:123', 1) for up to one second before serving.

"Does the fix for one user's own writes cover a case like a friend seeing your update?"

No. Read-your-writes is a per-session guarantee: the person who wrote sees it. Another user reading from a replica sees the old name until the replica catches up, and there is no session marker to tell the router.

That is usually acceptable, because the other user has no way to know the change happened milliseconds ago.

Where it is not acceptable, for example a shared document or an inventory count that two buyers see, the read must go to the primary or the system needs monotonic reads through a causal token attached to the data item itself rather than the session.

The honest statement to product is: the writer always sees their own change; others see it within the replication lag, which we monitor and keep under a stated bound.

"How much read load does the sticky window push back to the primary, and how do you measure it?"

It depends on the fraction of sessions that write.

On a typical site perhaps five percent of requests are writes, and a sticky window of three seconds after each write catches maybe one or two follow-up reads, so the primary takes on the order of ten percent of reads back.

I measure it by tagging routed queries with application_name, such as app-read-primary-sticky, and reading the share in pg_stat_statements or per-user counters in performance_schema.

If the number climbs, the usual cause is a window set far above p99 lag out of caution; measuring actual lag and shrinking the window to just above it brings the primary load back down.

Q133 · Scenario. "You moved reporting to a Postgres standby, and now long reports die with 'canceling statement due to conflict with recovery'. What is happening and what are your options?"

Reveal answer

The real test Whether you understand the standby's conflict between replaying history and serving long queries — and the trade each escape hatch makes.

Strong answer The standby has two jobs that collide. It must keep replaying WAL from the primary, and that stream includes vacuum records that clean up old row versions. If an incoming cleanup would remove a row version a long-running report still needs to see, the standby waits a grace period — max_standby_streaming_delay, 30 seconds by default — and then kills the query to keep replication moving. Long reports on a busy primary hit this constantly. Options, each with its price:

  1. hot_standby_feedback = on: the standby tells the primary which old row versions its queries still need, and the primary's vacuum politely retains them. Reports stop dying — but a six-hour report now holds back cleanup on the primary, causing table bloat there. You have exported your reporting workload's side effects to production.
  2. Raise max_standby_streaming_delay — or set it to -1 — on a dedicated reporting standby: replay simply waits for queries, that replica runs hours behind during reports, and that is fine because nothing else reads from it. This is my usual answer: one replica for failover kept tight, one for reporting allowed to drift.
  3. Move reporting off Postgres entirely into a warehouse fed by change capture, once report volume outgrows a replica.

Worth adding: spare replicas earn their keep beyond reads — you take backups from a standby (pg_basebackup) so the primary never feels backup I/O, and you rehearse risky schema changes and version upgrades against a detached replica with production-shaped data.

Land it A standby must choose between staying current and serving long queries — so give reporting its own replica that is allowed to lag, rather than letting hot_standby_feedback push report bloat back onto the primary.

Likely follow-ups
"With hot_standby_feedback on, how bad can the primary bloat get, and how would you see it?"

The primary keeps every row version newer than the oldest snapshot on the standby, so a six-hour report holds six hours of dead tuples on every table the primary updates, not just the ones the report reads.

On a table updated a thousand times a second, that is over twenty million dead rows that vacuum cannot remove. I see it in pg_stat_user_tables as n_dead_tup climbing while last_autovacuum is recent, meaning vacuum ran and could not clean.

The vacuum log lines say how many dead tuples were not yet removable. And pg_stat_replication on the primary shows the standby's backend_xmin, which is the transaction horizon it is holding back; if that value is far behind, the standby is the pin.

"Is there a middle option that lets the failover replica serve some reads without dying?"

Yes, keep max_standby_streaming_delay at a modest value like 60 seconds and make the queries short. The conflict only kills a query that has run long enough to collide with a cleanup record, so sub-second application reads almost never get cancelled.

I also set statement_timeout for the read role on the standby below the delay so a query cannot even reach the conflict window.

The other tuning is on the primary: vacuum_defer_cleanup_age is gone in modern versions, so the modern equivalent is a modest hot_standby_feedback with a long-transaction alert, accepting a small bloat cost for read reliability.

Long reports still go to the dedicated lagging replica; the failover replica serves the fast reads.

"Besides vacuum, what else causes recovery conflicts?"

Three other sources. Lock conflicts: a DDL statement on the primary, such as ALTER TABLE or DROP TABLE, requires an exclusive lock that the standby must also acquire during replay, so any query on that table on the standby is cancelled after the delay.

Tablespace or database drops cancel everything using them. And buffer pin conflicts: the replay needs to modify a page a query has pinned, which is rare and short.

pg_stat_database_conflicts breaks the counts down by cause, so I can tell whether reports are dying from vacuum, locks, or something else. If it is lock conflicts, the answer is to schedule DDL at quiet times rather than to touch vacuum settings.

"How does the MySQL side handle the same problem?"

MySQL replicas do not have this conflict, because InnoDB's MVCC keeps old versions in the undo log on the replica itself, and a long-running SELECT on the replica just pins the replica's own purge, not the primary's.

The replica keeps applying, so the cost shows up as history list length growing on the replica and undo tablespace growth there, and reads getting slower as they walk long version chains.

So long reports on a MySQL replica hurt only that replica, which is the behavior Postgres achieves by giving reporting its own standby.

The MySQL caveat is that a long SELECT holds a metadata lock, so a replicated DDL will wait behind it and stall the applier, giving you lag instead of a cancelled query.

Q134. "Statement-based versus row-based binlog in MySQL — why is row-based the default?"

Reveal answer

Strong answer Statement-based logging records the SQL text and lets the replica re-execute it; row-based records the actual before-and-after images of each changed row.

Statement-based looks attractive — one short statement instead of a million row images — but it silently corrupts replicas whenever a statement is not perfectly deterministic. UUID() and RAND() evaluate differently on the replica; UPDATE ... LIMIT 1 without an ORDER BY may pick a different row; anything touching user variables or nondeterministic functions in triggers can diverge.

The failure is the worst kind: no error, just a replica that quietly disagrees with the primary until a failover promotes the wrong data.

Row-based logging replays exactly the rows that changed, so determinism stops mattering — at the cost of log volume, since a bulk update logs every row image.

That trade is why row is the default since MySQL 5.7, and it has a second modern justification: change-data-capture tools like Debezium need row images to publish change events, so row-based is also the foundation of downstream pipelines.

MIXED mode exists — statement normally, switching to row for unsafe statements — but full row plus binlog_row_image=FULL is the boring, safe setting.

Land it Statement-based bets your replicas on every statement being deterministic and loses silently — row-based logs the truth itself, which is why it is the default and what CDC pipelines require.

Likely follow-ups
"What does binlog_row_image control and why would you ever set it to MINIMAL?"

binlog_row_image decides how much of each changed row is logged. FULL, the default, logs every column of the before and after image. MINIMAL logs only the primary key and the changed columns. NOBLOB is FULL minus unchanged blob columns.

MINIMAL can shrink the binlog dramatically on wide tables where updates touch one column, which reduces replication traffic and disk.

The price is that replicas must have identical primary keys, that tools relying on full images break, so CDC consumers like Debezium no longer see the whole row on updates and cannot reconstruct state without a prior snapshot, and that point-in-time analysis of the binlog loses information.

I keep FULL unless binlog volume is a measured problem and no CDC consumer depends on it.

"How much bigger does the binlog get with row-based logging, and what does that cost?"

For a bulk UPDATE touching a million rows with a 200-byte row, statement-based logs a few hundred bytes; row-based logs two images per row, roughly 400 MB. Typical mixed workloads see binlogs two to five times larger.

The costs are disk, which is manageable with binlog_expire_logs_seconds, network to each replica, and the replica's apply work, which is actually faster per row because there is no parsing or planning.

There is also a subtle cost: a giant row-based transaction is written to the binlog only at commit, so the replica sees nothing until the whole thing lands and then has to apply it all, which produces the lag spike from earlier. Batching writes keeps this manageable on either format.

"How does Postgres's WAL compare to row-based binlog? Is it the same thing?"

Not quite. The WAL is a physical log: it records byte-level changes to pages, including index pages and free-space maps, which is what physical standbys replay. It is not a list of row changes.

Logical decoding, using an output plugin like pgoutput, reconstructs row-level insert, update, and delete events from the WAL, and that reconstructed stream is the equivalent of a row-based binlog.

To get before-images on updates and deletes, the table needs REPLICA IDENTITY FULL or a primary key, otherwise the stream carries only the key. wal_level must be logical for decoding to work, which adds some WAL volume.

So MySQL's binlog is logical by design; Postgres derives the logical view from a physical log.

Q135. "Async, semi-sync, and fully synchronous replication — what does each guarantee when the primary is destroyed?"

Reveal answer

The real test Whether you can translate replication modes into RPO — the business language of data loss.

Strong answer The frame is RPO — recovery point objective, plainly: how much acknowledged data you are allowed to lose when the primary dies. Asynchronous: commit is acknowledged when the primary's own log is durable; whatever had not yet reached a replica dies with the machine.

RPO equals current replication lag — usually milliseconds, potentially minutes during a batch. Fastest commits, zero coupling to replica health.

Semi-synchronous: the commit acknowledgment waits until at least one replica confirms it has received and durably stored the change — not applied it, just safely holds the log. MySQL's semi-sync plugin and Postgres's synchronous_commit = on with a standby named in synchronous_standby_names both give this shape.

RPO is effectively zero for acknowledged commits, at the price of a network round-trip per commit — and a policy decision for when no replica answers: MySQL degrades to async after a timeout, Postgres blocks commits, which is an availability trade you must choose consciously; quorum forms like ANY 1 (s1, s2) soften it.

Fully synchronous apply — Postgres remote_apply — waits until the standby has applied the change, so reads on that standby see your commit; slowest, and mostly used for consistency rather than just durability.

Land it Async means "lag is your data loss", semi-sync means "safe on two boxes before we say yes", sync-apply means "visible on the replica too" — and choosing among them is choosing RPO against commit latency, which is a business decision to surface, not bury.

Likely follow-ups
"With MySQL semi-sync, what is the difference between AFTER_SYNC and AFTER_COMMIT, and which is safe?"

The setting is rpl_semi_sync_source_wait_point. With AFTER_COMMIT, the primary commits the transaction, making it visible to other sessions, and only then waits for a replica acknowledgment before telling the client.

If the primary dies in that gap, another session may have already read data that the promoted replica never received.

With AFTER_SYNC, the default since MySQL 5.7, the primary writes to the binlog, waits for the replica acknowledgment, and only then commits to the storage engine, so no other session can see a transaction that a replica does not hold.

AFTER_SYNC is the lossless one and the one to use. The timeout, rpl_semi_sync_source_timeout, defaults to ten seconds, after which the primary falls back to asynchronous mode and logs it, which must be monitored.

"In Postgres, what happens to a commit that is waiting for a synchronous standby that has just died?"

The commit is durable on the primary but the client is not told yet: the session hangs waiting for the standby's acknowledgment. If the standby never returns, the session waits forever, and every new write session joins it, so the application appears frozen.

Cancelling the wait with a query cancel releases the client with a warning that the transaction committed locally but may not be replicated.

The operational fix is to remove the dead standby from synchronous_standby_names and reload, or to have configured a quorum like ANY 1 (s1, s2) so one surviving standby suffices.

Postgres deliberately does not auto-degrade, unlike MySQL's timeout, because silent degradation would break the durability promise without anyone noticing.

"What does semi-sync do to commit latency, and how do you measure the cost?"

Every commit adds one network round-trip to the nearest acknowledging replica plus the replica's fsync of its relay log or WAL. Within one availability zone that is typically under a millisecond; across zones in the same region, one to two milliseconds; across regions, the full link latency, which is why cross-region synchronous replication is rare. Throughput is mostly unaffected, because commits from different sessions overlap their waits. I measure it by comparing p99 commit latency in pg_stat_statements for COMMIT statements before and after enabling it, or with a benchmark like sysbench or pgbench, and I watch for the replica's disk becoming the bottleneck, since its fsync is now on the critical path of every primary write.

"When would you choose remote_apply, and what does it cost?"

remote_apply makes the primary wait until the standby has replayed the transaction, not just stored it, so a read on that standby immediately after the commit returns is guaranteed to see the write.

That solves read-your-writes for a load balancer that spreads reads over synchronous standbys without any application routing logic.

The cost is the replay latency added to every commit, which includes the standby's apply time and any replay delay from conflicts, so a long query on the standby can stall primary commits.

I use it only when the standbys are dedicated, fast, and free of long queries, and typically on a per-transaction basis with SET synchronous_commit = remote_apply for the writes that need it, leaving the default at on.

Q136 · Scenario. "During a network partition your tooling promoted a replica, but application servers on the other side kept writing to the old primary for four minutes. Walk me through what went wrong and how failover should be built."

Reveal answer

The real test Whether you can explain split-brain concretely and name the machinery — fencing, quorum, fast client redirection — that prevents it.

Strong answer That is split-brain: two databases both believing they are the primary, both accepting writes. Concretely, for four minutes order 1001 was written on the old primary and order 1002 on the new one; the histories have diverged, and there is no automatic merge — someone will reconcile rows by hand or discard one side's writes. The failure had three missing pieces:

  1. Fencing before promotion. The iron rule is that the old primary must be made incapable of accepting writes before the new one is promoted — kill the process, revoke its virtual IP, set it read-only via an agent, or STONITH — "shoot the other node in the head," in one line: forcibly power-cycle the box through its management controller so it cannot possibly keep serving. Promotion without fencing is how every split-brain story starts.
  2. Quorum-based decision making. A single health-checker inside one network segment cannot distinguish "primary is dead" from "I cannot see the primary." Failover managers — Orchestrator or MHA for MySQL, Patroni for Postgres — decide from multiple vantage points and use a consensus store so only one side of a partition can win.
  3. Fast client redirection. The app servers kept writing because they found the primary via DNS with a long TTL — time-to-live, how long resolvers cache the answer. Clients must switch in seconds: a proxy layer such as ProxySQL or HAProxy holding the primary route, or a virtual IP that moves, with DNS only as the slow fallback.

The residual honesty: with async replication, promotion may also abandon the old primary's last unshipped commits — that is the RPO question, and the recovered node must be rewound (pg_rewind, or re-cloned) rather than rejoined as-is.

Land it Failover is safe only in this order — quorum decides, the old primary is fenced dead, then promotion, then clients repoint through a proxy in seconds — and skipping the fence is choosing split-brain.

Likely follow-ups
"How does Patroni actually prevent two primaries? Walk me through the mechanism."

Patroni stores a leader key in a consensus store, etcd or Consul, with a time-to-live of about thirty seconds. The primary's Patroni agent renews that key every ten seconds.

If the primary loses connectivity to the store, it cannot renew, and when the key expires the agent on the primary demotes its own Postgres to read-only, because it can no longer prove it is the leader.

Meanwhile the replicas see the key vanish and race to acquire it; the store guarantees only one succeeds, and that one promotes. The two timers are designed so the old primary demotes itself before a replica can be promoted.

Orchestrator for MySQL uses the same idea with a Raft-backed cluster of Orchestrator nodes deciding from multiple vantage points.

"The old primary comes back after the partition heals with four minutes of extra writes. What exactly do you do with it?"

First it must not rejoin as-is, because its history diverged from the new primary's.

I fence it, then extract its unique transactions before destroying them: in Postgres I dump the rows changed in those four minutes by comparing against the new primary using the tables' updated_at or by decoding the divergent WAL with pg_waldump and a logical slot; in MySQL, with GTIDs, the errant transactions are visible as the difference between the two servers' gtid_executed sets and can be extracted with mysqlbinlog.

The business then decides which writes to replay on the new primary and which customers to contact. After that, the node is rebuilt from the new primary, using pg_rewind if its timeline allows it, or a fresh base backup.

"How fast should failover be, and what is the trade-off in making it faster?"

Automated failover typically completes in fifteen to sixty seconds: ten to thirty seconds to be sure the primary is really gone, a few seconds to promote, and a few seconds for clients to repoint.

Making detection faster means a shorter TTL and more sensitive health checks, which increases false positives: a ten-second garbage collection pause or a network blip triggers a failover that loses in-flight async commits and forces a rebuild of the old primary.

So faster detection trades availability minutes for a higher rate of unnecessary failovers, each of which has a data-loss risk under async replication.

I set the detection window to the longest normal stall I have observed plus margin, and I make the client-side switch fast instead, because that part has no false-positive cost.

"The failover manager worked, but the application still errored for ten minutes. Why?"

Usually connection handling. Application pools keep open TCP connections to the old primary; if the old primary was fenced by killing the process, those connections break and the pool reconnects through the proxy to the new primary, which is fast.

If the old primary was fenced by making it read-only, the connections stay alive and every write fails with a read-only error until the pool recycles them, which can take the pool's max-lifetime, often thirty minutes.

The fix is a proxy like HAProxy or ProxySQL with a health check that closes backend connections to a non-primary, plus a pool max-lifetime of a few minutes, plus application retry on read-only errors.

DNS-based switching adds the TTL on top, and JVMs cache DNS results by default until networkaddress.cache.ttl is set.

Q137 · Scenario. "After last night's failover, customer-support finds orders that users swear they placed — with confirmation emails — but that do not exist in the database. Explain to me, and then to the business, what happened."

Reveal answer

The real test Whether you can own the async-replication data-loss conversation in business language instead of hiding behind jargon.

Strong answer To engineering: we run asynchronous replication, so the primary acknowledged those commits — and triggered the confirmation emails — before the changes reached any replica. The primary then died, we promoted a replica, and the promoted replica's history simply ends a few seconds before the crash. Those orders were durable on exactly one machine, and that machine is gone; this is not a bug in failover but the defined behavior of async replication. Steps I would take:

  1. Bound the loss: from monitoring, establish the replica's lag at promotion time — say four seconds — and the window of affected commits.
  2. Attempt recovery: if the old primary's disks survived, extract its final binlog or WAL segments and replay the missing transactions; if it degraded rather than vanished, compare positions and reconcile. Cross-check side effects — the email service and payment gateway logs enumerate exactly which orders to restore or apologize for.
  3. Prevent silent divergence: the old primary, if it returns, must be rewound or re-cloned, never rejoined with its extra transactions.

To the business, in their language: "Our current setup can lose the last few seconds of confirmed work if the database machine dies — that is called our recovery point objective.

We can make that window zero by having every commit wait for a second machine, which adds latency to every write and couples our uptime to two machines.

Tell me what a lost order costs, and I will tell you which configuration is cheaper." That is a priced decision for them, not a technical confession.

Land it Async replication means acknowledged work can die with the primary — the senior move is to quantify the window, recover what the old logs allow, and put the zero-loss-versus-latency choice in front of the business with prices attached.

Likely follow-ups
"How exactly would you extract the missing transactions from the dead primary's disks?"

If the volume is intact, I mount it on a recovery host and do not start the database on it.

In MySQL, mysqlbinlog reads the last binlog file, and with GTIDs I can compute the exact set the new primary is missing by comparing the old server's gtid_executed against the new one, then filter to those transactions and review them as SQL before replaying any.

In Postgres, pg_waldump lists the records in the final WAL segments, and to get row-level content I start the old data directory in an isolated container with no network, create a logical replication slot, and decode from the divergence LSN, or simply query the recovered instance for rows newer than the promotion point.

Everything extracted is reviewed and applied with a script, never blindly replayed.

"The business asks: could we have avoided sending the confirmation email? Is there a design that prevents this class of problem?"

Yes, two options. Semi-synchronous replication makes the commit itself wait until a replica has the data, so the email is never sent for a transaction that only one machine holds.

Or, without changing replication, the email is triggered from the replicated change rather than from the primary's commit: an outbox row written in the transaction is picked up by a relay that reads from a replica, or a CDC consumer, so an order that never reached a replica never sends an email.

The second option adds a delay of the replication lag to the email but leaves commit latency untouched. Both are cheap compared with reconciling lost orders by hand, and I would offer the business the choice with those trade-offs.

"What goes into the postmortem for this incident, and what is the one metric you add afterwards?"

The timeline: the primary's last heartbeat, the replica's replay position at promotion, the count of transactions between them from the recovered binlog or WAL, and the list of affected orders matched against the email service logs.

The contributing factors: async replication chosen without a stated RPO, no monitoring of lag at the moment of failover, and side effects fired directly on commit.

The actions: a decision from the business on RPO with the cost of semi-sync attached, an outbox for side effects, and a runbook step to record replica lag before promoting.

The metric I add is replication lag in bytes and seconds on every candidate replica, graphed and captured by the failover tool at promotion time, so the next incident's loss window is a known number within minutes.

Q138. "Why not run multi-primary replication and write to both nodes? It sounds like free capacity and free failover."

Reveal answer

Strong answer Because two nodes accepting writes to the same data must answer a question single-primary systems never face: what happens when both sides change the same row in the same window?

Replication ships both changes across, each node applies the other's, and now you need a conflict rule. "Last write wins" is the common one, and it is silent data loss with a timestamp for an alibi — one user's update simply evaporates.

Uniqueness is worse: both nodes can accept the same email signup or issue the same auto-increment value, and the constraint violation surfaces only when replication meets, on neither user's request. Add DDL coordination and the operational puzzle of replication breaking in both directions at once.

Certification-based systems — Galera, MySQL Group Replication — do solve this properly by having the cluster agree on transaction ordering and abort conflicting writers, but the price is that every commit pays a coordination round and hot-row workloads see deadlock-style aborts the application must retry.

The honest observation is that most teams who ask for multi-primary actually want fast, reliable failover — which single-primary with a good failover manager already provides — not concurrent writes to the same rows from two places.

Land it Multi-primary converts write conflicts from impossible into a policy you must live with — one primary with automated failover gives the availability people actually wanted, without the conflicts.

Likely follow-ups
"How do Galera and Group Replication actually detect conflicts?"

Both use certification-based replication. A transaction executes locally on one node with no cross-node locks.

At commit time, its writeset, the set of row keys it changed plus the changes, is broadcast to all nodes through a total-order group communication layer, so every node receives writesets in the same global order.

Each node then certifies the writeset by checking whether any concurrent writeset already ordered before it touched the same keys; if so, the later transaction is rejected, and the client that issued it gets a deadlock-style error at commit time and must retry.

Because every node runs the same deterministic check in the same order, they all reach the same decision without a coordinator. The cost is a group round-trip per commit and retries on hot rows.

"When would you actually use multi-primary, or Group Replication in single-primary mode?"

Group Replication in single-primary mode is a good answer for automatic failover with built-in consensus: only one node accepts writes, the group elects a new primary when it dies, and the writesets are already on a majority of nodes at commit, so you get semi-sync-like durability and fencing for free.

That is what most people who ask for multi-primary should deploy.

True multi-primary makes sense when writes are naturally partitioned by node, for example each regional site writing only its own tenants, so conflicts are structurally rare and the multi-primary mode is really about local write latency and surviving a region without promotion.

I would not use it for a general workload where any node may update any row.

"What are the hidden operational rules of Galera-style clusters?"

Every table needs a primary key, because certification works on keys, and tables without one cause errors or undefined behavior. Large transactions are limited by wsrep_max_ws_size and can stall the whole cluster while a huge writeset is certified and applied everywhere.

DDL is either run cluster-wide with a total order lock, which blocks the cluster for the duration, or through rolling schema upgrade mode with strict compatibility rules.

A node that falls behind triggers flow control, which pauses writes on every node until it catches up, so the slowest node sets the cluster's write speed. And a cluster that loses quorum goes read-only until a human bootstraps it.

Each of these has bitten teams who expected a drop-in replacement for a single primary.

Q139 · Scenario. "You need Elasticsearch kept in sync with your orders table. A teammate proposes writing to both from the service. Design the better pipeline."

Reveal answer

The real test Whether you know why dual-writes drift and can design a CDC pipeline with its delivery guarantees stated honestly.

Strong answer Dual-writing is the trap: the service writes the database, then the index — and any crash, timeout, or deploy between the two leaves them permanently disagreeing, with no record of what was missed. There is also no ordering guarantee once retries and concurrent requests interleave. The better design is CDC — change data capture: treat the database's own replication log as the event stream.

  1. Capture: a Debezium-style connector tails the MySQL binlog, or Postgres's logical decoding — the facility that turns WAL into a stream of row-change events — and publishes each insert, update, and delete to Kafka. The service writes only the database; the log is the single source of truth, so nothing can be missed: if it committed, it is in the log.
  2. Ordering: events are published per key in commit order — changes to order 1001 arrive in sequence. Partition the topic by primary key so that per-key order survives consumer parallelism; there is no total order across different keys, which is fine.
  3. Delivery honesty: the pipeline is at-least-once — after a connector or consumer restart, some events replay. So the consumer must be idempotent: reapplying an event produces the same state. Indexing by primary key as an upsert gives this naturally; adding a version or the log position and rejecting stale updates hardens it against reordering.
  4. Bootstrap and repair: an initial snapshot loads existing rows before streaming starts, and the same snapshot mechanism rebuilds the index after schema changes.

The price to state up front: the index is eventually consistent — search lags writes by the pipeline's latency, typically well under a second, and product must be told that number.

Land it Never dual-write — commit once, let the binlog or WAL be the event stream, and make consumers idempotent upserts, accepting sub-second staleness as the stated price.

Likely follow-ups
"How does Debezium's initial snapshot stay consistent with the stream that follows it?"

The connector records the current log position first, the binlog file and offset or GTID set in MySQL and the LSN in Postgres, and then reads every table inside a repeatable-read transaction that sees a snapshot consistent with that position.

When the snapshot finishes, it starts streaming changes from the recorded position, so no change is lost or double counted at the boundary, although some events from the overlap may be delivered twice, which the idempotent consumer absorbs.

In Postgres, creating the replication slot and taking the snapshot happen in the same step so the slot's starting point matches the exported snapshot.

For a large table the snapshot can take hours, and Debezium's incremental snapshot mode chunks it by primary key while streaming continues, which is what I would use in production.

"What happens when the schema of the orders table changes? Does the pipeline break?"

The connector sees the change, since MySQL logs DDL in the binlog and Postgres logical decoding reports new column layouts on the next row change, and it emits events with an updated schema, usually through a schema registry.

The consumer must handle a new optional column gracefully, which it does if it maps by name and ignores unknown fields. Where it breaks is a renamed or removed column that the Elasticsearch mapping still expects, or a type change.

So schema changes follow expand and contract here too: add the column, update the consumer to read it, only then stop using the old one.

I test every migration against a staging pipeline with the connector running, because a broken CDC consumer means the search index silently stops updating.

"Kafka is not available in our stack. Can you do this without it?"

Yes. The essential part is that the database's own log is the source, not that Kafka carries it.

In Postgres a small service can consume a logical replication slot directly using the pgoutput or wal2json plugin and write to Elasticsearch, acknowledging the LSN after each successful write so the slot only advances on success.

In MySQL a library that speaks the binlog protocol does the same.

Without a broker you lose replay for other consumers and buffering during an Elasticsearch outage, so the consumer must stop advancing the slot when the index is down, which pins WAL on the primary; that is the risk to monitor.

A simpler alternative is the outbox table: the service writes an event row in the same transaction and a poller ships it, which needs no log access at all.

"How do you know the index is correct, not just that the pipeline is running?"

Two checks. A freshness check: a heartbeat row updated on the primary every few seconds flows through the pipeline, and the consumer records when it saw it; the gap is end-to-end lag on a dashboard, with an alert above a threshold.

A correctness check: a nightly job samples a few thousand order IDs, fetches each from the database and from Elasticsearch, compares the fields, and reports mismatches; it also compares total counts per day.

Mismatches usually reveal a consumer bug on some event shape, such as a delete that was indexed as an update. When the job finds drift, I fix the consumer and re-snapshot the affected range rather than patching documents by hand.

Q140. "How do you serve users in three continents from a relational database without a globally distributed database?"

Reveal answer

Strong answer The sane default is read-local, write-single: one region owns the primary and all writes; the other regions run replicas — cross-region asynchronous replication — and serve reads locally.

Reads, which dominate most workloads, get local-region latency; writes pay one intercontinental round-trip, roughly 100–250 milliseconds, which checkout-style flows absorb far more gracefully than people fear. Correctness stays simple because there is exactly one write history and no conflicts to resolve. Two disciplines make it work.

First, remote-region replicas lag by the link latency plus apply time, so the read-your-writes routing from earlier applies across regions: after a write, the user's session reads from the primary region for a sticky window.

Second, failover across regions is a business event, not a reflex — promoting the Frankfurt replica while Virginia is merely partitioned away is how you get intercontinental split-brain, so cross-region promotion should demand quorum and usually a human.

If a product truly cannot accept write latency from every region — collaborative editing, regional marketplaces — the honest options are partitioning tenants by home region, each region being primary for its own tenants, or graduating to a consensus-based distributed SQL system, which is the next question's trade.

Land it Local reads, one global write region, sticky read-your-writes routing — you keep single-history correctness and give three continents fast pages, promoting across an ocean only when a human agrees the region is truly gone.

Likely follow-ups
"Product says 200 milliseconds on every write is unacceptable for users in Singapore. What are the options in order of cost?"

First, hide it: make writes asynchronous from the user's point of view by accepting the request at the edge, returning immediately, and completing the write in the background, which suits things like analytics events and notifications but not payments.

Second, reduce round-trips: batch several writes into one transaction and one call, since it is the count of round-trips, not the bytes, that costs. Third, move the primary to the region with the most writes, if the traffic is lopsided.

Fourth, partition tenants by home region so each region is primary for its own customers; cross-region operations then become rare and can be slow. Fifth, distributed SQL with regional leaseholders, which is the expensive last step. Most products stop at the second or third.

"How do you design the per-region-primary layout, and what breaks?"

Each tenant has a home region stored in the directory, and each region runs a primary for its tenants plus replicas of the other regions' data for local reads.

A request for a tenant is routed to that tenant's home region for writes, wherever the user is.

What breaks is anything global: a unique username across all regions cannot be enforced by any one primary, so it needs a small global service or a reservation table replicated synchronously; cross-tenant features such as marketplaces need cross-region transactions, which become sagas; and moving a tenant between regions is a migration with a write pause.

Backups, failover, and schema migrations now happen per region and must be coordinated so all regions run compatible schemas.

"The Virginia primary region is really down. Walk me through the cross-region promotion."

First I confirm it is down from more than one vantage point, including a probe outside both regions, and that the failure is the region and not our network path.

Then I check the Frankfurt replica's lag at the last contact, which is the data we are about to lose, and I record it.

Then I fence Virginia as far as I can, by disabling its DNS entry and its write endpoint at the global load balancer, so if it comes back it cannot take writes.

Then I promote Frankfurt, repoint the global write endpoint, and re-point the other region's replicas to stream from Frankfurt, which for Postgres means they must follow the new timeline. Then I communicate the loss window. When Virginia returns it is rebuilt as a replica, never rejoined.

Drill · Polyglot judgment

The closing group tests taste: whether you can say when the relational database stops being the answer — and resist adding datastores when it has not.

Q141. "When is Postgres or MySQL genuinely the wrong tool? Give me your honest checklist."

Reveal answer

Strong answer My checklist is short, because a tuned relational database covers more than people assume. It is genuinely the wrong tool when:

  • Relevance-ranked text search is the product — typo tolerance, ranking, facets at scale want a search engine.
  • Analytics that scan billions of rows across few columns — row-oriented storage reads whole rows, so a column store wins by orders of magnitude.
  • Extreme-throughput ephemeral data — caches, sessions, counters at hundreds of thousands of operations per second with expiry — belongs in memory, not in a durability-first engine.
  • Metrics-style time series at very high ingest, where compression and downsampling are the workload.
  • Event streaming with fan-out and replay — many consumers reading the same firehose independently is a log's job, not a table's.
  • Deep graph traversal — six-hops-out queries as the core product, where every hop is another self-join.

Equally important is what does not make the list: "our data is JSON" (both engines index JSON well), "we need scale" undefined (read replicas and partitioning go far), and "the schema changes a lot" (migrations are a solved discipline). Each list item earns a specialized store only when the need is measured, not predicted.

Land it The relational engine loses on ranked search, columnar analytics, in-memory throughput, metric firehoses, stream fan-out, and deep graphs — and on very little else, which is the point of the checklist.

Likely follow-ups
"Why is row storage so much worse for analytics? Give me the numbers."

A row store reads whole pages, and each page holds complete rows.

A query that sums one 8-byte column over a table with 40 columns averaging 400 bytes per row must read all 400 bytes to get its 8, so it reads fifty times more data than it uses.

On a billion rows that is 400 GB scanned for 8 GB of useful bytes.

A column store keeps each column in its own file, so it reads exactly the 8 GB, and because a column contains similar values it compresses five to twenty times, so the actual read is often under one gigabyte.

Add vectorized execution, which processes thousands of values per CPU instruction batch, and the same query runs in seconds instead of many minutes. The row store wins the opposite case: fetching one complete row by key.

"How would you verify that the relational database is actually failing before buying the specialized store?"

I write the specific requirement as a number and test it.

For search, that is a p95 latency target at a corpus size and a relevance feature list; I load the real data into Postgres full-text search and measure, then I try the same queries against a single-node Elasticsearch.

For analytics, I take the ten slowest reporting queries from pg_stat_statements and run them against a partitioned, indexed copy with rollup tables; if they still take minutes, I try ClickHouse on the same data. For throughput, I run a load test at three times current peak.

The specialized store must win by a large factor on a real workload, not a synthetic one, and I write down the result so the decision is auditable later.

"What about geospatial and graph queries? Are those on the list?"

Geospatial is not, because PostGIS makes Postgres one of the best spatial databases available, with GiST indexes for containment and distance queries, and MySQL has usable spatial indexes too. Graph is on the list only for deep traversals as the core product.

Two or three hops, such as friends of friends or a permission hierarchy, are fine with recursive common table expressions in either engine, and Postgres handles a few million edges that way with proper indexes on both endpoints.

Where it fails is unbounded traversals across hundreds of millions of edges, path finding, or graph algorithms like community detection, where a native graph store such as Neo4j keeps adjacency in memory and walks pointers instead of joining.

Most applications that think they need a graph database need an edges table.

Q142. "You put Redis in front of the database. What does it absorb, and what does it quietly corrupt?"

Reveal answer

The real test Whether you respect the cache as a consistency liability, not just a speed feature.

Strong answer What it absorbs: repeated reads of hot keys.

A product page read ten thousand times a minute becomes one database read per expiry instead of ten thousand; session lookups, rendered fragments, expensive aggregates, and rate-limit counters all move to sub-millisecond memory access, and the database's buffer pool stops being churned by traffic that never changes.

That can be a ten-to-hundred-fold cut in read load. What it quietly corrupts: freshness and truth.

The moment data lives in two places, every write creates a window where the cache lies — a user updates their price, the cache still holds the old one, and unlike a lagging replica the cache never converges on its own; a missed invalidation is stale forever until the TTL — time-to-live, the entry's expiry — rescues it.

The discipline is cache-aside with delete-on-write — read the cache, fall back to the database and populate, and on every write delete the key rather than update it — plus a TTL on everything as the backstop; the race conditions inside even that pattern belong to the caching drill.

The second corruption is subtler: teams start treating Redis as a datastore. It is memory with configurable persistence and an eviction policy — under pressure it deletes your data by design — so nothing lives only in the cache.

Land it Redis absorbs the repeated-read flood, and in exchange every write path inherits an invalidation duty — cache-aside, delete-on-write, TTL as the safety net, and never as the source of truth.

Likely follow-ups
"Why delete on write rather than update the cache with the new value?"

Because two concurrent writers can race: writer A updates the database to price 10 and writer B to price 12, then B updates the cache to 12 and A updates the cache to 10, leaving the cache at 10 while the database says 12, and it stays wrong until the TTL.

With delete-on-write, both writers delete the key, and the next reader fetches whatever the database says now, so the cache can only be briefly missing, never durably wrong. Deleting also avoids serializing an object the writer may not have fully loaded.

The remaining race is a reader that loaded the old value before the delete and writes it back after, which is narrow and is closed by a short TTL or by a versioned set-if-not-exists.

"What is a cache stampede and how do you prevent it?"

A stampede is when a popular key expires and thousands of concurrent requests all miss at once and all hit the database for the same row, which can take the database down exactly when the cache was supposed to protect it. Prevention has three layers.

Request coalescing: only one request per key per process fetches from the database while others wait on it, which Caffeine's loading cache does in the JVM and a Redis lock like SET key:lock NX PX 5000 does across processes.

Early refresh: refresh a hot key in the background a few seconds before its TTL so it never expires under load. And jittered TTLs, so keys populated together do not expire together. The metric to watch is database queries per second during a cache node restart.

"Redis itself went down. What should the application do, and what usually happens instead?"

It should degrade to reading the database directly with a circuit breaker so it does not wait on Redis timeouts, and the database must have been sized to survive that read load for a short period, which is a capacity decision people forget. What usually happens is one of two failures: the application treats a Redis error as a request failure and the site goes down even though the database is healthy, or the application falls through to the database correctly and the database, which has been running at ten percent load for a year, collapses under the full read load. So I load test the cache-off path quarterly, keep the Redis client timeout short, around 50 milliseconds, and keep read replicas with enough headroom to absorb a cache outage.

"Where does caching quietly break transactional correctness?"

When code reads a cached value and makes a decision that the database would have serialized. For example, checking inventory from the cache and then decrementing in the database lets two buyers both see one item available.

The cache has no isolation level; it is a snapshot with no relation to the transaction. So any check that guards a write must be done in the database with a constraint, a conditional update, or a lock, and the cache is only for display.

The second break is cache population inside a transaction: writing to the cache before the database transaction commits means a reader can see data that is then rolled back. The cache write, or delete, happens after commit, ideally from an after-commit hook.

Q143 · Scenario. "You inherit a system whose team 'chose MongoDB for flexibility' three years ago. The service now assembles orders, users, and plans in application code with four sequential queries per page. Diagnose what happened and say when a document store actually fits."

Reveal answer

The real test Whether you can critique the flexibility argument honestly without turning it into a tribal MongoDB-versus-SQL rant.

Strong answer What happened is a data-model mismatch discovered too late.

The data was relational — orders reference users reference plans — but a document store's unit of work is the single document, so relationships that a relational engine would join in one indexed query became sequential fetches assembled in application code: the N+1 pattern as architecture.

The "flexibility" also turned out to be an unpaid bill. Schema-per-row honesty: schemaless does not mean no schema; it means the schema lives implicitly in application code and in every historical shape of document ever written.

Three years of evolution means readers carry if-else ladders for five generations of order documents, because nothing ever forced old rows to migrate. Meanwhile the consistency tools — multi-entity transactions, foreign keys — were absent or late, so cross-document invariants depend on application discipline.

When a document store genuinely fits: data that is truly an aggregate, read and written as a whole — a content document, a product catalog entry with wildly variable attributes, a user preferences blob — with few cross-entity relationships and access almost entirely by key.

My move on this system would not start with a migration crusade: I would measure which access paths hurt, note that Postgres with jsonb offers the same ragged-attribute flexibility with joins and transactions restored, and price a strangler-style migration of the relational core against living with it.

Land it Document stores fit data that lives and dies as one document — pick by how the data relates, not by fear of migrations, because relationships denied at the database get rebuilt worse in application code.

Likely follow-ups
"How would you actually do the strangler migration from MongoDB to Postgres?"

I pick the entity with the worst access pattern, usually orders, and move it first.

Steps: define the relational schema for orders and order_items, build a CDC or change-stream consumer from MongoDB that writes into Postgres so the new store is continuously populated, backfill history from a snapshot, and verify counts and samples.

Then switch the read path for orders to Postgres behind a feature flag, then the write path, with dual writes during the transition, then remove the Mongo collection.

Each entity follows the same loop, and the join that used to be four sequential queries becomes one SQL statement the day orders and users are both in Postgres. The migration takes months, and the first entity proves the tooling so later ones are faster.

"What would you say to someone who claims MongoDB now has transactions and joins, so the trade-off is gone?"

It is partly true and worth being precise about. MongoDB has multi-document transactions since version 4.0 and the $lookup aggregation stage, which performs a left outer join.

But $lookup is not a general join optimizer: it runs per document with limited index use on the joined side, it cannot join across shards efficiently, and it is easy to produce a plan that scans the foreign collection for each input document.

Transactions across documents carry higher overhead and time limits, and the data model still encourages embedding, so relationships are either duplicated or fetched separately.

The honest position is that the gap has narrowed for occasional joins and small transactions, and a relational engine remains far stronger when relationships are the shape of the data.

"How do you handle the five generations of document shapes during the migration?"

I write one normalization function that takes any historical document and produces the current canonical shape, with explicit handling for each generation discovered by sampling, and I run it over the whole collection to produce a report of unknown shapes before migrating anything.

That function is the single place the if-else ladder lives, and it is unit tested against real examples of each generation. The migration then maps only the canonical shape to relational columns.

Documents that fail normalization go to a quarantine table with the raw JSON and a reason, and a human reviews them; there are always a few hundred. This turns implicit schema into explicit code once, rather than leaving the ladder scattered through every reader forever.

Q144. "Can you keep time-series data — device readings, telemetry — in Postgres or MySQL, or do you need a specialized store?"

Reveal answer

Strong answer You can go remarkably far in the relational engine if you respect the workload's shape.

Time-series is append-only — rows arrive in time order and never change — so the pattern is: a narrow table of (time, source, value), insert-only in batches, partitioned by time range so retention is a partition drop and time-scoped queries prune, exactly as in the partitioning discussion.

Pre-aggregated rollup tables — hourly and daily summaries maintained by a job — serve the dashboards, so raw data is scanned rarely; Postgres's BRIN index type is unusually cheap for such time-ordered data, though the mechanics belong to the index drill.

That design comfortably absorbs thousands to tens of thousands of points per second.

The specialized tier — TimescaleDB, which is Postgres extended with automatic partitioning, native compression, and continuous aggregates, or a ClickHouse-class columnar store — earns its place when the numbers outgrow that: sustained ingest toward hundreds of thousands of rows per second, retention of billions of points where columnar compression cuts storage ten-to-twenty-fold, and analytical scans across long ranges that row storage prices badly.

Timescale is the gentle first step precisely because it keeps SQL, drivers, backups, and the team's expertise intact.

Land it Append-only inserts, time partitions, and rollups carry telemetry a long way in the boring engine — the specialized store is earned by ingest rate and compression math, not by the phrase "time series".

Likely follow-ups
"What is the write path you would build for 20,000 readings per second into Postgres?"

Never one INSERT per reading. The collectors buffer readings for a second or so and write them in batches of a few thousand rows using multi-row INSERT or, better, COPY, which is the bulk-load protocol and is several times faster than inserts.

Each batch is one transaction, so commit overhead is amortized across thousands of rows. The table is narrow, with a timestamp, a device identifier as an integer rather than a string, and the value, partitioned by day or week.

Indexes are kept to a minimum during ingest, typically one on (device_id, time) plus a BRIN on time.

With that shape a single mid-range Postgres server handles tens of thousands of rows per second with modest CPU. MySQL's LOAD DATA or multi-row INSERT gives the same effect.

"How do you keep the rollup tables correct when late data arrives?"

Late readings, for example from a device that was offline, land in a time bucket that has already been aggregated. The rollup job therefore must be able to recompute a bucket, not just append.

I keep a small table of dirty buckets: every batch insert records the min and max time it touched, and the rollup job recomputes any hourly bucket that was touched since its last run, using an upsert on the rollup row.

That makes the job idempotent and late-data safe at the cost of occasionally recomputing an old hour. TimescaleDB's continuous aggregates do exactly this automatically by tracking invalidated ranges.

I also cap how late data can be accepted, say seven days, so very old buckets are frozen and can be compressed or archived.

"What does TimescaleDB's compression actually do, and what is the trade?"

It converts old chunks from row storage into a columnar layout inside Postgres: rows are grouped, typically a thousand at a time per device, and each column is stored as a compressed array using type-specific algorithms such as delta-of-delta for timestamps and Gorilla-style encoding for floats.

Compression ratios of ten to twenty are common on telemetry. Queries that read a range of one device's data become much cheaper because they read compact arrays.

The trade is that compressed chunks are expensive to update or delete individually, since a change requires decompressing the group, so compression is applied only to chunks older than the late-data window.

That is why the design pairs compression with a compress-after policy rather than compressing everything.

Q145. "Product search is LIKE '%term%' today. Walk me up the ladder — when is built-in full-text enough, and when do you pay for Elasticsearch?"

Reveal answer

Strong answer LIKE 'term%' — anchored at the start — can use an ordinary index, but LIKE '%term%' cannot, because a B-tree is sorted from the left and a pattern with a leading wildcard could begin anywhere; that query scans every row and degrades linearly with the table.

The first honest rung up is built-in full-text search: Postgres turns text into a tsvector — a normalized list of word stems — indexed with GIN, and MySQL has FULLTEXT indexes; both give word matching, stemming, basic ranking, and stay inside the database, which means transactional consistency with your data, no sync pipeline, and no new cluster to run.

For "search our few million product names and descriptions," that rung is genuinely enough, and stopping there is often the senior decision.

The Elasticsearch-class engines earn the jump when search becomes product-shaped: typo tolerance and fuzzy matching, relevance tuning per field, faceted navigation with live counts, autocomplete at scale, or corpus sizes where the database's text indexing strains.

The price must be named in the same breath: a separate cluster to operate, and a sync pipeline — the CDC design from the replication section — which means search results lag writes and can drift, so "index freshness" becomes a metric you monitor forever.

Land it Escape LIKE '%…%' with the database's own full-text first — Elasticsearch is bought with a second cluster and a permanent sync-lag budget, so it must be justified by relevance features, not by the word "search".

Likely follow-ups
"Show me the Postgres full-text setup concretely, including how the index stays updated."

I add a generated column: ALTER TABLE products ADD COLUMN search tsvector GENERATED ALWAYS AS (to_tsvector('english', coalesce(name, '') || ' ' || coalesce(description, ''))) STORED, then CREATE INDEX ON products USING gin (search).

Because the column is generated, every insert or update refreshes it automatically with no trigger. The query is WHERE search @@ websearch_to_tsquery('english', 'wireless mouse'), which parses user input safely, and ranking uses ORDER BY ts_rank(search, query) DESC. Weighting name above description uses setweight in the expression.

The GIN index handles millions of rows comfortably. What it lacks is typo tolerance, which pg_trgm trigram indexes can add for fuzzy matching on short fields like names at extra index cost.

"Why is a leading-wildcard LIKE unindexable, and is there any index that helps it?"

A B-tree stores values sorted from the first character, so a prefix like 'wire%' maps to a contiguous range in the index, but '%mouse%' could appear at any position in any value, so there is no range to scan and the engine must examine every row.

The index that helps is a trigram index from the pg_trgm extension: it breaks each value into overlapping three-character pieces, and a GIN index on those pieces can find all rows containing the trigrams of 'mouse' and then verify them.

It supports LIKE, ILIKE, and similarity queries, and it is the right tool for substring matching on names and codes. MySQL has no equivalent; FULLTEXT with n-gram parser is the nearest option for substring-like matching.

"Product wants facets with live counts on ten attributes. Can Postgres do that?"

It can, with a cost that grows with result size.

A faceted query runs the text match and then GROUP BY on each attribute, which is ten aggregations over the matching rows; for a result set of ten thousand rows that is fine, for a million it is slow.

Tricks like a single query with GROUPING SETS or FILTER aggregates reduce it to one pass, and caching facet counts for common queries helps. Elasticsearch computes facets from its inverted index in one pass over posting lists, which is what makes it fast at large scale.

So my answer is: Postgres for a catalog of hundreds of thousands of items with a few facets, Elasticsearch when the catalog is tens of millions or facets are central to the product, and I measure the cutover on real data.

Q146 · Scenario. "Your background workers poll a jobs table, and two workers keep grabbing the same job. Fix it in the database, and tell me when this design stops being enough."

Reveal answer

The real test Whether you know the SKIP LOCKED dequeue pattern and can honestly place the boundary where a real broker takes over.

Strong answer The double-grab is a check-then-act race: both workers SELECT the same ready row, then both UPDATE it to running. The database fix is FOR UPDATE SKIP LOCKED — lock the rows you claim, and skip rows other workers have locked instead of waiting on them, so each worker dequeues a disjoint batch:

dequeue.sql
BEGIN;
SELECT id, payload FROM jobs
WHERE status = 'ready' AND run_at <= now()
ORDER BY run_at
LIMIT 10
FOR UPDATE SKIP LOCKED;   -- locked rows are skipped, not waited on

UPDATE jobs SET status = 'running', locked_by = :worker
WHERE id IN (:claimed_ids);
COMMIT;
-- Works on PostgreSQL and MySQL 8.0+.

This pattern is genuinely good, not a hack, and it has one advantage no broker matches: the job is enqueued in the same transaction as the business change, so "order saved but job lost" is impossible — the same property the outbox pattern in the transactions drill builds on. It carries thousands of jobs per minute comfortably, with an index on (status, run_at) and periodic cleanup of done rows to control bloat. It stops being enough when the workload becomes a stream: sustained throughput toward tens of thousands of messages per second, fan-out where several independent consumer groups each need every message, replay of history, or long retention — at which point polling a hot table burns the database and a log-based broker like Kafka is the right shape. The middle rung, RabbitMQ-class brokers, buys push delivery and routing without Kafka's operational weight.

Land it SKIP LOCKED gives you a transactional queue for free at modest scale — graduate to a broker when you need fan-out, replay, or throughput, not because a table-as-queue sounds unfashionable.

Likely follow-ups
"A worker crashes after claiming jobs. They stay 'running' forever. How do you handle that?"

Every claim records locked_at and locked_by, and jobs carry a maximum runtime. A reaper query runs periodically: UPDATE jobs SET status = 'ready', attempts = attempts + 1 WHERE status = 'running' AND locked_at < now() - interval '10 minutes'.

Jobs whose attempts exceed a limit go to 'failed' for a human.

Because a job may be retried after a crash mid-execution, each job's work must be idempotent, for example by keying its side effects on the job ID. An alternative is to hold the row lock for the whole execution inside one transaction, so a crash releases it automatically, but that keeps a transaction open for minutes, which pins vacuum and locks, so I prefer the lease-and-reaper design for anything longer than a second.

"The jobs table is now 50 million rows of completed jobs and the dequeue query got slow. Why, and what is the fix?"

The dequeue query filters on status = 'ready', and the index on (status, run_at) still has to skip over dead index entries and, in Postgres, dead tuples left by every completed job's UPDATE; the visible ready rows are a tiny slice of a huge, bloated structure.

The fix is to keep the queue table small: move completed jobs to an archive table or delete them in batches within minutes of completion, partition by status or by day so completions are dropped, and use a partial index in Postgres, CREATE INDEX ON jobs (run_at) WHERE status = 'ready', which only contains the rows that matter and stays tiny.

Aggressive autovacuum settings on this table are also essential because its churn is extreme.

"How do you avoid workers hammering the database with polling when the queue is empty?"

Exponential backoff on the polling interval when a poll returns nothing, from 100 milliseconds up to a few seconds, which cuts idle load to a handful of queries per second across the fleet.

In Postgres I add LISTEN/NOTIFY: the enqueue transaction issues NOTIFY jobs_channel after commit, and idle workers block on LISTEN instead of polling, waking instantly when work arrives, with a fallback poll every thirty seconds in case a notification is missed.

MySQL has no notify, so backoff plus a modest floor is the answer there. With ten workers and a one-second idle poll, the load is ten cheap index lookups a second, which is negligible; the danger is only with hundreds of workers and sub-100-millisecond polling.

"What happens with SKIP LOCKED on MySQL under REPEATABLE READ, and are there gotchas?"

SELECT ... FOR UPDATE SKIP LOCKED is available from MySQL 8.0 and works as a locking read, which always reads the latest committed data regardless of the transaction's snapshot, so a worker sees newly ready jobs even in an old REPEATABLE READ transaction.

The gotchas are gap locks: under REPEATABLE READ, a FOR UPDATE on a range takes next-key locks that can block inserts into the same range by the enqueuers, causing contention or deadlocks between producers and consumers.

Using READ COMMITTED for the worker transaction removes gap locks, and LIMIT with an ORDER BY on the indexed run_at keeps the locked range small. Also, SKIP LOCKED makes the result set inconsistent by design, which is fine for a queue and wrong anywhere else.

Q147 · Scenario. "At 11am the OLTP primary went to 100% CPU and checkout latency exploded. The cause: a new BI dashboard querying production directly. Walk me through the response and the right long-term architecture."

Reveal answer

The real test Whether you can explain why analytics kills OLTP mechanically, and lay out the replica-warehouse ladder.

Strong answer OLTP — online transaction processing, many small indexed reads and writes — and analytics are opposite workloads, and the damage has specific mechanisms: the BI — business intelligence — tool's giant scans read cold data through the buffer pool and evict the hot rows checkout needs, so every transaction starts missing cache and hitting disk; the scans saturate CPU and I/O; and their long-running queries hold back MVCC cleanup — vacuum in Postgres, purge of undo history in InnoDB — so the primary bloats while they run. Response in order:

  1. Stop the bleeding: find the offenders in pg_stat_activity or SHOW PROCESSLIST, kill them, and revoke the BI tool's credentials on the primary. Checkout recovers in minutes as the cache re-warms.
  2. Same week: point the BI tool at a read replica — ideally a dedicated reporting replica allowed to lag, per the standby-conflict discussion — and set statement_timeout and a resource-limited role for analyst access so no future query runs unbounded.
  3. Right long-term home: a warehouse — a column store, which in one plain paragraph means data stored column-by-column instead of row-by-row, so a query touching 3 of 40 columns reads only those bytes, and same-typed columns compress tenfold; that is why ClickHouse, BigQuery, Snowflake, and Redshift scan billions of rows in seconds while a row store cannot. Feed it by CDC or nightly loads, and analysts get freedom without a blast radius.
  4. Prevent recurrence organizationally: production credentials for humans and BI tools simply cease to exist; analytics has its own front door.

Land it One workload optimizes for a thousand small transactions, the other for one giant scan — they share hardware only until the scan wins, so analytics gets a replica now and a column-store warehouse as the real home.

Likely follow-ups
"You killed the queries and revoked the credentials, but latency is still bad twenty minutes later. What is going on?"

Two likely reasons.

The cache is still cold: the scans evicted the working set, and checkout's pages are being read back from disk one miss at a time, so latency recovers gradually as the buffer pool refills; the hit ratio graph climbing back toward 99 percent confirms it, and pg_prewarm on the hottest tables speeds it up.

Or the bloat from held-back cleanup is now hurting: while the scans ran, vacuum or purge could not remove dead versions, so hot indexes and tables grew, and every checkout query walks more pages than before.

pg_stat_user_tables dead tuple counts or InnoDB history list length show that; a manual VACUUM on the hot tables, or waiting for purge to catch up, resolves it. If neither, I check whether a different heavy query took the BI tool's place.

"Explain the cache eviction damage in more detail. Does the database not protect the hot set?"

Both engines try. InnoDB's buffer pool is split into young and old sublists, and a page read by a scan enters the old sublist and is evicted unless it is touched again after innodb_old_blocks_time milliseconds, so a single pass scan should not push out hot pages.

Postgres uses a clock-sweep with usage counts and, for large sequential scans, a small ring buffer so scanned pages do not flood shared buffers.

The protection fails when the analytics queries are not simple scans but hash joins and sorts that touch the same pages repeatedly, promoting them, and when they run many at once. And neither engine protects the operating system page cache in Postgres's case.

So the protection reduces the damage but does not prevent it, which is why the queries had to go.

"What guardrails do you put on the analyst replica so the same thing cannot happen there?"

A dedicated role with statement_timeout of ten or fifteen minutes and work_mem set per role so a runaway sort cannot exhaust memory, a connection limit on that role, and the replica allowed to lag with max_standby_streaming_delay raised so their long queries are not cancelled.

Monitoring on the replica's CPU and lag, alerting the analytics team rather than the on-call engineer when it is saturated, because a slow replica is their problem, not the customers'. And a rule that any query that needs more than the timeout is a warehouse query.

In MySQL, the equivalents are max_execution_time on the account, MAX_USER_CONNECTIONS, and a replica that serves nothing user-facing. The replica becomes a sandbox with a fence around it.

"Why not just run the warehouse queries on a bigger replica instead of building a column-store pipeline?"

Because a bigger replica is still a row store, so the queries stay slow and expensive in absolute terms even when they no longer hurt anyone else, and analysts will keep asking for a bigger box every quarter.

A column store answers the same questions ten to a hundred times faster on smaller hardware. The replica is the right first step and remains the right tool for operational reports that need fresh data and modest scans.

The warehouse pipeline earns its complexity once analysts run scans over hundreds of millions of rows daily, or once the reporting replica needs to be larger than the primary.

I present both costs honestly: the replica is a day of work, the pipeline is a quarter, and the replica buys the time to build it properly.

Q148. "Should we move to CockroachDB or Spanner? Give me the honest trade."

Reveal answer

Strong answer Distributed SQL — Spanner, CockroachDB, Yugabyte — delivers something genuinely new: SQL with serializable transactions across nodes and regions, plus automatic sharding, rebalancing, and node-failure survival, so the application never sees shards at all.

The mechanism is also the price tag: every write is committed through a consensus protocol — Raft or Paxos, where a majority of replicas must accept the change before it counts — so a write costs a coordination round-trip at minimum, and a multi-region quorum puts an ocean crossing inside your commit latency: tens to hundreds of milliseconds where a single-node Postgres commit takes one.

Spanner hides some of this with TrueTime, Google's atomic-clock infrastructure, which you rent rather than run.

Beyond latency you pay in operations or vendor dependence — a consensus cluster is a genuinely harder system than one primary with replicas — in ecosystem gaps around extensions and tooling, and in cost.

So the question is whether we have the one problem it uniquely solves: writes originating in multiple regions that must be strongly consistent with each other, or scale-out with full transactional SQL that sharded MySQL would make miserable.

If our need is read locality plus one write region — which is most companies — the previous answers cover it for a fraction of the complexity.

Land it Distributed SQL sells serializable-everywhere and charges consensus latency on every write plus a heavier system to run — buy it for multi-region strong consistency you can name, not for scale you project.

Likely follow-ups
"What is a leaseholder in CockroachDB, and how does it change the latency story?"

CockroachDB splits data into ranges, each replicated to three or more nodes by Raft. One replica of each range holds the lease, which is the right to serve reads for that range without consulting the others, and to coordinate writes.

Reads that reach the leaseholder are fast, roughly local. Writes still require a Raft majority, so a write to a range whose replicas are in three regions pays a cross-region round-trip.

The latency tool is placement: with regional-by-row tables, each row's home region holds the leaseholder and enough replicas for a quorum inside that region, so both reads and writes for a European customer stay in Europe, and only cross-region rows pay the ocean. That configuration is the work you pay for in schema design.

"What ecosystem gaps would actually bite us moving from Postgres?"

As of Aug 2026, CockroachDB speaks the Postgres wire protocol and most of its SQL, so drivers and ORMs work, but extensions do not: no PostGIS in the full sense, no pg_trgm, no pgvector, no custom C extensions, and stored procedures and triggers are limited.

Some features behave differently: sequences are non-monotonic across nodes by default, large transactions are slower and have size limits, and serializable isolation means retry errors that applications must handle with a retry loop. Tooling like pg_dump, pg_stat_statements, and pgBouncer are replaced by the vendor's equivalents.

Any of these is manageable; together they mean a migration is a project with a test matrix, not a connection-string change.

"When would Spanner beat CockroachDB, or the reverse?"

Spanner is fully managed by Google, uses TrueTime for external consistency without clock uncertainty penalties, and scales to very large deployments with no operations on your side; it locks you into Google Cloud and its own SQL dialect, with a Postgres interface that is a partial compatibility layer. CockroachDB runs anywhere, including on your own hardware or across clouds, is closer to Postgres in dialect, and offers a managed service too; you pay for it with more operational involvement in self-hosted mode and with clock-skew configuration that Spanner does not need. If the company is already on Google Cloud and wants zero operations, Spanner; if multi-cloud or on-premises matters, or Postgres compatibility is the priority, CockroachDB.

Q149. "The team is adding semantic search and wants to buy a vector database. Ground me: what is it, and do we need one?"

Reveal answer

Strong answer In one grounded paragraph: an embedding is an array of a few hundred to a few thousand floating-point numbers that a model produces to represent a text's or image's meaning, such that similar things get nearby vectors; a vector database stores these arrays and answers "the k nearest vectors to this one" using an approximate nearest neighbor index — typically HNSW, a graph structure walked greedily toward the query — because exact comparison against millions of vectors per query is too slow.

The judgment call: pgvector, the Postgres extension, adds a vector column type plus HNSW indexing to the database we already run, and below roughly ten million vectors at ordinary query rates it performs entirely respectably.

It has a structural advantage no dedicated engine matches: the vectors sit in the same database as the rows they describe, so filtering by tenant, joining to products, transactional consistency on update, and one backup story all come free — where a separate vector store reintroduces the sync-pipeline and drift problems we discussed for search.

Dedicated engines — Milvus, Pinecone, Weaviate-class — earn their place at hundreds of millions of vectors, high query throughput, or heavy index-tuning needs.

For a first semantic-search feature over a product catalog of a few hundred thousand items, buying a new datastore is solving a scale we do not have.

Land it Under about ten million vectors, pgvector inside the database you already operate wins on joins, consistency, and ops — a dedicated vector store is a scale decision, not a starting point.

Likely follow-ups
"How does an HNSW index work, and what does it cost to build and store?"

HNSW, hierarchical navigable small world, is a layered graph. Each vector is a node connected to its nearest neighbors; the bottom layer contains every vector, and each higher layer contains a random sample with longer-range links.

A query starts at the top layer, greedily moves to the neighbor closest to the query, descends a layer, and repeats until it reaches the bottom, then explores a candidate set of size ef_search to find the best k.

Build time is significant: pgvector builds at tens of thousands of vectors per second per core for 1,536-dimension vectors, so a million vectors takes minutes.

Storage is the vectors themselves, six kilobytes each at 1,536 float32 dimensions, plus the graph links, roughly 20 to 50 percent more. The index must fit in memory for good performance.

"How do you combine a vector search with a tenant filter efficiently?"

The naive approach, finding the top 10 nearest and then filtering by tenant, returns fewer than 10 or zero results for small tenants, because the nearest vectors belong to other tenants.

pgvector handles a WHERE clause by applying it during the index scan, but with HNSW it may still stop early; since pgvector 0.8, iterative index scans keep searching until enough rows pass the filter.

Two structural fixes: a partial index per large tenant, or partitioning the table by tenant so each partition has its own small HNSW index. Increasing ef_search widens the candidate set at a latency cost.

A dedicated vector database has the same problem and solves it with filtered search options; there is no free lunch, just a schema decision to make deliberately.

"What is the cost of getting the embeddings, and how do you keep them fresh when products change?"

Each embedding is produced by calling an embedding model, which costs a fraction of a cent per thousand tokens with hosted providers as of Aug 2026, or CPU time with an open model.

For a few hundred thousand products the initial run is a few dollars and a few hours.

Freshness is a pipeline problem: when a product's name or description changes, its embedding must be recomputed, so I treat the vector as derived data, populated by a background job that reads from an outbox or CDC stream and writes the new vector in the same row.

A version column records which model produced it, because changing the model means re-embedding everything, and vectors from two models cannot be compared. That job and its lag get monitored exactly like the search index.

Q150. "Last one. An architect proposes Redis, Mongo, Elasticsearch, Kafka, and ClickHouse for the new platform — each 'best for its job'. How do you respond?"

Reveal answer

The real test The taste question: whether you price datastores by their total cost of ownership rather than their feature lists.

Strong answer I would respond that each store is being priced by its best feature and none by its total cost.

Every datastore we adopt is a permanent operational commitment: backups and restore drills, replication and failover, monitoring and alerting, security patching, capacity planning, driver and library upkeep, at least two people who understand it deeply, and a slot in the on-call rotation — multiplied by five, plus the sync pipelines between them, and every pipeline is a consistency bug waiting for its incident.

This is the "boring technology" argument: a team has a limited budget of novelty, and it should be spent on the product, not the plumbing.

My counter-proposal is capability honesty: Postgres alone gives us JSON documents with indexing, solid full-text search, a transactional queue via SKIP LOCKED, pub/sub with LISTEN/NOTIFY, and vectors with pgvector — adequate versions of most of that list, in one system with one backup story and one expertise pool.

So the platform starts as Postgres plus, in all likelihood, Redis — caching earns its keep almost immediately.

Every further store gets admitted by the same test: a specific, measured requirement that the boring stack demonstrably fails, an owner for its operations, and the sync pipeline priced into the estimate.

Kafka, ClickHouse, and Elasticsearch all pass that test at real scale; the discipline is making them pass it, on evidence, one at a time.

Land it Choose boring until a measured requirement breaks it — every additional datastore is an on-call rotation, a backup story, and a sync pipeline, and "best tool for the job" only counts after that bill is in the estimate.

Likely follow-ups
"Give me the concrete operational cost of one extra datastore in engineer-hours."

From experience, a production-grade datastore costs roughly one to two engineer-days a week in steady state: patching and upgrades, backup verification, capacity reviews, alert tuning, and the occasional incident, plus the initial setup of high availability, backups, monitoring, and runbooks, which is two to four weeks.

On-call load rises because every store has its own failure modes, and each requires at least two people who can debug it at 3am, which means training time.

Then there is the pipeline between it and the source of truth, which has its own lag alerts and reconciliation jobs. Multiply by five stores and that is a full-time engineer or more spent on plumbing before any product work.

Those numbers belong in the platform proposal next to the feature list.

"Which of the five would you admit first, and what evidence would earn the next one?"

Redis first, almost on day one, because caching and rate limiting earn their keep at very modest traffic and it is simple to operate.

Next, in most products, is Elasticsearch, and the evidence is a measured search requirement Postgres full-text cannot meet, such as typo tolerance and facets over millions of items with a p95 under 100 milliseconds.

Kafka comes when several independent consumers need the same event stream with replay, which usually happens when the company has more than a handful of services. ClickHouse comes when analytical queries measurably fail on a replica. MongoDB rarely earns admission next to Postgres with jsonb.

Each admission needs a written owner, a backup and restore drill, and a dashboard before it takes production traffic.

"The architect says Postgres cannot handle our expected scale, so we should build for it now. How do you answer?"

I ask for the number. Expected scale is usually stated as users, and I convert it into queries per second, write rate, and data volume at launch and at year two.

A single Postgres primary with replicas serves thousands of transactions per second and terabytes of data, which covers the first years of most products that are not already large.

If the numbers really exceed that, the answer is a specific store for the specific bottleneck, not five stores for hypothetical ones.

Building for a scale that may never arrive slows the team now, when speed matters most, and the fastest way to fail to reach that scale is to spend the early years operating infrastructure instead of shipping.

The design should make the later additions possible, not build them in advance.

09 · DrillProduction Database Operations — Q151–Q200

Everything before this section was about designing and querying. This section is about the part of the job that starts when the pager goes off: a production database misbehaving while real users wait. Interviewers test operational seniority almost entirely through scenarios — they describe the 3am symptom and watch whether you triage in the right order, mitigate before you root-cause, and know which commands are safe to run against a live system.

Drill · Incident triage — the first ten minutes

This group tests whether you have actually held the pager: whether you check things in the right order, kill the right session in the right way, and stay calm enough to preserve evidence.

Q151 · Scenario. "It is 3am and the alert just says 'the database is slow'. Walk me through your first ten minutes, step by step."

Reveal answer

The real test Order and calm under pressure — a junior jumps straight into the database; a senior first proves the database is actually the problem.

Strong answer My first ten minutes are a fixed checklist, in this order:

  1. Decide whether it is really the database. I look at the app side first: the connection pool — the fixed set of database connections the app keeps open and reuses — via HikariCP metrics. If threads are queuing for connections but the database CPU and IO (input/output — how hard the disks are working) are low, the app is holding connections open, often waiting on some other slow dependency. The database is the victim, not the cause.
  2. Ask what changed. A deploy in the last few hours, a traffic spike, a new cron job, a schema migration, a config change. Most incidents follow a change, so the deploy log is faster than any profiler.
  3. Look at live activity: pg_stat_activity in Postgres or SHOW FULL PROCESSLIST in MySQL — the live list of every connected session and what it is doing right now. I count sessions by state and look for long-running statements and lock waits.
  4. Check the four vitals together: CPU, IO wait, connection count against the maximum, and replication lag — how far behind the read copies are.
  5. Mitigate. If one query or one client is clearly the cause, I kill it or shed that load first, and only then start root-causing properly.

Land it The first question is never "what is wrong with the database" — it is "is the database actually the thing that is wrong".

Likely follow-ups
"What are the exact commands you run in the first two minutes on Postgres, and what are you looking for in each?"

First, SELECT state, count(*) FROM pg_stat_activity GROUP BY state, to see whether the server is full of active queries, idle-in-transaction sessions, or lock waiters.

Second, SELECT pid, now() - xact_start, wait_event_type, wait_event, left(query, 60) FROM pg_stat_activity WHERE state <> 'idle' ORDER BY xact_start LIMIT 20, to see the oldest transactions and what they are waiting on. Third, SELECT count(*) FROM pg_stat_activity WHERE cardinality(pg_blocking_pids(pid)) > 0, to count blocked sessions.

Fourth, on the operating system, top or vmstat 1 for CPU, iowait, and swap. Fifth, SELECT * FROM pg_stat_replication for lag. In MySQL, SHOW FULL PROCESSLIST, SELECT * FROM sys.innodb_lock_waits, SHOW ENGINE INNODB STATUS for the history list and semaphores, and SHOW REPLICA STATUS.

"Nothing in your checklist is abnormal, but users say it is slow. What next?"

Then the database is probably not the bottleneck and I widen the view. I check the application's own latency breakdown, since a slow downstream service or a garbage-collection storm often gets blamed on the database.

I check the pool metrics again for wait time, which shows the pool is too small even when the database is idle.

I check the network between application and database, for example packet loss or a saturated link, using the round-trip time of a trivial SELECT 1 from an application host.

I check whether one specific query rather than the whole database is slow, by looking at pg_stat_statements mean time deltas over the last ten minutes. And I check DNS, because a slow resolver adds seconds to every new connection. The rule is to follow the latency, not the assumption.

"How do you decide between failing over and continuing to debug?"

Failover is the right mitigation when the problem is the machine, not the workload: a disk that has gone slow, a kernel issue, memory errors, or a corrupted buffer state that a restart would clear. It is the wrong mitigation when the cause is a bad query, lock chain, or connection storm, because the same workload will follow to the new primary within minutes and now I have also lost the evidence and any async-replicated tail. So my rule is: if I can name the workload cause within ten minutes, I fix the workload; if the host metrics show hardware-level trouble or the cause is invisible after that time and the replica is healthy and caught up, I fail over and debug the old primary at leisure.

"What evidence do you capture before you kill anything?"

I copy pg_stat_activity or the full processlist to a file with a timestamp, including the full query text, using psql's \o or SELECT ... INTO a table on a scratch schema. I save the lock graph, pg_locks joined to pg_stat_activity, or the innodb_lock_waits view.

I snapshot pg_stat_statements or performance_schema summary tables into a table so I can compute deltas later. I note the exact time, the deploy version, and any config change. I grab the last few hundred lines of the server log.

This takes under a minute with a prepared script in the runbook, and it is the difference between a postmortem that finds the cause and one that says "it was slow and then it was not."

Q152 · Scenario. "During an incident you query pg_stat_activity and see the output below. Read it to me like you would to a teammate — what does each row tell you?"

Reveal answer

The real test Whether you know which session states matter and which are noise.

Strong answer Here is the excerpt:

pg_stat_activity-excerpt.sql
SELECT pid, state, wait_event_type, wait_event,
       now() - xact_start AS xact_age, left(query, 40) AS query
FROM pg_stat_activity WHERE state <> 'idle';

 pid  | state               | wait_event_type | wait_event    | xact_age | query
------+---------------------+-----------------+---------------+----------+------------------------------
 4211 | active              | Lock            | transactionid | 00:04:12 | UPDATE orders SET status = ...
 4188 | idle in transaction |                 | ClientRead    | 00:09:55 | UPDATE orders SET note = ...
 4090 | active              | IO              | DataFileRead  | 00:00:03 | SELECT sum(amount) FROM ...

Row 4211 says active, but the wait event says Lock: it is not doing work at all, it has been stuck waiting for another transaction's lock for four minutes. Row 4188 is the interesting one: idle in transaction means it started a transaction, ran that UPDATE, and is now doing nothing — waiting on its own client (ClientRead) while still holding every lock it took, for almost ten minutes. That session is very likely what 4211 is stuck behind, and the query column shows its last statement, not a running one. Row 4090 is genuinely working: active and reading data files, only three seconds in. In MySQL I read the same story from SHOW PROCESSLIST: the State column ("Waiting for table metadata lock" is the alarm), Command = Sleep with an open transaction as the silent blocker, and the Time column for age.

Land it The dangerous session is rarely the busy one — it is the quiet one holding locks while it waits for its client.

Likely follow-ups
"What are the possible values of state and the important wait_event_type values, and what does each mean?"

state is one of active, meaning executing a query; idle, meaning connected and waiting for a command with no open transaction; idle in transaction, meaning inside a transaction but not running anything; idle in transaction (aborted), meaning an error occurred and the transaction is waiting for a rollback; and fastpath function call or disabled in rare cases.

wait_event_type is NULL when the backend is running on CPU. Lock means waiting for a heavyweight lock such as a row or table lock. LWLock means an internal short lock, such as buffer contention. IO means waiting for disk.

Client means waiting for the client to send or receive, which is where an idle-in-transaction session sits. IPC is waiting for another process, such as parallel workers. Activity is a background process idling.

"Tell me what you would run next to confirm that 4188 is blocking 4211."

SELECT pg_blocking_pids(4211), which returns the array of process IDs holding locks that 4211 is waiting for; if it returns {4188}, that is the confirmation.

Then SELECT locktype, relation::regclass, mode, granted FROM pg_locks WHERE pid IN (4188, 4211) shows the specific locks: 4188 holds a RowExclusiveLock on orders and a granted transactionid lock, while 4211 has a not-granted ShareLock on 4188's transaction ID, which is how a row-level wait shows up.

Because 4188 is idle in transaction and its client is not sending anything, the next step is pg_terminate_backend(4188), after saving its query text and application_name for the postmortem, since the application that left it open is the bug.

"The query column shows the last statement. How do you find the full history of what an idle-in-transaction session did?"

pg_stat_activity only keeps the most recent statement, so the history comes from logs.

If log_statement is set to mod or all for that role, or if the session's statements exceeded log_min_duration_statement, the log has them with the same process ID, and grep for that PID between backend_start and now gives the sequence.

If nothing was logged, pg_locks tells me which tables the session touched, because it holds locks on every table it wrote or read with FOR UPDATE. From the application side, the client_addr and application_name identify the service, and its request logs or traces at that timestamp show which handler opened the transaction.

For future incidents I set log_min_duration_statement low and application_name per service, so this reconstruction is a query rather than detective work.

Q153 · Scenario. "You find hundreds of sessions in state 'idle in transaction'. The database is otherwise healthy. What is happening, and what do you do about it?"

Reveal answer

The real test Whether you can trace a database symptom back to an application design mistake.

Strong answer "Idle in transaction" at that scale means the application is opening a transaction and then doing something slow inside it — almost always a remote call: an HTTP request, a message publish, a cache call, sitting between the first query and the commit. Each session holds its locks and pins cleanup for the whole duration. My steps:

  1. Confirm the pattern: group the idle-in-transaction sessions by application_name and client_addr in pg_stat_activity, and look at the last query each ran. They usually all point at one service and one code path.
  2. Trace it in the code: in Java this is typically a @Transactional method that also calls a remote service, so the transaction stays open for the full remote-call latency. When the remote service slows down, hundreds of transactions hang open together.
  3. Explain the damage: those sessions block other writers, and they stall cleanup. Postgres uses multi-version concurrency control (MVCC) — instead of changing a row in place it writes a new version and cleans the old ones later — and an old open transaction forces the database to keep every old version since it began.
  4. Fix the code: shrink the transaction to just the database work; do remote calls outside it, or use an outbox pattern.
  5. Add the guardrail: idle_in_transaction_session_timeout in Postgres (say 60 seconds) kills exactly this kind of session automatically. In MySQL the closest cousin is a low wait_timeout plus monitoring information_schema.innodb_trx for old transactions.

Land it A transaction should wrap database statements, never a network round-trip — and a timeout should enforce that rule when a human forgets it.

Likely follow-ups
"You set idle_in_transaction_session_timeout to 60 seconds. What could that break?"

Any legitimate flow that pauses inside a transaction for longer than a minute.

Interactive psql sessions where a DBA opens a transaction and thinks; migration tools that hold a transaction while waiting for a lock retry; batch jobs that open a transaction, call a slow external validator, and then commit; and ORM sessions with an open transaction across a long user interaction.

When the timeout fires, the session is terminated and the transaction rolled back, so the client sees a connection error on its next statement, and if it does not handle that, the job fails.

So I roll it out per role, starting with the web application roles where a minute is generous, keep it higher for migration and admin roles, and watch the log for "terminating connection due to idle-in-transaction timeout" to see what it caught.

"Show me the Java code shape that causes this, and the corrected shape."

The bad shape is a service method annotated @Transactional that saves an order, then calls paymentClient.charge(order) over HTTP, then updates the order status and returns.

The transaction is open for the whole HTTP call, which may take seconds under load, and the connection sits idle in transaction holding the order row lock.

The corrected shape splits it into three: a transactional method that saves the order with status pending and returns; a non-transactional step that calls the payment service; and a second transactional method that records the result.

If the payment call fails or the process dies, the order is pending and a reconciliation job resolves it. If the call must be reliable, the outbox pattern replaces the direct call with an event written in the first transaction.

"How does the same problem look in MySQL and how do you find the offenders there?"

In SHOW PROCESSLIST the session shows Command = Sleep, which looks harmless, so the trick is to join information_schema.innodb_trx, which lists open transactions with trx_started and trx_mysql_thread_id, against the processlist to find sleeping threads with old transactions.

A query like SELECT t.trx_started, p.id, p.user, p.host, p.time FROM information_schema.innodb_trx t JOIN information_schema.processlist p ON p.id = t.trx_mysql_thread_id WHERE p.command = 'Sleep' ORDER BY t.trx_started shows exactly the idle-in-transaction sessions.

The damage is the same: row locks held and purge blocked, visible as history list length.

MySQL has no per-transaction idle timeout, so the guardrail is a lower wait_timeout for application users plus an alert on innodb_trx age, and pt-kill can terminate sleeping sessions with old transactions automatically.

"Why is this incident worse under a connection pooler in transaction mode?"

With pgBouncer in transaction pooling mode, a server connection is assigned to a client for the duration of a transaction.

An idle-in-transaction client keeps that server connection reserved the whole time, so hundreds of stuck transactions consume hundreds of the small pool of real server connections, and every other client queues for a connection even though the database is idle.

The symptom is pgBouncer's cl_waiting count rising and application pool timeouts while pg_stat_activity shows nothing busy. So the pooler turns a lock problem into a capacity problem too.

pgBouncer has its own idle_transaction_timeout setting that closes the client connection and returns the server connection, which is the right guard at the pooler layer in addition to the server-side timeout.

Q154 · Scenario. "One analytics query is saturating the disks and everything else is crawling. Talk me through finding it and killing it — safely."

Reveal answer

The real test Whether you know there are two ways to kill, in which order to use them, and what killing actually costs.

Strong answer My sequence:

  1. Find it: in pg_stat_activity I sort by query_start and look for the long-running active statement — usually a giant join or aggregation from a reporting user. In MySQL, SHOW FULL PROCESSLIST and the Time column. I note the pid, the user, and the exact SQL for the postmortem.
  2. Cancel before terminate. In Postgres, pg_cancel_backend(pid) cancels just the running statement and leaves the connection alive — that is the polite kill. Only if the session ignores it do I use pg_terminate_backend(pid), which drops the whole connection. MySQL has the same pair: KILL QUERY 4211 stops the statement; KILL 4211 kills the connection.
  3. Think before killing a writer. Killing rolls the transaction back, and rollback is not free: if a transaction has modified fifty million rows, InnoDB must undo all fifty million changes, largely single-threaded, and the rollback can take longer than letting the statement finish — while still holding its locks. For a huge write that is nearly done, letting it complete is sometimes the faster mitigation. A read-only analytics query has nothing to undo, so it is always safe to kill.
  4. Prevent the repeat: move analytics to a read replica, and give the reporting user its own login with a statement timeout so this class of query can never run unbounded on the primary again.

Land it Cancel the statement before you terminate the connection, and never kill a huge write without pricing the rollback first.

Likely follow-ups
"pg_cancel_backend returned true but the query is still running a minute later. Why, and what next?"

Cancel only sends a signal; the backend acts on it at its next interrupt check, and some operations do not check for a while, for example a long call into an extension, a blocking system call, or a large sort step.

So the return value means the signal was delivered, not that the query stopped.

I check the wait_event: if it is a DataFileRead loop the cancel should be honored soon; if it is stuck in something uninterruptible, I use pg_terminate_backend, which sends a stronger signal and closes the connection.

If even that does not work within seconds, the process is stuck in the kernel on I/O, and the only options are waiting or, as a last resort, a database restart, which I would rather avoid.

On MySQL, KILL QUERY has the same caveat, since the thread checks the kill flag between operations.

"How do you estimate how long a rollback will take before deciding whether to kill a big writer?"

In MySQL, SHOW ENGINE INNODB STATUS lists the transaction with its undo log entries count, and information_schema.innodb_trx shows trx_rows_modified.

Rollback speed is roughly comparable to the original write speed or slower, so a transaction that modified fifty million rows over an hour will take about an hour to roll back, and during that time its locks are held and the rollback is single-threaded.

If it is 90 percent done, letting it finish is faster. In Postgres, rollback is nearly instant because MVCC just leaves the new versions dead for vacuum, so killing a writer is cheap; the cost moves to vacuum afterwards.

That difference is a real reason the answer differs by engine, and I state it rather than giving one rule.

"The query is from a scheduled report that will run again tomorrow at the same time. What do you change tonight?"

Tonight I make sure tomorrow is a non-event even before the proper fix. I set a statement_timeout on the reporting role of, say, ten minutes, so the query dies on its own.

I repoint the report's connection string at the read replica, which usually needs only a config change.

I look at the query's EXPLAIN to see if a missing index or a rewritten filter turns forty minutes into forty seconds; often it is a function wrapped around an indexed column.

And I message the report's owner, because they need to know it will fail if it is still slow.

The lasting fix, a warehouse or a dedicated reporting replica, is a ticket for the morning, but the four steps above take an hour and remove the risk.

Q155 · Scenario. "Connection count is spiking toward max_connections and new clients are being refused. Triage it."

Reveal answer

The real test Whether you diagnose who is connecting before touching the limit, and whether you know the real fix is a pooler, not a bigger number.

Strong answer Raising max_connections is the trap answer — in Postgres every connection is a full operating-system process with real memory cost, so raising the cap usually converts a refusal problem into an out-of-memory problem. My order:

  1. Get in first: Postgres reserves slots via superuser_reserved_connections, and MySQL 8 has a separate admin port, so an operator can still connect when the app cannot.
  2. Identify who: group sessions by user, application_name, and client address. Three usual suspects: a reconnect storm — after a brief blip, every client retries at once with no backoff; a newly deployed service whose pool has no maximum; or serverless functions (a Lambda swarm) where every concurrent invocation opens its own connection.
  3. Breathe: kill idle sessions from the offending source (pg_terminate_backend on idle ones) to free slots while the real fix goes in.
  4. Fix the source: cap the offender's pool, add jittered exponential backoff to reconnect logic, and give each database user a per-role cap (ALTER ROLE svc_reports CONNECTION LIMIT 20) so one service can never starve the rest.
  5. Fix it structurally: put pgBouncer (or ProxySQL for MySQL) in front — a lightweight proxy that lets thousands of application connections share a few dozen real database connections. That is the durable answer for serverless clients especially.

Land it Connection spikes are an identification problem first and a pooling problem second — the one thing they are not is a reason to raise max_connections under pressure.

Likely follow-ups
"Why is a Postgres connection expensive, and how does that compare with MySQL?"

Each Postgres connection is a forked operating system process with its own memory for query plans, catalog caches, and work areas, typically five to ten megabytes idle and much more once work_mem is used, and the kernel scheduling cost grows with process count.

Lock management structures are also sized per connection. So a thousand connections is several gigabytes of memory before any query runs.

MySQL uses a thread per connection, which is lighter, around a few hundred kilobytes idle plus per-thread buffers, so MySQL tolerates thousands of connections more gracefully, though it still suffers from contention when thousands are active at once.

This is why pgBouncer is almost mandatory for Postgres at scale and ProxySQL is more of an optimization for MySQL.

"How do you size the connection pool correctly instead of guessing?"

Start from the database's capacity, not the application's wishes. A database can usefully run a number of active queries close to its core count plus the number of disks it can wait on at once; a common rule is cores times two to four.

That number is the total budget across all application instances, so with 32 cores and 20 application instances, each instance gets around three to five connections. It sounds tiny, but a pool of five on a service doing five-millisecond queries handles a thousand queries a second.

Then I measure: HikariCP's pending-threads and wait-time metrics show whether the pool is too small, and the database's active session count shows whether it is too large. The pooler in front absorbs the fleet arithmetic when instances multiply.

"What is the reconnect storm mechanism exactly, and what is the fix in the client?"

The database blips for two seconds. Every connection in every pool breaks.

Every pool tries to refill immediately, all at once, so the database receives thousands of connection attempts within a second, each requiring a fork or thread plus authentication, which itself is CPU-heavy with SCRAM. The database's accept queue overflows, connections time out, the pools retry, and the storm sustains itself.

The fix is on the client: exponential backoff with jitter on reconnect, so retries spread over seconds; a pool that grows gradually rather than pre-filling all at once; and a cap on concurrent connection attempts per instance.

HikariCP's initializationFailTimeout and connectionTimeout settings help, and a pooler in front absorbs the storm because reconnecting to pgBouncer is cheap.

"Serverless functions are the source, and you cannot cap their concurrency. What do you build?"

A pooler that the functions connect to instead of the database, with the pooler holding a fixed set of real connections. For Postgres that is pgBouncer or a managed equivalent such as RDS Proxy or Supabase's pooler; for MySQL, ProxySQL or RDS Proxy.

The functions open cheap connections to the pooler, which queues them when the real pool is busy, so the database sees a steady number regardless of how many functions are running.

I set the pooler's client-side limit high and its server-side pool to the database's capacity, and I make function timeouts shorter than the pooler queue wait so a backed-up queue fails fast.

The functions also need to close connections at the end of each invocation rather than caching them across frozen instances.

Q156 · Scenario. "Dozens of sessions are stuck in lock waits and the queue keeps growing. How do you find the session at the head of the chain, and what do you do with it?"

Reveal answer

The real test Whether you kill the one blocker instead of flailing at its many victims.

Strong answer Lock waits cascade: one session holds a lock, its waiters take locks of their own, and soon a whole tree of sessions hangs off a single root. Killing victims does nothing — they are reaped and replaced. I go straight for the head of the chain:

find-the-blocker.sql
-- Postgres: who blocks whom. The root blocker appears in
-- others' blocked_by lists but has an empty list itself.
SELECT pid, pg_blocking_pids(pid) AS blocked_by,
       state, now() - xact_start AS xact_age, left(query, 50) AS query
FROM pg_stat_activity
WHERE cardinality(pg_blocking_pids(pid)) > 0
   OR pid IN (SELECT unnest(pg_blocking_pids(pid)) FROM pg_stat_activity);

-- MySQL 8.0: the ready-made view does the walking for you
SELECT blocking_pid, blocking_query, waiting_pid, wait_age
FROM sys.innodb_lock_waits;

The root is typically not even running a query — it is an idle in transaction session whose human or app wandered off mid-transaction, or a schema change waiting for its own lock. Once identified, I capture what it was doing for the postmortem, then cancel or terminate that one session; the entire tree of waiters then proceeds on its own. Afterwards I root-cause why one transaction held a contended lock so long — usually a missing commit, a transaction spanning a remote call, or an unbatched mass update — and add lock_timeout (Postgres) or a lower innodb_lock_wait_timeout (MySQL) so future waiters fail fast instead of piling up.

Land it In a lock pileup you kill exactly one session — the root of the tree — and the rest heals itself.

Likely follow-ups
"You terminated the root blocker and within a minute the queue is back. What is going on?"

Either the application immediately retried the same transaction and left it open again, which means the code path is the root cause and killing sessions is only shaving the symptom, or there was a second independent chain hidden behind the first.

I rerun the blocking query and look at the new root: same application_name and same query text means the code path; a different one means a second chain.

If it is the code path, the mitigation is at the application level: scale that service down, disable the feature flag, or block that user's route at the load balancer until the fix deploys.

I also check whether a schema migration is running in a retry loop, because a migration wrapper that retries an ALTER every second can recreate the queue constantly.

"Explain how a schema change waiting on its lock makes SELECTs queue too."

Postgres grants locks in queue order and does not let a later request jump ahead of an earlier waiting one, to avoid starving the writer.

So when an ALTER TABLE requests ACCESS EXCLUSIVE and waits because a long SELECT holds ACCESS SHARE, every new SELECT that arrives requests ACCESS SHARE, sees an incompatible request ahead of it in the queue, and waits behind the ALTER, even though it would be compatible with the currently running SELECT. One slow reader plus one waiting ALTER therefore freezes the table for everyone.

In pg_stat_activity the ALTER shows wait_event Lock relation and everything behind it shows the same. MySQL's metadata lock queue behaves the same way, with State showing "Waiting for table metadata lock."

"What lock_timeout value do you set and where?"

For migrations, a few seconds, set in the migration session, for example SET lock_timeout = '3s' at the top of each migration, with the tool retrying the statement after a pause when it fails; that turns a potential outage into a quick error.

For the application role, I generally do not set lock_timeout, because normal row lock waits of a second or two are legitimate and failing them creates user-visible errors; instead I rely on statement_timeout for the overall bound.

For interactive DBA sessions, a lock_timeout of a few seconds is a safety net against running a manual DDL that dams traffic. In MySQL, lock_wait_timeout governs metadata locks and defaults to a year, so I set it to a few seconds for migration and admin sessions.

"How do you make lock waits visible before they become an incident?"

Two settings and one metric. log_lock_waits = on in Postgres writes a log line whenever a session waits longer than deadlock_timeout, one second by default, including the blocking PID and both statements, so the log accumulates evidence of contention before anyone notices.

A gauge on the count of sessions where pg_blocking_pids is non-empty, sampled every ten seconds, goes on the dashboard with an alert when it stays above a small number for a minute.

In MySQL, the sys.innodb_lock_waits view supplies the same gauge, and the Innodb_row_lock_time and Innodb_row_lock_waits status counters give trend lines. With those in place a growing lock chain shows up as a climbing line minutes before latency climbs.

Q157 · Scenario. "Database CPU jumped to 100% overnight with no deploy. You discover one query's execution plan changed after statistics were refreshed. Walk me through recognizing, mitigating, and root-causing a plan flip."

Reveal answer

The real test Whether you know plans are computed from statistics, so "nothing changed" is never true — the statistics changed.

Strong answer My sequence:

  1. Recognize it: pg_stat_statements (or MySQL's performance_schema) shows one query whose mean time jumped a thousandfold at a specific moment, with unchanged SQL. In pg_stat_user_tables, last_autoanalyze on the involved table lines up with that moment — autovacuum, the background process that cleans up dead row versions, also refreshes the optimizer's statistics, and the refreshed sample pushed the planner across a decision boundary, say from an index scan to a sequential scan.
  2. Confirm with EXPLAIN ANALYZE: compare the actual row counts with the planner's estimates; a plan flip almost always sits on top of a bad estimate.
  3. Mitigate now: in MySQL I can pin the old plan directly with FORCE INDEX or an optimizer hint. Postgres has no built-in hints, so the quick levers are re-running ANALYZE with a bigger sample, or as a blunt emergency tool disabling the bad plan shape for that role (for example ALTER ROLE app SET enable_seqscan = off) until the real fix lands — and clearly marked as temporary.
  4. Root-cause: usually a skewed column whose default sample of 100 buckets is too coarse. I raise it — ALTER TABLE t ALTER COLUMN status SET STATISTICS 1000 then ANALYZE — or create extended statistics (CREATE STATISTICS) when two correlated columns fool the planner. In MySQL, I build or refresh a histogram with ANALYZE TABLE ... UPDATE HISTOGRAM.

Land it A plan flip is a statistics problem wearing a CPU costume — pin the plan to stop the bleeding, then fix the estimate so the planner chooses well on its own.

Likely follow-ups
"Why did the same statistics refresh produce a different plan? Statistics are supposed to make plans better."

Statistics are a sample, and a plan choice is a threshold decision on top of estimates. Suppose the planner estimates that a filter matches 4 percent of a table; below about 5 percent it chooses an index scan, above that a sequential scan is cheaper.

A new sample that happens to estimate 6 percent flips the plan, and if the true selectivity was 4 percent, the sequential scan is far slower.

The estimate moved because the sample of 30,000 rows was drawn differently, or because the data really changed and a skewed value entered the most-common-values list. So the refresh was not wrong; the estimate was near a boundary and the sample noise pushed it across.

That is why the fix is more precise statistics, so the estimate stops being noisy.

"Postgres has no hints. What are the real options if you must force the old plan right now?"

The pg_hint_plan extension adds hints in comments, such as /*+ IndexScan(orders orders_customer_idx) */, and is widely used on managed Postgres services as of Aug 2026; if it is installed, that is the fastest targeted fix.

Without it, the planner enable_ flags can be set per role or per session, but they affect every query in that scope, so I would set them only for the one function or code path, for example via SET LOCAL inside the transaction that runs the problem query.

Rewriting the query to make the good plan the only option also works: adding a redundant predicate on the index column, or splitting a query into a CTE with MATERIALIZED to fix join order.

None of these are elegant, so they are marked temporary with a ticket.

"How would you have caught this before users did?"

Two mechanisms. Monitoring pg_stat_statements for per-query mean time, alerting when a query's mean time exceeds ten times its trailing week, catches a flip within minutes of the ANALYZE, at 2am rather than when traffic arrives.

And tracking plan changes directly: the auto_explain extension logs plans for slow statements, and tools like pg_stat_plans or, in MySQL, the performance_schema statement digests with their plan hashes show when a query's plan hash changes.

An alert on plan-hash change for the top fifty queries is cheap and precise. In MySQL a query that suddenly reports Handler_read_rnd_next counts in the millions in the slow log is the same signature.

Both would have paged someone with the exact query before CPU hit 100.

"What is extended statistics and when do you actually need it?"

The planner assumes columns are independent, so for WHERE city = 'Mumbai' AND state = 'Maharashtra' it multiplies the two selectivities and underestimates badly, because every Mumbai row is in Maharashtra.

CREATE STATISTICS stats_name (dependencies, ndistinct, mcv) ON city, state FROM addresses tells the planner about that correlation: dependencies captures functional dependency, ndistinct the number of distinct combinations for GROUP BY estimates, and mcv the most common value combinations.

I need it when EXPLAIN ANALYZE shows estimated rows off by a factor of ten or more on a multi-column filter of correlated columns, which is common with geography, dates and status, or tenant and anything. MySQL 8 lacks multi-column statistics but has histograms for single columns.

Q158 · Scenario. "Disk usage on the database server is climbing fast and you have maybe two hours before it is full. What do you check, what is safe to delete, and what must you never touch?"

Reveal answer

The real test Whether you free space through the database's own mechanisms — the engineer who deletes WAL files by hand causes a far worse outage than a full disk.

Strong answer First I find what is growing, because the usual culprit is not data — it is the change journal. The write-ahead log (WAL) in Postgres and the binary log (binlog) in MySQL are append-only journals of every change; they are normally recycled automatically, and when they grow without bound something is pinning them. The two classic pins are a replication slot — Postgres's bookmark that promises to keep WAL until a subscriber has consumed it — left behind by a decommissioned replica or a dead Debezium connector, and a replica that stopped pulling binlogs.

who-is-pinning-the-wal.sql
SELECT slot_name, active,
       pg_size_pretty(pg_wal_lsn_diff(pg_current_wal_lsn(), restart_lsn)) AS retained
FROM pg_replication_slots;
-- slot 'debezium_old' | active = f | retained = 480 GB  -- the culprit

SELECT pg_drop_replication_slot('debezium_old');  -- space frees on next checkpoint

-- MySQL: never rm binlog files; let the server delete them
PURGE BINARY LOGS BEFORE NOW() - INTERVAL 2 DAY;

I also check pg_stat_archiver for a failing archive_command (failed archiving also pins WAL) and look for a very long transaction. Safe to remove: old server text logs and stale local backup staging. Never touch by hand: anything in pg_wal, InnoDB redo files, or binlog files — deleting those corrupts the database or breaks every replica. Afterwards I set max_slot_wal_keep_size and binlog_expire_logs_seconds so an abandoned consumer can never fill the disk again, and alert on slot lag.

Land it A filling disk is almost always a journal someone promised to a consumer that died — release the promise properly and never delete the journal yourself.

Likely follow-ups
"The disk is at 99 percent right now and Postgres is about to stop. What is the emergency move?"

Postgres does not stop cleanly when the disk fills; it PANICs on a failed WAL write, and recovery then also needs space. So the immediate goal is a few gigabytes of headroom in the next minute.

Safe candidates: old server log files in the log directory, any core dumps, stale files in a temporary tablespace after a restart, and any non-database data on the same volume, such as a backup staging directory.

If that is not enough, dropping an inactive replication slot frees WAL on the next checkpoint, and running CHECKPOINT forces recycling sooner. On cloud volumes, growing the volume online is often the fastest fix of all and takes minutes.

I never delete WAL segments or InnoDB files, and I never delete pg_xact or pg_multixact, which look like small junk directories and are essential.

"How does a failing archive_command pin WAL, and how do you see it?"

With archive_mode on, Postgres will not recycle a WAL segment until archive_command has succeeded for it. If the command fails, for example because the S3 credentials expired, Postgres retries forever and keeps every segment since the failure.

pg_stat_archiver shows last_failed_wal, last_failed_time, and failed_count climbing, and the pg_wal directory's archive_status subdirectory fills with .ready files. The fix is to repair the command and let the archiver drain, watching pg_wal shrink.

In an emergency you can set archive_command to a command that returns success, such as /bin/true, to unpin, but that breaks point-in-time recovery until a new base backup is taken, so it is a conscious trade.

MySQL has no equivalent because the binlog does not depend on an archiver.

"What is a safe retention setting for binlogs and WAL, and how do you decide it?"

The retention must cover the longest outage of any consumer that you want to survive without a rebuild.

For binlogs, binlog_expire_logs_seconds defaults to thirty days, which is often more disk than necessary; if replicas and CDC connectors are monitored and a replica outage longer than three days would be rebuilt anyway, three days is enough, provided the backups' own binlog copies exist for point-in-time recovery.

For WAL with slots, max_slot_wal_keep_size is a size, not a time, so I set it to what the disk can afford, for example 100 GB, and accept that a consumer further behind than that must resync.

Then I make the alert fire long before the cap, at perhaps 20 GB of slot lag, so the cap is a last defense rather than a routine event.

Q159. "During an incident, do you root-cause first or mitigate first? Defend your answer."

Reveal answer

Strong answer Mitigate first, always — users are being harmed per minute, and understanding can wait while harm cannot. If killing one query, shedding one client, or failing over restores service, I do it before I fully understand the cause.

The senior refinement is to spend thirty seconds preserving evidence on the way: snapshot pg_stat_activity or the processlist to a file, save the exact query text and its EXPLAIN, note timestamps, copy the relevant log window.

That way mitigation does not destroy the crime scene, and the postmortem can still find the truth. The discipline has a second half: mitigation creates an obligation.

Once service is restored, the root-cause work is scheduled and finished, because an unmitigated cause simply pages you again next week at the same hour.

Land it Stop the bleeding first, but grab the evidence as you do — a mitigation without a follow-up root cause is just a scheduled repeat incident.

Likely follow-ups
"Give me a case where mitigating first would have been the wrong call."

When the mitigation destroys data or the possibility of recovery. If the symptom is that writes are failing and the cause turns out to be a full disk, restarting the database as a reflex mitigation could leave it unable to recover because recovery also needs space.

If a replica is lagging and someone fails over to it as a mitigation for slow reads, the async tail on the old primary is lost.

If a table appears corrupted, running a repair or a REINDEX before capturing the state can erase the evidence needed to determine the extent of the damage.

So the rule has a qualifier: mitigate first when the mitigation is reversible and does not lose data; when it is not, spend the minutes to understand enough to choose safely.

"How do you keep the root-cause work from being dropped once service is restored?"

By making it a tracked artifact with an owner and a date before the incident channel closes.

The incident ends with a postmortem scheduled within two working days, and the postmortem produces action items in the same tracker as feature work, prioritized by the incident's severity, with the on-call lead as the owner until reassigned.

A temporary mitigation such as a disabled plan flag or a killed cron gets a tombstone: a comment in the config with the incident ID and a calendar reminder, so it is either made permanent deliberately or removed.

A monthly review of open postmortem actions is the last defense. Without those mechanics, the second incident report always contains the phrase "this was identified previously."

"What is the fastest reversible mitigation for each of the common causes?"

For one bad query, cancel it and set a statement timeout on its role. For a lock chain, terminate the root. For a connection storm, terminate idle sessions from the offending source and cap its role.

For a plan flip, a session-level planner flag or an index hint. For a runaway migration, pause it, which it must support. For a bad deploy that changed query patterns, roll back the deploy, which is usually faster than any database-side fix.

For a saturated primary from read traffic, shift reads to replicas or shed the lowest-value traffic at the load balancer. For a full disk, free space or grow the volume. Each of these can be undone, so I can apply them in seconds and think afterwards.

Q160 · Scenario. "It is 9am after last night's database incident and leadership wants a timeline. The in-memory stats are gone. How do you reconstruct what happened, and how do you keep it blameless?"

Reveal answer

The real test Whether you set up the recording before the incident, and whether your postmortems fix systems rather than people.

Strong answer I reconstruct from durable sources, cross-referenced by timestamp:

  1. Statement logs: in Postgres, log_min_duration_statement (I keep it at something like 500 milliseconds in production) writes every slow statement with its duration and user; MySQL's slow query log with long_query_time does the same. These give the "what ran, when, how long" backbone.
  2. Lock and error evidence: log_lock_waits in Postgres logs waits over a second; deadlocks and cancellations appear in the server log with both queries involved.
  3. Aggregate deltas: pg_stat_statements survives connections (though not resets), and metric dashboards — CPU, IO, connections, lag — pin the exact onset minute.
  4. Who ran what: audit logging (pgaudit in Postgres, the audit plugin in MySQL) plus per-service database users mean the processlist history attributes actions to services, not to a shared anonymous login.
  5. Change context: deploy history, migration logs, and cron schedules — the incident almost always aligns with one of them.

Then I write the timeline as facts with timestamps, not names with blame: "14:32: a backfill started" rather than "X broke it". The corrective actions target guardrails — the timeout that was missing, the review step that would have caught it — because a system that requires perfect humans is a broken system.

Land it You can only reconstruct what you recorded — turn on statement, lock, and audit logging on a quiet day, because you cannot enable them retroactively.

Likely follow-ups
"What would you configure today so the next incident is reconstructible from durable data?"

On Postgres: log_min_duration_statement at a few hundred milliseconds, log_lock_waits on, log_checkpoints on, log_autovacuum_min_duration at zero or a small value, log_line_prefix including timestamp, PID, user, database, and application_name, and log_connections and log_disconnections so session lifetimes are known.

pg_stat_statements enabled with a job that snapshots its contents to a history table every five minutes, which gives deltas across any window.

On MySQL: the slow query log with long_query_time around half a second and log_slow_extra, performance_schema enabled with events_statements_summary_by_digest snapshotted the same way, and the error log at a verbosity that includes deadlocks via innodb_print_all_deadlocks.

Plus the host metrics shipped to a store with at least a month's retention.

"The incident was caused by a specific engineer running a manual query. How do you write that in the postmortem?"

As a fact about the system, not about the person: "14:32, an ad-hoc UPDATE was executed on the primary from an interactive session with write permissions and no statement timeout.

" The analysis then asks why the system allowed it: why did an interactive session have write rights on production, why was there no review step for manual changes, why did nothing stop a statement that ran for forty minutes.

Each answer becomes an action item on the system. The engineer's name appears nowhere, and in the meeting the facilitator redirects any "who" question back to "what allowed.

" The person who made the mistake is usually the best contributor to the postmortem, because they know exactly what they saw and what would have stopped them.

"How do you build the actual timeline efficiently from all these sources?"

I collect every source into one place ordered by time.

Practically, I export the relevant window from the database log, the slow log, the deploy system, the alerting system, and the chat channel, normalize timestamps to UTC, because the database logs in one zone and the chat in another and that mismatch has confused more postmortems than anything else, and merge them into one sequence.

Then I mark three moments: first cause, first symptom, first human awareness, and mitigation. The gaps between them are the metrics that matter: time to detect and time to mitigate.

Everything else in the postmortem hangs off those gaps, because reducing them is what the action items are for.

Drill · Maintenance, bloat & the knobs that matter

This group tests whether you understand the housekeeping a database needs to stay fast — cleanup, statistics, and memory settings — and whether you know the small set of configuration knobs that actually matter.

Q161. "Explain the difference between VACUUM, autovacuum, and VACUUM FULL in Postgres — what each one does and what each one blocks."

Reveal answer

Strong answer Because of MVCC, an UPDATE or DELETE in Postgres never removes the old row — it leaves a dead tuple, an expired row version waiting for cleanup.

VACUUM is that cleanup: it scans a table, marks the space held by dead tuples as reusable for future writes, and updates visibility bookkeeping.

It runs alongside normal reads and writes and blocks almost nothing — but it does not shrink the file on disk; it only makes room inside it.

Autovacuum is the same operation run automatically by a background daemon whenever a table crosses a change threshold, plus automatic ANALYZE for statistics.

VACUUM FULL is a different beast entirely: it rewrites the whole table into a new compact file and returns the space to the operating system — but it holds an ACCESS EXCLUSIVE lock the entire time, which blocks every read and every write on that table.

Going deeper Two mechanisms make plain VACUUM cheap enough to run constantly.

The visibility map is a bitmap with one bit per table page saying "every row on this page is visible to all transactions"; vacuum skips those pages entirely, so on a table where only the recent pages change, a vacuum reads a small fraction of the file.

The same bit lets index-only scans avoid touching the heap. The second is that vacuum takes only a SHARE UPDATE EXCLUSIVE lock, which conflicts with DDL and other vacuums but not with reads or writes.

Its one blocking moment is at the end when it tries to truncate empty pages off the tail of the file, which needs a brief ACCESS EXCLUSIVE lock; on a busy table that can cause short stalls, and the per-table option vacuum_truncate = off disables it.

Vacuum also does three things beyond space reuse that people forget: it freezes old rows to prevent wraparound, it updates the free space map so inserts know where the holes are, and, as autovacuum, it runs ANALYZE. From Postgres 17 as of Aug 2026, vacuum's memory for dead-tuple tracking uses a compact radix tree, so it no longer needs multiple index passes on large tables the way it did with the old one-gigabyte limit.

Land it Plain VACUUM makes space reusable without blocking anyone; VACUUM FULL gives the space back to the OS at the price of a full outage on that table — so it is an emergency tool, not maintenance.

Likely follow-ups
"Why does Postgres need VACUUM at all when InnoDB manages without one?"

The two engines put old row versions in different places.

InnoDB updates the row in place and writes the previous version to the undo log, a separate structure, and background purge threads discard undo records once no transaction needs them; the table itself never accumulates dead rows.

Postgres writes the new version as a new row in the table and leaves the old one in place, marked with the transaction ID that expired it; nothing removes it until vacuum does.

The Postgres design makes writes and rollbacks simpler and faster, since rollback is just abandoning the new version, and reads of old versions never leave the table. The cost is the separate cleanup pass.

Neither is free; InnoDB's version of vacuum debt is history list length and undo growth.

"Can VACUUM ever return disk space to the operating system?"

Only from the end of the file. After removing dead tuples, vacuum checks whether the last pages of the table are now completely empty, and if so it truncates them, which shrinks the file.

So a table where the dead rows happen to be at the end, such as after deleting the newest rows, does shrink.

A table where deletes are scattered, or where old rows sit at the end because of insert order, does not, because a single live row on the last page prevents truncation.

That is why a table can be 90 percent dead and still full size after vacuum. VACUUM FULL and pg_repack rewrite the table compactly; CLUSTER does the same while ordering rows by an index.

"What does ANALYZE do and how is it related?"

ANALYZE samples a table, by default 300 times default_statistics_target rows, so 30,000 rows, and writes the statistics the planner uses into pg_statistic: number of distinct values, most common values with their frequencies, a histogram of value distribution, null fraction, average width, and the physical correlation between column order and disk order.

It takes a light lock and finishes in seconds even on huge tables because it only samples. It is bundled with autovacuum because both are triggered by change counts, but with a separate threshold, autovacuum_analyze_scale_factor at 10 percent by default.

Vacuum without analyze leaves stale plans; analyze without vacuum leaves bloat. VACUUM ANALYZE runs both, which is what I run manually after a bulk operation.

"What does VACUUM (VERBOSE) output tell you, and which line do you look at?"

It reports, per table, how many pages were scanned and skipped using the visibility map, how many dead row versions were removed, how many could not yet be removed because they are still visible to some open transaction, which is the key line during bloat investigations, how many pages were frozen, index vacuum statistics per index, and the buffer and WAL usage of the run. The "dead but not yet removable" count is what tells me a pin exists, and the oldest xmin it prints tells me what horizon it was constrained by. The autovacuum log lines, enabled with log_autovacuum_min_duration, contain the same information, so I can grep the log for a table's history without running anything.

Q162 · Scenario. "A well-meaning teammate just ran VACUUM FULL on the orders table at noon to 'clean it up'. The site is now timing out. What happened and what do you do?"

Reveal answer

The real test Whether you know it is safe to cancel, and what the online alternative is.

Strong answer What happened: VACUUM FULL took an ACCESS EXCLUSIVE lock on the orders table, so every SELECT, INSERT, and UPDATE against it is queued behind the rewrite — on a big table that can be an hour of effective downtime. My steps:

  1. Confirm in pg_stat_activity: one session running VACUUM FULL, everything else waiting on a lock against that table.
  2. Cancel it with pg_cancel_backend(pid) — and here is the key judgment: this is safe. VACUUM FULL builds the compacted copy in a new file while the original stays intact, so cancelling throws away the half-built copy and loses nothing. The lock releases and the queue drains within seconds.
  3. Ask whether the goal was even valid. Most of the time plain VACUUM plus normal reuse is enough, because new writes will refill the freed space anyway.
  4. If the table genuinely must shrink — say it is 90 percent dead space after a mass delete — schedule pg_repack instead: an extension that rebuilds the table online by copying it while capturing concurrent changes, then swapping with only a brief lock at the end. The MySQL analogue of the whole situation is OPTIMIZE TABLE, which is far less disruptive because InnoDB rebuilds it through online DDL.
  5. Prevent the repeat: restrict who can run maintenance DDL on production, and write down the pg_repack playbook so the helpful instinct has a safe outlet.

Land it Cancel it without fear — VACUUM FULL is all-or-nothing by design — and route the underlying need to pg_repack, which does the same job without stopping the world.

Likely follow-ups
"You cancelled it, but the site is still slow. What else could be going on?"

Three possibilities. The cancel was not honored immediately, since VACUUM FULL checks for interrupts between chunks of work, so I confirm in pg_stat_activity that the session is gone and the lock queue has drained.

The queued sessions all hit the database at once when the lock released, producing a thundering herd of minutes of pent-up work, which resolves in a minute or two on its own.

Or the half-built copy filled the disk: VACUUM FULL needs space for a second copy of the table and its indexes, and if it consumed most of the free space before cancelling, the cleanup of the temporary files must complete, and until then checkpoints and WAL writes may be struggling. Checking df and pg_stat_activity together tells me which one it is.

"How does pg_repack actually work, and what can go wrong with it?"

pg_repack creates a log table and a trigger on the original table that records every insert, update, and delete, then copies the table into a new one, applies the accumulated log changes in batches until it is nearly caught up, then takes a brief exclusive lock, applies the last changes, swaps the files under the original table's name, and drops the old one. Indexes are rebuilt on the new copy. What goes wrong: it needs free disk equal to the table plus indexes; it needs to acquire the exclusive lock at the start and end, so it waits on long transactions the same way DDL does and should be run with a lock timeout and retry; the trigger adds write overhead during the copy; and it must not be interrupted uncleanly or it can leave its trigger and log table behind, which the tool can clean up on the next run.

"Is there a case where VACUUM FULL is actually the right tool?"

Yes, when the table is small enough that the lock lasts seconds, when the table is not in use, or during a planned maintenance window where downtime is already accepted.

It is simpler than pg_repack, requires no extension, and is what I would use on a 500 MB table at 3am, or on a staging system.

It is also the right tool when a table is mostly dead after a one-time purge and the goal is to reclaim disk space quickly with no other traffic around.

The rule is about lock duration relative to what the application tolerates, not about the command being bad. What was wrong at noon was running it on a hot table without knowing it takes an exclusive lock for the whole rewrite.

Q163 · Scenario. "A table holds 20 GB of live data but occupies 200 GB on disk. Diagnose how it got there and how you fix it without downtime."

Reveal answer

The real test Whether you know bloat's two ingredients — churn plus something blocking cleanup — and the online repair path.

Strong answer That ratio is bloat: the file is mostly dead tuples that were never cleaned or whose space was never reused. It takes two ingredients: heavy update or delete churn producing dead versions, and something preventing vacuum from keeping up. My diagnosis:

  1. Measure it: pg_stat_user_tables shows n_dead_tup against n_live_tup and, crucially, last_autovacuum. Millions of dead tuples with a recent autovacuum timestamp means vacuum is running but cannot remove them.
  2. Find the pin. Vacuum can only remove versions older than the oldest thing that might still read them, so I check three pins: a long-running transaction (in pg_stat_activity, order by xact_start), an abandoned replication slot, and — often forgotten — a standby with hot_standby_feedback on running long queries, which exports its old snapshot needs back to the primary.
  3. Release the pin: kill or fix the ancient transaction, drop the dead slot. Now vacuum can actually reclaim, and the growth stops — but the file does not shrink.
  4. Reclaim online: pg_repack rebuilds the table into a compact copy while a trigger captures concurrent writes into a log table, replays them, and swaps the tables under a short exclusive lock. No long outage, unlike VACUUM FULL.
  5. Prevent: make autovacuum more aggressive on this table (next question) and alert on dead-tuple ratio so 10× never happens silently again.

Land it Fix the thing holding cleanup back first — repacking while the pin remains just rebuilds the bloat.

Likely follow-ups
"How do you measure bloat accurately, not just from n_dead_tup?"

n_dead_tup is an estimate maintained by the statistics collector and can be far off.

The accurate tool is the pgstattuple extension: SELECT * FROM pgstattuple('orders') scans the table and returns live and dead tuple counts and bytes, and free space, so the dead percentage is exact; pgstattuple_approx is a cheaper version that uses the visibility map.

For indexes, pgstatindex reports leaf density and fragmentation. The widely used bloat estimation queries from check_postgres compute expected size from column widths and compare with actual size without scanning, which is good enough for a dashboard.

In MySQL, information_schema.tables shows data_free per table, which is reclaimable space inside the file, and a comparison of data_length against a fresh copy gives the rest.

"You released the pin and ran pg_repack, but the table bloated back to 200 GB within a month. Why?"

Because the churn rate, not the pin, is the primary cause, and vacuum is still not keeping up with it.

The table probably receives updates at a rate where, between autovacuum runs, dead tuples accumulate to a large fraction of the live data, and with the default scale factor of 20 percent, autovacuum does not even start until 4 GB of dead rows exist.

Then it runs throttled by cost limits and takes hours, during which more accumulate.

The fix is per-table autovacuum tuning: a scale factor of 1 percent or lower, a higher cost limit so each run finishes fast, and a lower fillfactor so updates stay on the same page as HOT updates and avoid index bloat.

If the workload is a queue-like pattern with extreme churn, partitioning or a redesign that avoids updating the same rows constantly is the real answer.

"How does this look on MySQL, and what is the fix there?"

InnoDB does not accumulate dead rows in the table, but it does accumulate two other forms of waste.

Fragmentation inside the tablespace: deleted rows leave free space within pages that new rows may not fit, so the .ibd file can be several times the live data, visible as data_free in information_schema.tables.

And undo growth from a pinning transaction, which grows the undo tablespaces rather than the table. The fix for fragmentation is OPTIMIZE TABLE, which rebuilds the table through online DDL with only brief locks, or pt-online-schema-change for full control.

The fix for undo is killing the old transaction and, on MySQL 8, letting innodb_undo_log_truncate reclaim the undo tablespaces. The concepts match Postgres; only the locations differ.

"What alert would have caught this at 40 GB instead of 200 GB?"

A daily bloat estimate per table, using the check_postgres-style query or pgstattuple_approx on the top twenty tables by size, with a ticket at 30 percent bloat and a page at 50 percent on any table above ten gigabytes.

Paired with an alert on the age of the oldest transaction, say over one hour, and on inactive replication slots, because those are the pins that make bloat unbounded.

A third useful signal is the ratio of a table's size to its row count trending upward week over week, which needs no extension at all.

Any of those would have opened a ticket at twice the live size, and the fix at that point is a routine pg_repack rather than an emergency.

Q164. "Are the autovacuum defaults good enough for a busy production table? How would you tune them, honestly?"

Reveal answer

Strong answer For hot tables the defaults are too lazy. The trigger is proportional: autovacuum runs when dead tuples exceed autovacuum_vacuum_scale_factor — 20 percent of the table by default — plus a small fixed threshold.

On a 100-million-row table that means waiting for 20 million dead rows before cleanup even begins, which is far too late.

The honest tuning is per-table, not global: ALTER TABLE orders SET (autovacuum_vacuum_scale_factor = 0.01) makes the hot table clean at 1 percent churn while leaving quiet tables alone.

The second lever is speed: autovacuum deliberately throttles itself, so on modern SSD storage I raise autovacuum_vacuum_cost_limit so that when it runs, it finishes. I make the same move for statistics with autovacuum_analyze_scale_factor on tables whose distribution shifts quickly.

Going deeper Two more settings matter on busy systems.

Insert-only tables never generate dead tuples, so the old trigger rule never fired and they were vacuumed only at wraparound time, in one enormous pass; since Postgres 13, autovacuum_vacuum_insert_scale_factor, default 20 percent, triggers vacuum on inserts too, which keeps the visibility map current for index-only scans and spreads freezing out.

On an append-only events table I lower it to a few percent.

The second is concurrency: autovacuum_max_workers, default three, is shared across the whole cluster, and a single huge table can occupy one worker for hours while a hot small table waits; raising workers to five or six on a big server, and remembering that the cost limit is shared across all workers so it should be raised in step, avoids that starvation.

As of Aug 2026, Postgres 18 lets autovacuum_max_workers be changed without a restart, up to the new autovacuum_worker_slots limit.

The way to verify tuning is the log: with log_autovacuum_min_duration = 0, every run reports pages scanned, tuples removed, and duration, and a healthy hot table shows short frequent runs rather than rare long ones.

Land it Tune autovacuum per hot table to run early and fast — a vacuum that starts late and crawls is how bloat becomes an incident.

Likely follow-ups
"Explain the cost-based throttling. What do cost_limit and cost_delay actually do?"

Vacuum counts the work it does in points: reading a page from cache costs 1, reading from disk costs 2 by default, and dirtying a page costs 20.

Whenever the accumulated points reach autovacuum_vacuum_cost_limit, which defaults to the global vacuum_cost_limit of 200, the worker sleeps for autovacuum_vacuum_cost_delay, 2 milliseconds by default.

That caps a worker at roughly 200 points per 2 milliseconds, which on a mixed read and dirty workload is a few megabytes per second, deliberately gentle for spinning disks from fifteen years ago.

On NVMe storage that throttle makes vacuum absurdly slow relative to what the disk can do, so raising the cost limit to 1000 or 2000, or setting the delay to zero for a specific table, lets a run finish in minutes instead of hours.

"How do you know your tuning worked?"

Three numbers on the hot table before and after. n_dead_tup from pg_stat_user_tables, sampled every minute, should now oscillate in a low band rather than climbing to millions between runs.

The autovacuum log lines should show runs every few minutes each lasting seconds to a minute, rather than one run every few hours lasting an hour. And the table's size from pg_total_relation_size should stop growing while row count is flat.

I also watch for the downside: autovacuum I/O competing with the application, visible as I/O wait rising during vacuum runs, which would mean the cost limit went too far. A week of those graphs is the evidence I would put in the change ticket.

"Can you tune autovacuum too aggressively? What breaks?"

Yes.

A scale factor near zero on a large table makes vacuum run almost continuously, which is fine for I/O on fast storage but adds constant write traffic to WAL, because vacuum's changes to pages and the visibility map are logged, and that WAL flows to every replica and archive.

A very high cost limit lets vacuum saturate disk bandwidth and increase latency for user queries. Too many workers with a shared cost limit starve each other.

And vacuum on a hot table holds a SHARE UPDATE EXCLUSIVE lock, which blocks DDL and CREATE INDEX CONCURRENTLY from starting, so migrations may wait behind a vacuum that keeps restarting.

The balance is: frequent enough that dead tuples stay small, throttled enough that the application never notices.

Q165 · Scenario. "Monitoring warns that your Postgres database is approaching transaction-ID wraparound. Explain in plain words what that is, why Postgres will eventually refuse writes over it, and what you do right now."

Reveal answer

The real test Whether you can explain the scariest Postgres failure mode calmly — most candidates have only seen the word.

Strong answer Every row in Postgres is stamped with the transaction ID (XID) of the transaction that wrote it, and XIDs come from a 32-bit counter — about four billion values that wrap around like an odometer.

Row visibility is decided by comparing XIDs, so if the counter wrapped past an old unstamped row, that row would suddenly look like it was written "in the future" and become invisible: silent data loss.

Vacuum prevents this by freezing old rows — marking them as "older than everything, always visible" — so their XID stamp no longer matters. Wraparound danger means freezing has fallen behind: the oldest unfrozen XID is getting close to the counter.

Postgres defends itself in stages — warnings, then forced aggressive vacuums, and finally it stops accepting new write transactions rather than corrupt visibility. My response:

  1. Measure the runway: SELECT datname, age(datfrozenxid) FROM pg_database; — the age is how far behind freezing is; forced autovacuum kicks in at autovacuum_freeze_max_age (200 million by default).
  2. Find why freezing is behind: the same pins as bloat — a long transaction, an abandoned replication slot, a forgotten prepared transaction (pg_prepared_xacts) — and remove them.
  3. Freeze the worst tables now: order tables by age(relfrozenxid) and run VACUUM FREEZE on the oldest ones, largest offenders first.
  4. Afterwards, alert on database age at, say, 500 million — long before the database has to defend itself.

Land it Wraparound is not exotic — it is vacuum debt with a hard deadline, and the fix is removing whatever has been blocking vacuum for weeks.

Likely follow-ups
"Why does the age keep growing even though autovacuum is running constantly on the biggest table?"

Because the age of a database is the age of its oldest unfrozen row across all tables, and vacuum cannot freeze anything newer than the oldest open transaction horizon.

If a transaction, a prepared transaction, or a replication slot with an old xmin is holding the horizon back, every vacuum run on every table finishes and reports the same age.

The other common cause is a single huge table whose aggressive vacuum takes days, so the database's age is stuck at that table's relfrozenxid until the run finishes, and if the run keeps being cancelled by DDL or a restart, it never does.

SELECT relname, age(relfrozenxid) FROM pg_class ORDER BY 2 DESC LIMIT 10 shows which table is the anchor, and pg_stat_progress_vacuum shows whether a freeze is actually progressing on it.

"What happens if we hit the shutdown limit, and how do you recover?"

About three million transactions before wraparound, Postgres refuses new transaction IDs and every write fails with an error telling you to vacuum in single-user mode.

Since Postgres 14 it is possible to run VACUUM in a normal session at that point as long as you avoid consuming XIDs, and Postgres 14 also added the failsafe: when the age passes vacuum_failsafe_age, 1.6 billion by default, vacuum drops its cost throttling and skips index cleanup to freeze as fast as possible.

If the database has truly stopped, the recovery is to stop the application, run VACUUM FREEZE on the oldest tables, with single-user mode as a last resort on old versions, and wait.

On a multi-terabyte database that is many hours of outage, which is why the alert exists.

"How do you tune freezing so aggressive vacuums are not a surprise?"

Three settings. vacuum_freeze_min_age, 50 million by default, is how old a row must be before a normal vacuum freezes it; lowering it means routine vacuums freeze more as they go, so less is left for the aggressive pass.

vacuum_freeze_table_age, 150 million, is when a normal vacuum becomes an aggressive one that scans all unfrozen pages. autovacuum_freeze_max_age, 200 million, is when a forced aggressive vacuum starts even on a quiet table.

On very busy systems consuming a billion transactions a week, I raise autovacuum_freeze_max_age toward one billion so forced runs are rarer, and I schedule explicit VACUUM FREEZE on the largest tables at quiet times so the forced pass never has much to do.

Monitoring age with a page at a quarter of the limit keeps it boring.

"Does MySQL have the same problem?"

No. InnoDB uses 48-bit transaction IDs, so wraparound would take longer than the hardware's lifetime, and it does not stamp rows with visibility information that ages; old versions live in undo and are purged.

Its analogous slow disaster is undo growth from an old transaction, which fills disk rather than stopping writes.

What MySQL does share is the pattern of a limit that is silent for years and then sudden: the 32-bit auto-increment column that reaches 2.1 billion, which the next question group covers.

The lesson generalizes: every engine has a counter with a ceiling, and the job is to know which counter and graph its distance to the wall.

Q166 · Scenario. "On a MySQL box, the undo tablespace keeps growing and SHOW ENGINE INNODB STATUS shows 'History list length: 2,000,000' and climbing. What is going on?"

Reveal answer

The real test Whether you recognize InnoDB's version of the same disease Postgres calls bloat.

Strong answer This is InnoDB's cousin of Postgres bloat.

InnoDB also keeps old row versions for MVCC, but it stores them in the undo log — a separate area holding the information needed to reconstruct past versions — and background purge threads delete undo records once no transaction could still need them.

The history list length is the count of not-yet-purged undo records, so two million and climbing means purge has fallen behind.

The cause is almost always one old transaction: under REPEATABLE READ, a transaction's first read establishes a snapshot, and purge cannot discard any version that snapshot might still need — so a session that opened a transaction yesterday and went idle pins every version created since. My steps:

  1. Find the pin: SELECT trx_id, trx_started, trx_mysql_thread_id FROM information_schema.innodb_trx ORDER BY trx_started LIMIT 5; — the oldest transaction is the culprit, often a forgotten interactive session or a stuck batch job.
  2. Kill it (KILL <thread_id>) after noting what it was; the purge threads then catch up on their own and the history list drains.
  3. Note the disk honesty: in older setups undo lived inside ibdata1, which never shrinks; modern MySQL uses separate undo tablespaces that can be truncated (innodb_undo_log_truncate).
  4. Prevent: alert on history list length and on transaction age, and give interactive users autocommit so an idle terminal cannot pin the database.

Land it A climbing history list means one old snapshot is pinning millions of versions — find the oldest transaction, not a purge tuning knob.

Likely follow-ups
"Besides an old transaction, what else makes purge fall behind?"

Sheer write volume. Purge runs in a limited number of threads, innodb_purge_threads, four by default in MySQL 8, and each undo record requires reading the page it refers to, so a burst of millions of updates and deletes can outrun purge even with no pinning transaction.

In that case history list length rises during the burst and falls afterwards; if it never falls, there is a pin. Slow storage makes it worse.

Also, in MySQL 8 the purge threads back off when the server is busy, controlled by innodb_purge_batch_size and innodb_max_purge_lag, which can be set so that when history grows beyond a threshold, DML is deliberately delayed to let purge catch up.

That last knob is a real trade of throughput for stability that most people do not know exists.

"What does a long history list actually cost a query?"

A read under REPEATABLE READ that touches a row modified since its snapshot must follow the undo chain backwards through every intervening version until it finds one it is allowed to see.

With purge behind, those chains are long, so a single row read can mean dozens of undo page reads, and a range scan over a hot table multiplies that.

Latency rises for reads that touch churned rows even though the data volume has not changed, and the undo pages compete for buffer pool space with real data. Secondary index reads suffer more, because InnoDB must check the clustered record to decide visibility.

The symptom is queries getting slower with no plan change and no growth, and Handler_read counters looking normal, which sends people looking in the wrong place.

"How do you set up the alert and the auto-kill so this never pages you again?"

Two metrics. History list length, from SHOW ENGINE INNODB STATUS or information_schema.innodb_metrics under trx_rseg_history_len, with a ticket above a few hundred thousand and a page above a few million, thresholds set from the normal baseline.

And the age of the oldest transaction from innodb_trx, with a page at, say, thirty minutes for non-batch users.

For automatic remediation, pt-kill with a rule that kills sessions with an open transaction idle longer than a threshold, restricted to interactive and application users, not the batch or replication users. Interactive users get autocommit forced on via their init_connect setting.

The combination catches the forgotten terminal within minutes rather than the next morning.

Q167 · Scenario. "Every morning after the nightly bulk load, the first hour of queries is slow with terrible plans, then it fixes itself. Why, and what is the fix?"

Reveal answer

Strong answer The bulk load — a typical ETL job (extract-transform-load, the nightly pipeline that copies data in) — changed the table dramatically, but the optimizer's statistics still describe last night's table. The planner is choosing plans for a table that no longer exists: wrong row estimates, wrong join orders. It "fixes itself" when auto-analyze eventually notices the churn and refreshes the statistics — that is the mystery hour. The fix is to stop relying on the lagging automatic refresh:

  1. Make ANALYZE (Postgres) or ANALYZE TABLE (MySQL) an explicit final step of the load pipeline, so statistics are current before the first morning query arrives. It takes seconds because it only samples.
  2. In MySQL, know the automatic behavior: with persistent statistics, InnoDB recalculates when roughly 10 percent of rows change — a load that appends 8 percent daily can stay stale for days, so the explicit step matters even more.
  3. For columns with skewed distributions — one merchant owning half the rows — the default sample is too coarse regardless of freshness: raise it with ALTER TABLE t ALTER COLUMN merchant_id SET STATISTICS 1000 in Postgres, or build a histogram with ANALYZE TABLE t UPDATE HISTOGRAM ON merchant_id in MySQL.

Land it After any bulk change, statistics refresh belongs to the pipeline, not to chance — ANALYZE is cheap and the bad plans it prevents are not.

Likely follow-ups
"The load also truncates and reloads a table. What extra problem does that cause for statistics?"

TRUNCATE resets the table, and in Postgres it also clears the table's statistics counters and leaves pg_statistic describing the old data until the next ANALYZE, so for the first hour the planner believes the table has yesterday's distribution while the row count estimate from the relation size may be tiny at the start of the load.

Queries planned during the load may pick nested loops expecting a small table and then hit millions of rows.

In MySQL, TRUNCATE followed by a bulk load resets persistent statistics and InnoDB recalculates after the load crosses its change threshold, but plans cached during the load can be wrong.

The fix is the same: ANALYZE as the last step, and if queries run during the load, load into a new table and swap names so the live table is never half-loaded.

"How would you verify the statistics are the cause and not something else, like cold cache after the load?"

Take one of the slow morning queries and run EXPLAIN ANALYZE at 8am before auto-analyze has run; compare estimated rows with actual rows on the scan nodes.

If estimates are off by ten times or more and the plan is a bad join order or a sequential scan where an index scan is obvious, it is statistics.

Then run ANALYZE on the table and EXPLAIN ANALYZE again; if the plan changes and the time drops, the cause is confirmed.

Cold cache looks different: the plan is the same as later in the day but buffer statistics show reads instead of hits, and it warms up within minutes, not an hour.

The two can coexist after a big load, so I check both and fix both with an ANALYZE plus a pg_prewarm of the loaded table.

"Does ANALYZE on a 500-million-row table really take seconds? What does it lock?"

It takes seconds to a few minutes, because it reads a random sample of pages rather than the whole table: with default_statistics_target at 100 it samples 30,000 rows, which means reading roughly 30,000 pages scattered across the file, so on a large table it is bounded by random I/O rather than size.

Raising the target to 1000 for a column raises the sample to 300,000 rows and the time proportionally. It takes a SHARE UPDATE EXCLUSIVE lock, which conflicts only with DDL and vacuum, so reads and writes continue normally.

In MySQL, ANALYZE TABLE samples innodb_stats_persistent_sample_pages pages, 20 by default, and is nearly instant, though it briefly needs a metadata lock and flushes the table from the table cache, which can stall queries momentarily on a very hot table.

Q168. "Do indexes need periodic rebuilding? Give me the honest answer, not the ritual."

Reveal answer

Strong answer Mostly no — scheduled index rebuilds are usually cargo cult. B-tree indexes self-balance, and both engines reuse freed index space. The honest exceptions: an index can genuinely bloat after mass deletes or on a heavy-churn column, and certain append-then-delete patterns leave sparse pages.

So I rebuild on evidence, not on a calendar: I measure index size against a freshly built copy or use bloat-estimation queries, and act when an index is, say, three times its ideal size and hot.

The mechanism matters: REINDEX CONCURRENTLY (Postgres 12 and later) rebuilds without blocking writes; a plain REINDEX locks writers and belongs to maintenance windows.

In MySQL, OPTIMIZE TABLE rebuilds the table and its indexes via online DDL. Also worth knowing: Postgres 13 added B-tree deduplication, which shrank many bloated-index problems away on upgrade.

Land it Rebuild indexes when measurement says they are bloated and hot — never as a weekend ritual, and always with the concurrent variant.

Likely follow-ups
"Show me how you measure whether a specific index is bloated."

With the pgstattuple extension, SELECT * FROM pgstatindex('orders_customer_idx') returns avg_leaf_density and leaf_fragmentation. A healthy B-tree built by CREATE INDEX has leaf density around 90 percent; one that has degraded to 40 or 50 percent is holding twice the pages it needs.

I also compare pg_relation_size of the index against the size of a freshly built copy on a replica or staging database. For a cheaper estimate without scanning, the bloat estimation queries compute expected size from tuple width and row count.

In MySQL, information_schema.innodb_indexes and the INNODB_BUFFER_PAGE view give page counts, and comparing index_length before and after OPTIMIZE TABLE on a replica gives the honest answer.

"What does REINDEX CONCURRENTLY actually do and what can go wrong?"

It builds a new index alongside the old one in two scans, allowing writes throughout, then swaps the names and drops the old one, taking only brief locks at the transitions.

It needs disk space for both copies during the build, and it needs the lock briefly at start and end, so long transactions can block it exactly as DDL is blocked, and it should run with a lock timeout and retry.

If it fails or is cancelled midway, it leaves an invalid index with a _ccnew suffix that must be dropped manually, and queries will not use it but writes will maintain it until then.

It cannot run inside a transaction block, and it cannot be used on system catalog indexes. Since Postgres 14 it also handles partitioned indexes, reindexing every partition's index in turn.

"What index patterns cause bloat that vacuum cannot fix?"

The classic is a monotonically increasing key with deletion from the left: a queue table indexed by created_at, where old rows are deleted.

The pages at the left edge empty out, and empty pages get recycled, but pages that keep even one live entry stay allocated with mostly free space, and new inserts never land there because they go to the right edge.

So the index grows steadily even though the table stays constant size. Timestamp-based partial indexes and status columns with high churn show the same pattern.

Postgres 14 added bottom-up index deletion, which removes dead entries during inserts and dramatically reduced bloat from non-HOT updates, but the left-delete pattern still needs a periodic REINDEX CONCURRENTLY or a design change such as partitioning.

Q169. "You get a fresh Postgres box with default config. Which memory settings do you touch first, and why those?"

Reveal answer

Strong answer Four knobs cover most of the value.

First, shared_buffers — Postgres's own cache of data pages — set to roughly 25 percent of RAM. Not more, because Postgres deliberately relies on the operating system's file cache as a second layer: give Postgres most of the RAM and the same pages get cached twice while the OS cache starves, so returns diminish and can even go negative.

Second, work_mem — the memory one sort or hash operation may use — kept modest globally, say 16 to 64 megabytes, because it multiplies (next question).

Third, maintenance_work_mem — memory for vacuum and index builds — can be generous, say 1 gigabyte, because few of those run at once and they finish much faster with room.

Fourth, effective_cache_size, which allocates nothing at all: it is purely a hint telling the planner how much total caching (Postgres plus OS) likely exists, so it favors index scans appropriately; around 50 to 75 percent of RAM.

Land it The default config assumes a tiny machine — but the 25 percent rule for shared_buffers exists because Postgres shares caching with the OS, and knowing why beats knowing the number.

Likely follow-ups
"What are the other non-memory settings you would change on a fresh box before it takes traffic?"

The checkpoint settings: max_wal_size to a few gigabytes and checkpoint_completion_target at 0.9, so checkpoints are smooth. random_page_cost lowered from 4 to around 1.1 on SSD storage, so the planner stops overpricing index scans. effective_io_concurrency raised to 200 on NVMe so bitmap scans prefetch.

wal_compression on, which trades a little CPU for less WAL volume. The logging block: log_min_duration_statement, log_lock_waits, log_checkpoints, log_autovacuum_min_duration, and a log_line_prefix with time, PID, user, database, and application name. shared_preload_libraries with pg_stat_statements. And the connection cap, max_connections, kept modest with a pooler in front.

Tools like PGTune produce a sensible first draft of all these from RAM and disk type, which I then adjust from measurements.

"Why not set shared_buffers higher than 25 percent on a 512 GB machine? Surely more cache is better."

Two reasons.

First, double caching: a page read from disk goes into the operating system cache and then is copied into shared buffers, so the same page occupies memory twice; with a huge shared_buffers most reads are already hits and the OS cache is wasted, while with a huge OS cache and modest shared_buffers the two cooperate.

Second, checkpoint behavior: every dirty page in shared buffers must be written at checkpoint, so a 300 GB shared_buffers can mean a checkpoint writing hundreds of gigabytes, causing the I/O storms from the sawtooth question.

In practice, values above about 40 percent rarely help, and on large machines the useful move is a large but not majority setting, say 64 to 128 GB, with huge pages enabled so the kernel page tables stay manageable. The working set, not the RAM, sets the right number.

"How do you decide whether the working set fits in memory?"

The working set is the set of pages touched regularly, not the database size. I estimate it from cache statistics: if the hit ratio in pg_stat_database is above 99 percent and pg_statio_user_tables shows the hot tables with almost no heap_blks_read, the working set fits.

If the ratio drops when traffic rises, or I/O wait appears at peak, it does not. The pg_buffercache extension shows exactly which relations occupy shared buffers and how much of each, which gives a direct measure of hot data size.

Then I compare that against shared_buffers plus the OS cache. If hot data is 40 GB on a 64 GB machine, we are near the edge, and the plan is either more RAM or a smaller hot set through archiving and narrower rows.

Q170 · Scenario. "A teammate raised work_mem to 512 MB globally because a report was spilling to disk. Two days later the database was killed by the OOM killer at peak traffic. Explain the failure."

Reveal answer

The real test Whether you know work_mem multiplies — per operation, per query, per connection.

Strong answer The failure is multiplication. work_mem is not a per-server or even per-connection budget — it is the allowance for each individual sort or hash operation, and a single complex query can contain several of them.

The worst-case memory is roughly work_mem × operations per query × concurrent queries. At 512 megabytes with 200 active connections each running a query with three or four sort or hash nodes, the theoretical demand runs into the hundreds of gigabytes.

It held for two days because nothing hit the bad combination; at peak, enough heavy queries coincided, RAM ran out, and the OOM (out-of-memory) killer — the Linux mechanism that kills processes when memory is exhausted — shot a Postgres process, forcing a crash recovery. The correct pattern:

  1. Keep the global value modest — 16 to 64 megabytes.
  2. Raise it only for the session that needs it: the reporting job runs SET work_mem = '512MB' for its own connection, or the reporting role gets ALTER ROLE reporter SET work_mem = '512MB'.
  3. Diagnose spills properly first: EXPLAIN (ANALYZE, BUFFERS) shows "Sort Method: external merge Disk" — sometimes the real fix is an index that removes the sort entirely.

MySQL has the same trap with sort_buffer_size and join_buffer_size: per-operation allowances that people mistake for global budgets.

Land it work_mem is a per-operation allowance that concurrency multiplies — raise it for the one session that needs it, never for the fleet.

Likely follow-ups
"How do you find the right work_mem for the reporting query specifically?"

Run EXPLAIN (ANALYZE, BUFFERS) on it. Each Sort node reports Sort Method: either quicksort with Memory: N kB, or external merge with Disk: N kB; each Hash node reports Batches: N, where more than one batch means it spilled.

The disk figure tells me how much memory the operation needed, and the number of sort and hash nodes tells me how many times work_mem may be allocated in that query.

So a query with one sort spilling 300 MB needs work_mem of roughly 400 MB for that session and nothing more. I set it with SET LOCAL work_mem = '400MB' at the start of that transaction so it applies only there.

If several operations each need hundreds of megabytes, the query needs a rewrite or an index, not a bigger allowance.

"What does the OOM killer do to Postgres exactly, and how do you make that failure less catastrophic?"

Linux kills the process using the most memory, which under Postgres is often the postmaster's child with the biggest sort, or sometimes the postmaster itself.

When any backend dies abnormally, the postmaster assumes shared memory may be corrupted and terminates every other backend, then runs crash recovery from the last checkpoint, so one killed process becomes a full restart, dropping every connection and requiring a cold cache warm-up.

To soften it, set vm.overcommit_memory = 2 so the kernel refuses allocations instead of overcommitting and then killing, which turns the failure into a clean out-of-memory error for the one greedy query, and set the postmaster's oom_score_adj so the postmaster is never the chosen victim. And keep swap small but present to absorb short spikes.

"What is hash_mem_multiplier and does it change the arithmetic?"

Since Postgres 13, hash-based operations, such as hash joins and hash aggregates, are allowed work_mem times hash_mem_multiplier, which defaults to 2.0 since Postgres 15.

So with work_mem at 64 MB, a hash join may use 128 MB before spilling, while a sort is still capped at 64 MB. This exists because hash tables spill more expensively than sorts, so giving them more headroom is a good trade.

For the worst-case arithmetic it means the per-operation number is up to double for hash nodes, so a query with three hash joins at 512 MB work_mem could take 3 GB.

It is one more reason the global value must stay modest and the big allowances be scoped to the sessions that need them.

Q171. "Same question for MySQL: which settings matter first on a dedicated InnoDB server?"

Reveal answer

Strong answer Two settings dominate. First, innodb_buffer_pool_size — InnoDB's cache of data and index pages — at roughly 70 percent of RAM on a dedicated box.

The guidance differs from Postgres's 25 percent for a principled reason: InnoDB does its own caching and bypasses much of the OS file cache, so there is no second layer to leave room for — the buffer pool is the cache, and if the working set fits in it, most reads never touch disk.

Second, the redo log capacity — innodb_redo_log_capacity in modern MySQL, formerly sized via innodb_log_file_size.

The redo log absorbs write bursts before pages are flushed to their real locations; if it is too small, InnoDB must flush aggressively to reclaim log space, and you see periodic write stalls under load.

Sizing it to hold an hour or so of peak redo generation smooths writes dramatically. After those two, everything else — flush method, IO capacity hints — is fine-tuning.

Land it Buffer pool size decides your reads and redo capacity decides your write smoothness — get those two right before touching anything else.

Likely follow-ups
"What does innodb_flush_log_at_trx_commit do, and would you ever change it from 1?"

It controls when the redo log is flushed to disk relative to commit.

At 1, the default, every commit writes and fsyncs the redo log, so a committed transaction survives a power loss; that is the D in ACID. At 2, the log is written to the operating system at commit but fsynced once a second, so a MySQL crash loses nothing but an OS crash or power loss loses up to a second.

At 0, both write and fsync happen once a second, so even a MySQL crash loses up to a second.

I would set 2 only on a replica or a system where a second of loss is explicitly acceptable, such as a metrics store, and never on a primary holding financial data.

sync_binlog = 1 is the matching setting for the binlog and must stay at 1 for crash-safe replication.

"How do you size the redo log capacity from measurements, not folklore?"

I measure how much redo the server generates at peak. SHOW GLOBAL STATUS LIKE 'Innodb_os_log_written' gives bytes written to the redo log; sampling it a minute apart at peak gives bytes per minute.

If peak is 200 MB per minute, an hour of redo is 12 GB, so innodb_redo_log_capacity of 8 to 16 GB gives the checkpointing machinery room to smooth flushes.

The signal that it is too small is the Innodb_log_waits counter climbing, or checkpoint age approaching the capacity in SHOW ENGINE INNODB STATUS, both of which mean InnoDB is stalling writes to flush.

The cost of a larger log is longer crash recovery, roughly proportional to how much redo must be replayed, which on modern hardware is minutes for tens of gigabytes.

"What about the other commonly cited settings: innodb_io_capacity, innodb_flush_method, thread settings?"

innodb_io_capacity tells the background flushing how many I/O operations per second it may use, default 200, which is a spinning-disk number; on SSD I set it to a few thousand and innodb_io_capacity_max to two or three times that so dirty pages are flushed steadily rather than in bursts.

innodb_flush_method = O_DIRECT on Linux bypasses the OS cache for data files, avoiding double caching, and is the standard choice with a large buffer pool. innodb_buffer_pool_instances splits the pool into several to reduce mutex contention, and MySQL sets it automatically for pools over one gigabyte.

Thread concurrency settings I leave at defaults unless a benchmark shows contention. Everything here is second-order compared with the buffer pool and redo log.

"What does the buffer pool look like on a replica that only serves reads? Same sizing?"

Same rule, because the replica has to apply every write from the primary and also serve its reads, so it needs the working set in memory just as much.

A replica with a smaller buffer pool than the primary applies writes slower, because each row change must read the page from disk before modifying it, and that is one of the most common causes of unexplained replication lag.

Reporting replicas that scan cold data may need even more memory or, more realistically, tolerate a lower hit rate.

The other replica-specific setting is innodb_flush_log_at_trx_commit = 2, which is defensible there because a replica that loses a second of applied changes can simply re-apply from the primary's binlog.

Q172. "How do you read the cache hit ratio, and what are its limits as a health metric?"

Reveal answer

Strong answer The hit ratio is the share of page reads served from memory instead of disk. In Postgres: blks_hit / (blks_hit + blks_read) from pg_stat_database; in MySQL: compare Innodb_buffer_pool_read_requests with Innodb_buffer_pool_reads (the latter are the misses that went to disk).

Healthy transactional systems sit above 99 percent. The limits matter as much as the number. In Postgres a "miss" often lands in the OS file cache anyway, so blks_read overstates real disk IO — the ratio is optimistic about pain and pessimistic about cause.

Second, it is an average: a 99 percent overall ratio can hide one critical table thrashing at 60 percent, which is why per-table views like pg_statio_user_tables exist.

Third, it is a lagging trend metric, not an alert: the useful signal is a ratio that has been drifting down for weeks, telling you the working set is outgrowing memory before latency shows it.

Land it Watch the hit ratio as a trend for capacity planning, not as a truth about disk pain — its slow decline is the early warning that your working set no longer fits.

Likely follow-ups
"If hit ratio is unreliable, what do you look at instead to know whether reads are hitting disk?"

The operating system's view and the wait events. On Linux, iostat shows read operations per second and await, the average I/O latency, on the database volume, which is the truth about whether disk reads are happening and how slow they are.

In Postgres, pg_stat_activity wait events of type IO, specifically DataFileRead, sampled frequently, show what fraction of active time is spent waiting on the disk. The pg_stat_io view since Postgres 16 breaks I/O down by backend type and context.

In MySQL, Innodb_data_reads and Innodb_data_pending_reads show real disk reads, and performance_schema's file I/O summaries show latency per file. Those numbers answer "are we disk bound" directly, where the ratio only hints.

"The ratio is 99.5 percent but latency is bad. What are the possible explanations?"

Several. The half percent of misses may be concentrated on the hot path, so every checkout query misses once and pays a disk read while thousands of cheap queries inflate the hit count.

The misses may be very slow, for example on a network volume with ten-millisecond latency, so a small miss rate still dominates.

The bottleneck may not be reads at all: write latency from checkpoints, lock waits, CPU saturation from a bad plan, or connection queueing all leave the hit ratio perfect.

Or the slow queries scan millions of cached pages, which hit in memory but still take seconds of CPU. So a high ratio rules out one cause, disk-bound reads across the board, and nothing else; the next step is the wait events and the top queries.

"Postgres's blks_read may be an OS cache hit. How do you find out how much the OS cache is helping?"

The direct tool is pg_stat_kcache, an extension that records real system-level read and write bytes per statement alongside pg_stat_statements, so I can compare Postgres-level reads against physical reads per query.

Without an extension, the comparison between blks_read growth in pg_stat_database and the read operations reported by iostat over the same interval gives the ratio: if Postgres reports ten thousand block reads per second and the disk shows five hundred, the OS cache is serving 95 percent of misses.

The fincore utility or the pgfincore extension can also report which portion of a table's file is resident in the OS cache. That analysis decides whether more RAM helps or whether the working set already fits in the two caches combined.

Q173 · Scenario. "You restarted the database for a patch. It comes back healthy, but for the next thirty minutes everything is slow and users complain. What happened and how do you handle it next time?"

Reveal answer

Strong answer This is a cold cache. Before the restart, the hot working set lived in memory — the buffer pool or shared buffers plus the OS file cache — and virtually every read was a memory read. The restart emptied that memory, so the same queries now hit disk for pages they used to find instantly, and stay slow until the cache re-learns the working set from traffic. That is the thirty minutes. Handling it like a senior:

  1. MySQL largely solves it for you: innodb_buffer_pool_dump_at_shutdown and innodb_buffer_pool_load_at_startup (both on by default in modern versions) save the identities of the hottest pages at shutdown and reload those pages after startup — verify they are enabled rather than assuming.
  2. Postgres needs the explicit tool: the pg_prewarm extension loads chosen tables and indexes into cache — SELECT pg_prewarm('orders'); for the known-hot objects right after startup — and its background worker mode can autosave and restore the buffer state across restarts.
  3. Operationally: plan restarts and failovers for troughs, warm the standby before promoting it where possible, and ramp traffic gradually rather than slamming a cold instance with peak load.
  4. Set expectations: post-restart latency elevation is physics, so the maintenance notice should say so instead of letting it look like a botched patch.

Land it A restart erases the cache's memory of your working set — warming it back deliberately is part of the restart, not an afterthought.

Likely follow-ups
"How does pg_prewarm's autoprewarm mode work, and what does it cost?"

With pg_prewarm in shared_preload_libraries, a background worker periodically, every 300 seconds by default per pg_prewarm.autoprewarm_interval, writes a list of which blocks of which relations are currently in shared buffers to a file called autoprewarm.blocks in the data directory.

At the next startup, the worker reads that list and loads those blocks back into shared buffers in the background while the server is already accepting connections.

The cost is one small file write every five minutes and the read I/O at startup, which happens anyway when traffic arrives, just earlier and sequentially. It only restores shared buffers, not the OS cache, so on a server with modest shared_buffers the benefit is partial. It is the right default on any production Postgres.

"You are about to fail over to a standby that has been idle. How do you warm it first?"

A hot standby that has been replaying WAL already has the recently modified pages in memory, but not the read-only hot set.

Before a planned switchover, I send it real read traffic for a while: route a share of replica reads to it for ten or twenty minutes, or run a script that executes the top read queries from pg_stat_statements against it.

pg_prewarm can load specific hot tables and indexes explicitly on the standby, since it works in recovery mode too.

For MySQL, I can copy the primary's buffer pool dump file, ib_buffer_pool, to the replica and trigger a load with SET GLOBAL innodb_buffer_pool_load_now = ON, which loads the same page identities. Then I switch over in a traffic trough and watch p99 rather than assuming.

"Besides the cache, what else is cold after a restart?"

Several smaller things add up. Plan and statement caches in the application and in the JDBC driver are gone, so every statement is re-parsed and re-planned for its first few executions. Connection pools must reconnect, and the first requests pay authentication and handshake time.

In Postgres, each backend's catalog caches start empty, so the first queries on each connection read system tables. In MySQL, the adaptive hash index is rebuilt from scratch as the workload runs, and the table cache and open-file handles refill.

On the OS, the page cache is empty, which matters far more for Postgres than InnoDB with O_DIRECT. And JIT-compiled code in the application is gone if the application was restarted too. Each is small; together they explain the first few minutes.

Q174 · Scenario. "Your IO graphs show a sawtooth: every few minutes write latency spikes hard, then calms. Nothing in the application changes. What is the signature and what do you tune?"

Reveal answer

Strong answer That sawtooth is the checkpoint signature. A checkpoint is the moment the database forces all modified pages held in memory down to disk, so that the write-ahead log before that point can be recycled and crash recovery stays short. If checkpoints are too frequent or too abrupt, each one dumps a burst of writes — and an fsync storm — onto the disks, and every ordinary query pays the latency toll during the burst. Diagnosis and tuning in Postgres:

  1. Confirm: enable log_checkpoints and read the frequency and duration; the log literally warns "checkpoints are occurring too frequently" when WAL growth is forcing them early.
  2. Space them out: raise max_wal_size so checkpoints are triggered by the timer, not by running out of WAL space mid-burst — this trades a longer crash recovery for smooth steady-state IO.
  3. Spread each one: checkpoint_completion_target = 0.9 tells Postgres to pace the flushing across 90 percent of the interval instead of sprinting, turning the spike into a gentle slope.

MySQL has the same disease with different names: an undersized redo log forces aggressive flushing to reclaim log space, and the cure is a larger innodb_redo_log_capacity plus adaptive flushing doing the pacing. In both engines the principle is identical — give the engine enough journal runway that it can smooth writes instead of panicking periodically.

Land it Periodic latency spikes with no app change are almost always checkpoint pressure — the trade you are tuning is smooth IO now against recovery time after a crash.

Likely follow-ups
"What is the actual cost of raising max_wal_size? Be concrete about crash recovery."

Crash recovery replays WAL from the last completed checkpoint to the end of the log, so the amount to replay is at most roughly the checkpoint spacing. With max_wal_size at 1 GB, recovery replays up to about a gigabyte, which takes seconds.

At 32 GB it may replay tens of gigabytes, which at typical replay rates of a few hundred megabytes per second is a minute or two.

The same applies to a standby being promoted or a restart after a crash, so the trade is a longer worst-case outage in exchange for smooth steady-state I/O. Disk space is the other cost: pg_wal can hold up to max_wal_size plus some overshoot.

On a system where recovery time matters, I keep checkpoint_timeout at 10 to 15 minutes and size max_wal_size so timer-based checkpoints dominate.

"What else causes a periodic I/O spike besides checkpoints?"

Autovacuum runs on a large table, visible in the log with timestamps that line up with the spikes. A cron job or scheduled report at a fixed interval. WAL archiving that copies segments in bursts, or a backup tool taking incremental snapshots.

Log rotation with compression of a large file. On MySQL, the buffer pool dump if it were set to a short interval, or the binlog rotating and flushing.

The way to tell them apart is correlation: log_checkpoints shows the checkpoint start and end times; if the spikes align with them, it is checkpoints, and if they align with cron minute marks or vacuum log lines, it is those. iotop or pidstat during a spike identifies the process directly.

"How do you smooth the fsync storm at the operating system level?"

The storm comes from the kernel accumulating dirty pages from the checkpoint's writes and then flushing them all when fsync is called.

Postgres's checkpoint_flush_after, default 256 kB on Linux, tells the kernel to start writing back after that many bytes so dirty data does not pile up, and bgwriter_flush_after does the same for the background writer.

The kernel's vm.dirty_background_bytes and vm.dirty_bytes can be set to modest values, say 64 MB and 1 GB, so writeback is continuous instead of a wall of writes when the ratio thresholds are hit, which on a machine with 512 GB of RAM would otherwise let tens of gigabytes accumulate.

Modern MySQL does its own pacing with O_DIRECT, so the kernel knobs matter less there.

"How would you confirm the fix actually worked?"

Three graphs before and after. Write latency from iostat's w_await should lose its sawtooth and settle into a flat band.

The checkpoint log lines should show checkpoints starting on the timer, with the reason field reading "time" rather than "wal", and each one spread over most of the interval with a write time close to checkpoint_completion_target times checkpoint_timeout.

And the application's p99 latency should lose the periodic bumps. pg_stat_bgwriter, or pg_stat_checkpointer since Postgres 17, gives the counts: checkpoints_timed should dominate checkpoints_req.

If the sawtooth is still there but smaller, the next lever is the kernel dirty settings; if it is unchanged, the spikes were never checkpoints and I go back to correlation.

Q175. "A team wants to solve their slow database by moving to a bigger instance and re-tuning the config. When do you push back, and what is your honest position on exotic tuning like huge pages and NUMA?"

Reveal answer

Strong answer I push back when nobody has looked at the queries yet. Configuration tuning is multiplicative at best — 20 or 30 percent — while a missing index or a rewritten query is often a hundredfold.

So the order is fixed: check pg_stat_statements or the slow log for the top offenders, fix the worst queries and indexes, and only then ask whether the correctly-queried workload still exceeds the hardware.

Buying hardware to run bad queries faster is renting time, not fixing anything — the workload grows back into the bigger box.

On exotic tuning I stay honest: huge pages (larger memory-mapping units that cut page-table overhead) are worth enabling for a large shared_buffers or buffer pool on a dedicated box, and on big multi-socket machines NUMA — non-uniform memory access, where each CPU socket reaches its local memory faster than the other socket's — can cause imbalance worth mitigating with interleaving.

Beyond enabling those and disabling swap-thrash, I do not chase single-digit percents until the queries deserve it.

Land it Tune the query before the server — configuration buys percentages while queries and indexes buy orders of magnitude.

Likely follow-ups
"Give me a case where the bigger instance really was the right answer."

When the queries are already good and the working set has outgrown memory.

A system where pg_stat_statements shows the top queries each using indexes with correct row estimates, the hit ratio has drifted from 99.5 to 96 percent over six months as the data grew, and I/O wait rises at peak.

No index fixes that, because the data is simply bigger than the RAM, and archiving old data was already done or is not possible.

Then doubling memory is a one-line change that restores the hit rate for a year or two, and the cost is a few thousand dollars a month versus weeks of engineering.

The key is that I can show the queries are efficient, so the hardware is being asked to do necessary work, not wasted work.

"What is transparent huge pages versus explicit huge pages, and what do you set?"

Huge pages are 2 MB memory pages instead of 4 KB, so a 64 GB shared_buffers needs 32,000 page-table entries instead of 16 million, which reduces memory used by page tables in every backend process and TLB misses.

Explicit huge pages are reserved at boot with vm.nr_hugepages and used by Postgres when huge_pages = on or try; that is the good kind.

Transparent huge pages, THP, are the kernel automatically merging pages in the background, and the compaction that does the merging causes latency stalls and memory bloat in database workloads.

So the standard setting is explicit huge pages on for Postgres and the InnoDB buffer pool with large-pages, and transparent huge pages set to never or at least madvise. Both Postgres and MySQL documentation say the same.

"How do you convince a team that wants to spend a month on tuning to look at queries first?"

With one afternoon of evidence. I pull the top ten statements by total time from pg_stat_statements or the slow log digest, run EXPLAIN ANALYZE on the top three, and show the sequential scan or the estimate that is off by a thousand times.

Then I add the obvious index on a replica or staging copy and show the same query going from two seconds to two milliseconds. That single demonstration reframes the conversation, because no configuration change produces a thousand-fold improvement.

I then propose the sequence in writing: query fixes this sprint, measure, then the handful of config settings that matter, measure, then hardware if still needed. Teams rarely argue with a before-and-after they watched happen.

Drill · DDL in production & getting data back

This group tests the two highest-stakes operations a senior signs off on: changing a live schema without downtime, and recovering data after something destructive already happened.

Q176 · Scenario. "A one-line ALTER TABLE took your site down for four minutes, even though the change itself was instant. Explain the mechanics and how you run DDL safely next time."

Reveal answer

The real test Whether you know about the lock queue — the outage was the queue, not the ALTER.

Strong answer DDL — data definition language, the schema-changing statements like ALTER TABLE — needs the strongest lock in Postgres, ACCESS EXCLUSIVE, even when the change is metadata-only and takes milliseconds.

The outage mechanism is the queue of doom: some long-running query (a report, a backup, a stuck transaction) was already reading the table, so the ALTER waited for it — and because the ALTER's exclusive lock request was queued, every subsequent query, even plain SELECTs, queued behind the ALTER.

One slow reader plus one instant ALTER equals a frozen table for as long as the reader runs. Safe procedure:

  1. Check pg_stat_activity for long-running queries against the table before starting.
  2. Set a short lock_timeout — SET lock_timeout = '2s' — so the ALTER gives up quickly instead of damming traffic, and wrap it in a retry loop that tries again in a moment. Failing fast and retrying is the discipline; waiting patiently is the outage.
  3. Run it in a low-traffic window regardless, because retries still need a gap to slip into.

MySQL is different in mechanism but identical in trap: online DDL classifies operations as INSTANT, INPLACE, or table-COPY, but even an INSTANT change needs the metadata lock (MDL) briefly at the start and end — and that MDL request queues behind long queries exactly the same way, blocking everything behind it. The same answer applies: check for long transactions first and set a low lock_wait_timeout.

Land it The danger of production DDL is rarely the operation — it is queuing for the lock behind one slow query while the whole world queues behind you; lock_timeout plus retry converts that outage into a non-event.

Likely follow-ups
"Show me the retry loop for a DDL statement with lock_timeout in practice."

In a migration script it is a loop of up to, say, twenty attempts: each attempt runs SET lock_timeout = '2s' followed by the ALTER inside a transaction; if the statement fails with the lock_not_available error, SQLSTATE 55P03, the script sleeps for a few seconds with a little random jitter and tries again; after the last attempt it fails the migration loudly for a human.

Between attempts it can check pg_stat_activity for long transactions on the table and print them, so the operator knows what is in the way.

Flyway and Liquibase do not do this natively, so it lives in the migration's SQL as a DO block or in a wrapper script; tools such as pg-osc and Squawk-aware migration runners add it automatically.

In MySQL the equivalent is SET SESSION lock_wait_timeout = 2 with the same loop.

"Which ALTER TABLE operations are instant in Postgres, and which rewrite the table?"

Instant, metadata-only: adding a nullable column, adding a column with a non-volatile default since Postgres 11, dropping a column, which just hides it, renaming a column or table, adding a CHECK or foreign key as NOT VALID, setting a default, and changing varchar(n) to a larger n or to text.

Rewrite the whole table under an exclusive lock: changing a column's data type in most cases, adding a column with a volatile default, SET NOT NULL without a proven constraint on older versions, and changing tablespace.

In between are operations that scan but do not rewrite, such as VALIDATE CONSTRAINT and adding a constraint without NOT VALID, which take a full scan under a lock that still permits reads and writes only in the NOT VALID two-step.

The Postgres documentation's notes on ALTER TABLE and tools like Squawk classify each one.

"And which MySQL operations are INSTANT, INPLACE, or COPY?"

INSTANT, needing only a brief metadata lock: adding a column, from 8.0.12, at any position from 8.0.29; dropping a column from 8.0.29; renaming a column; setting or dropping a default; adding or dropping a virtual generated column.

INPLACE, which rebuilds or scans in the background while allowing concurrent DML but may take a long time: adding or dropping an index, adding a foreign key with foreign_key_checks off, changing nullability, OPTIMIZE TABLE, and adding a column when the INSTANT limit of 64 instant operations per table since the last rebuild is exceeded.

COPY, which locks the table for writes for the duration: changing a column's data type, changing the character set, converting to a partitioned table, and anything on a table with a FULLTEXT index in some cases.

I always specify ALGORITHM and LOCK explicitly so a fallback fails instead of surprising me.

"How do you test that a specific DDL is instant before running it in production?"

Two checks. First, run it on a production-sized copy, a restored backup on a scratch server, and time it; an instant operation finishes in milliseconds regardless of size, and a rewrite scales with the table.

Second, inspect the lock and rewrite behavior directly: in Postgres, run the ALTER in a transaction on the copy and check pg_locks for the lock mode taken, and compare pg_relation_filenode before and after, since a rewrite changes the file node; in MySQL, EXPLAIN does not cover DDL, but specifying ALGORITHM=INSTANT makes the server refuse with an error if the operation does not qualify, which is the test itself.

I write the observed timing into the migration's pull request as evidence.

Q177 · Scenario. "Product wants a new column with a default value on a 300-million-row table, during business hours. Yes or no — and justify it for both engines."

Reveal answer

Strong answer Yes, on modern versions, with precautions — and this question is exactly where version honesty matters. Historically, adding a column with a default meant rewriting every row to physically store the value: hours of exclusive locking on a table that size.

Since Postgres 11, ADD COLUMN ... DEFAULT <constant> is metadata-only: the default is stored once in the catalog, existing rows are served the value on read without being touched, and the operation is instant.

The catch is volatility — a constant or stable expression qualifies, but a volatile default like random() or gen_random_uuid() still forces the full rewrite, because each row needs its own value.

MySQL 8.0 has the same evolution: ALGORITHM=INSTANT covers adding a column (from 8.0.12, and at any position from 8.0.29), and I would state the algorithm explicitly in the DDL — ALGORITHM=INSTANT, LOCK=NONE — so the statement fails loudly rather than silently falling back to a copy.

So my runbook: confirm the server version, confirm the default is non-volatile, set lock_timeout for the brief metadata lock, and run it. On Postgres 10 or MySQL 5.7, the answer flips to no — that is an expand-and-backfill job instead.

Land it "Can we add a column with a default?" has opposite answers two versions apart — a senior answers with the version, the volatility caveat, and an explicit ALGORITHM clause that refuses to degrade silently.

Likely follow-ups
"The default is now() for a created_at column. Is that instant?"

In Postgres, now() is a stable function, not volatile: it returns the transaction's start time and gives the same value throughout a statement, so ADD COLUMN created_at timestamptz DEFAULT now() qualifies for the fast path, and every existing row is served the single value captured at the time of the ALTER. That is often surprising: all 300 million old rows report the same created_at, the moment of the migration, which is probably not what the business wants, so I usually add the column with no default, backfill a meaningful value in batches from another column if one exists, and then set the default for new rows. clock_timestamp() and random() and gen_random_uuid() are volatile and force a rewrite. In MySQL, DEFAULT CURRENT_TIMESTAMP is supported as an INSTANT add and behaves the same way for old rows.

"The column also needs to be NOT NULL and part of a new index. Still a yes?"

Yes, with sequencing. In Postgres, ADD COLUMN ... DEFAULT 'x' NOT NULL is still instant, because every existing row is defined to have the default, so NOT NULL is provable without a scan.

The index is the slow part: CREATE INDEX CONCURRENTLY on 300 million rows takes tens of minutes and does not block writes, but it must run outside a transaction and outside the migration tool's transaction wrapper, and it needs a lock timeout for its brief lock acquisitions.

In MySQL, the ADD COLUMN with NOT NULL DEFAULT is INSTANT, and ADD INDEX is INPLACE with concurrent DML allowed, running as a background build. So the answer stays yes for business hours, provided the index build is monitored for replica lag and disk I/O.

"What is the risk of MySQL's INSTANT add column that nobody mentions?"

Two.

First, the 64-operation limit: each table tracks a count of instant column changes since its last full rebuild, and after 64 the next ADD COLUMN falls back to INPLACE, which is a rebuild of a 300-million-row table; specifying ALGORITHM=INSTANT makes it fail instead, which is the safer surprise.

Second, row format: instant-added columns are stored as metadata with a version marker on each row written after the change, and rows written before it lack the column physically, so some tools that read InnoDB files directly, older versions of XtraBackup, or replication to an older MySQL version can misread them.

As of Aug 2026 the mainstream tooling handles it, but I check the backup tool version before the first instant column on a critical table.

Q178 · Scenario. "You must change user_id from INT to BIGINT on a 500-million-row table because you are running out of IDs. Direct ALTER, or something else? Walk me through it."

Reveal answer

Strong answer Not a direct ALTER. In Postgres, changing a column's type to a wider one rewrites the entire table under an exclusive lock — hours of downtime at that size. In MySQL, INT to BIGINT is not INPLACE-eligible either; it is a table-COPY operation. The safe path is staged:

  1. Expand: add a new column, user_id_new BIGINT, nullable — instant in both engines.
  2. Keep them in sync: a trigger (or dual-write in the application) copies user_id into user_id_new on every insert and update from this moment on.
  3. Backfill history in small batches — say 10,000 rows per transaction with a pause between batches — watching replication lag and vacuum pressure as I go. Never one giant UPDATE: that is a bloat and lag bomb.
  4. Enforce integrity without a blocking scan: in Postgres, add CHECK (user_id_new IS NOT NULL) NOT VALID — instant, applies to new rows only — then VALIDATE CONSTRAINT, which scans without blocking writes. From Postgres 12, SET NOT NULL can then use that validated constraint as proof and skip its own scan.
  5. Cut over in one short transaction: rename columns, rewire indexes, foreign keys, and sequences; deploy the app change; drop the old column later.

In MySQL I would let gh-ost or pt-online-schema-change do this dance for me instead. Same NOT VALID two-step applies to adding any constraint on a live Postgres table.

Land it Type changes at scale are never one statement — they are add, sync, backfill in batches, validate without blocking, and a short cutover.

Likely follow-ups
"user_id is the primary key and is referenced by ten other tables. How does that change the plan?"

It becomes a coordinated migration. The new BIGINT column, the trigger, and the backfill happen on the users table as described, and every referencing table needs the same treatment for its foreign key column, because a BIGINT cannot reference an INT primary key.

So ten tables get user_id_new, ten triggers, ten backfills.

The cutover transaction then drops the old foreign keys, swaps columns on all eleven tables, adds new foreign keys as NOT VALID, and swaps the primary key: in Postgres that is building a unique index CONCURRENTLY on user_id_new beforehand and then ALTER TABLE ...

ADD PRIMARY KEY USING INDEX, which is fast. Foreign keys are validated afterwards. It is a multi-week project with a rehearsal on a production copy, and the sequence in the runbook is what the review is about.

"You are days from running out of INT values and cannot finish the migration in time. What is the emergency bridge?"

Check the signedness first.

An INT primary key in Postgres is signed, so the ceiling is about 2.1 billion; in MySQL an INT UNSIGNED reaches 4.2 billion, and if the column is signed, changing it to UNSIGNED is itself a rewrite, so that door is mostly closed.

The real bridge is to reuse the negative range: in Postgres, ALTER SEQUENCE users_id_seq MINVALUE -2147483648 RESTART WITH -2147483648 makes new rows take negative IDs, which doubles the runway instantly with no rewrite, provided the application does not assume positive IDs and no ordering logic depends on ID. A second bridge is reclaiming gaps if sequences were cached in large blocks.

I have used the negative-range trick in a real emergency; it buys the weeks the proper migration needs.

"Why is a trigger better than application dual-write for keeping the new column in sync?"

Because it covers every write path atomically. The trigger runs inside the same statement, so the new column is always consistent with the old one, including writes from admin tools, batch jobs, and ad-hoc SQL that would never see the application change.

Application dual-write requires every write path to be found and updated, and a missed one produces rows the backfill must catch on a second pass.

The trigger costs a small per-row overhead, and it must be created before the backfill starts and dropped in the cutover transaction.

In MySQL, gh-ost avoids triggers entirely by reading the binlog, but for a single column copy a BEFORE INSERT OR UPDATE trigger that sets NEW.user_id_new = NEW.user_id is ten lines and hard to get wrong.

"Postgres 12's SET NOT NULL trick: explain exactly why it avoids the scan."

SET NOT NULL must guarantee that no NULL exists, and the only way to know that is to look at every row, which takes an ACCESS EXCLUSIVE lock for the duration.

But a validated CHECK constraint is a proof the database already trusts: adding CHECK (col IS NOT NULL) NOT VALID is instant and applies to new rows, and VALIDATE CONSTRAINT scans the table under a SHARE UPDATE EXCLUSIVE lock, which does not block reads or writes.

Once the constraint is valid, Postgres 12 and later notice during SET NOT NULL that an equivalent valid constraint exists and skip the scan, so the exclusive lock lasts milliseconds. Afterwards the redundant CHECK constraint is dropped.

The same idea applies to adding foreign keys and any CHECK on a live table.

Q179 · Scenario. "Describe the expand–migrate–contract pattern by walking me through a concrete zero-downtime schema change — say moving a column into a new table."

Reveal answer

The real test Whether you understand the invariant: at every step, both the old and the new application version must work.

Strong answer The pattern exists because deploys are not atomic — during a rollout, old and new application versions run side by side against one schema, so every schema state must satisfy both. Moving shipping_address out of orders into its own table:

  1. Expand. Create the new order_addresses table. Purely additive; nothing reads it, nothing can break, and the old app version is oblivious.
  2. Dual-write. Deploy an app version that writes to both places but still reads from the old column. Now new data exists in both; a rollback of this deploy loses nothing.
  3. Backfill. Copy historical rows into the new table in chunks — bounded batches, committed frequently, throttled against replication lag. After this, the new table is complete and continuously maintained by the dual-writes.
  4. Migrate reads. Deploy an app version that reads from the new table. Verification step: compare counts and checksums between old and new before flipping, and keep the old path behind a feature flag for fast retreat.
  5. Contract. Only after a bake period — days, not minutes — stop writing the old column, and later drop it in its own migration. Dropping is the only irreversible step, so it goes last and travels alone.

The whole shape is deliberately boring: five small reversible steps instead of one heroic irreversible one.

Land it Expand–migrate–contract works because every step is individually deployable and reversible — the destructive part is postponed until it is provably safe and trivially small.

Likely follow-ups
"During the dual-write phase, the two writes are in the same transaction, but a bug writes different values. How do you detect it?"

With a comparison job that runs throughout the dual-write phase, not just before the read switch.

It joins orders to order_addresses on order_id and reports rows where the old column and the new table disagree, restricted to rows updated in the last hour so it stays cheap, plus a nightly full pass.

The count goes on a dashboard and any non-zero value stops the migration from advancing. When it finds mismatches, the pattern of which code path wrote them, from application_name or updated_by, usually points at the path that was missed or mapped incorrectly.

The fix is deployed, the backfill repairs the affected rows from the old column, which is still the source of truth, and the comparison must stay at zero for several days before reads move.

"What happens if you need to roll back after step four, when reads have moved?"

It is still safe, because the old column is still being written. Rolling back means deploying the previous version or flipping the feature flag, so reads come from the old column, which has every write. Nothing is lost because contract has not happened.

That is precisely why the contract step is delayed for days: as long as both copies are maintained, either read path is correct.

The only thing to watch is a write path introduced by the new version that writes only to the new table; the rule during the migration is that every write goes to both until contract, and the comparison job enforces it.

Rollback after contract is the real danger, which is why contract is a separate migration after a bake period.

"The change is a column rename, not a move. Is the full pattern still needed?"

A plain RENAME COLUMN is instant on both engines, but it is not safe during a rolling deploy: the old application version references the old name and breaks the moment the rename lands, and the new version breaks until it lands.

So yes, the pattern applies, in a lighter form: add the new column, dual-write, backfill, switch reads, then drop the old one.

A cheaper alternative in Postgres is to keep the physical column and add a view or a generated column with the new name, though generated columns cannot be written to.

The very cheapest is to not rename at all and change the name only in the application's mapping layer, which is what I usually recommend, because a column name is rarely worth a five-step migration.

"What would you cut from the five steps under time pressure, and what would you never cut?"

Under pressure I would merge steps two and three, deploying dual-write and running the backfill immediately, and I would shorten the bake period before contract from weeks to a few days with the comparison job as the gate. I would never cut dual-write itself, because without it the new table is stale the moment the backfill ends; never cut the comparison, because it is the only evidence the data is right; and never do contract in the same deploy as the read switch, because that removes the rollback path. If the deadline truly does not fit, the honest option is to ship the feature reading from the old column and do the move afterwards, since the pattern exists to protect the data, not the calendar.

Q180. "Explain gh-ost and pt-online-schema-change in one plain paragraph — and when you reach for them instead of native online DDL."

Reveal answer

Strong answer Both tools solve the same MySQL problem the same basic way: they create an empty shadow table with the new schema, copy the existing rows over in small chunks, capture every change that happens to the real table during the copy, apply those changes to the shadow, and finally swap the two tables with an atomic rename that takes only an instant.

They differ in how they capture the ongoing changes: pt-online-schema-change installs triggers on the original table, which adds write overhead to every statement, while gh-ost subscribes to the binary log — the replication change stream — so the original table carries no extra triggers at all, and the migration can be throttled or paused cleanly.

I reach for them when native online DDL is not enough: when the operation is a table-COPY class change (like a type change), when the table is so large that I need pause, throttle, and progress visibility, or when replica lag during the change must be actively controlled.

For an operation MySQL can genuinely do INSTANT or INPLACE, native DDL is simpler and I use it.

Land it Shadow table, chunked copy, change replay, atomic swap — use the tools when the native path would copy the table anyway, because they add the throttle and pause buttons the native copy lacks.

Likely follow-ups
"What is the cut-over step in gh-ost and what can go wrong there?"

When the shadow table is caught up, gh-ost needs to swap the tables atomically.

MySQL's RENAME TABLE a TO b, c TO a is atomic, but gh-ost must make sure no writes slip in between the last binlog event applied and the rename, so it briefly locks the original table, applies the final events, and performs the rename, typically holding the lock for well under a second.

The failure mode is the lock wait: if a long query holds a metadata lock on the table, the cut-over waits and, as with any DDL, queues everything behind it; gh-ost protects against that with a cut-over lock timeout and retries, and it can be told to postpone cut-over until an operator removes a flag file.

The other thing that goes wrong is disk space, since the shadow table doubles the table's footprint.

"How does gh-ost throttle, and what do you set?"

gh-ost checks replica lag continuously by writing a heartbeat into its own changelog table and reading it on the replicas listed in --throttle-control-replicas, pausing the row copy when lag exceeds --max-lag-millis, typically 1500.

It also pauses when the primary's Threads_running exceeds --max-load, and it can be paused by hand by creating the file named in --throttle-flag-file. Chunk size, --chunk-size, defaults to 1000 rows per copy statement, and --nice-ratio adds a sleep proportional to the copy time.

The right settings come from watching the first ten minutes: if lag rises, reduce chunk size or add nice ratio; if the copy is far too slow, raise chunk size.

The copy of a billion-row table can take a day, and that is fine because it is fully online.

"Is there an equivalent for Postgres, or is it not needed?"

Postgres needs it less, because most common changes are metadata-only or have CONCURRENTLY variants, and the NOT VALID pattern covers constraints.

For the remaining rewrites, such as changing a column type or reordering columns, the tools are pg_repack for reclaiming space and pg-osc, which is a gh-ost-style tool for Postgres using triggers and a shadow table, or pgroll for versioned expand-and-contract migrations.

Logical replication provides another route: replicate the table to a new one with the changed schema and swap.

In practice I do Postgres type changes with the manual expand and contract from the earlier question, because the steps are short and the tooling ecosystem is younger than MySQL's, though as of Aug 2026 pgroll is gaining adoption.

Q181 · Scenario. "Your eight-hour backfill migration is running. Midway, replica lag hits twenty minutes and the table starts bloating badly. What is the interplay you failed to plan for?"

Reveal answer

Strong answer A long migration is not just its own workload — it fights the database's background machinery on two fronts, and both were predictable:

  1. Against cleanup. Every batched UPDATE creates dead row versions faster than autovacuum can clear them, so the table and its indexes swell. Worse, if the backfill runs as one long transaction, it pins the cleanup horizon for the whole database — no table can have versions younger than my transaction removed. Eight hours of that is bloat everywhere, not just here.
  2. Against replication. Every changed row must be shipped to and replayed on the replicas, and replay is less parallel than the primary's work — a firehose backfill saturates it. Twenty minutes of lag means read replicas serve twenty-minute-old data (correctness incidents in anything reading them) and the failover point is twenty minutes behind (a temporary hole in disaster readiness).

Mid-incident, I pause the backfill and let vacuum and the replicas catch up — a backfill that cannot pause is itself a design failure. The proper design: commit per small batch so no long transaction ever exists; between batches, check pg_stat_replication (or SHOW REPLICA STATUS lag) and sleep whenever lag exceeds a threshold — a feedback loop, not a fixed sleep; schedule across low-traffic hours; and afterwards run a manual VACUUM ANALYZE on the table rather than waiting for autovacuum to notice.

Land it A migration shares the database with vacuum and replication — batch small, commit often, and throttle on replica lag as a feedback signal, not a guess.

Likely follow-ups
"You paused it, but the replica is not catching up. Why?"

The replica is still working through the backlog that was already shipped, and its apply is the bottleneck.

If the backfill ran as few huge transactions, the replica must apply each one in full, single-threaded in Postgres physical replay and serialized in MySQL if the transactions conflict, so twenty minutes of lag may take twenty minutes to drain even with nothing new arriving.

I check that the replica's I/O is saturated, which is the expected state, and that nothing else is hurting it, such as a long query on a Postgres standby causing replay to wait, or a reporting job on a MySQL replica holding a metadata lock that the replicated DDL is stuck behind.

If the replica is idle and lag is flat, replication itself has stopped and needs restarting.

"How do you write the batch loop so it is safe against replica lag and vacuum? Show the shape."

The loop keeps a cursor on the primary key. Each iteration: begin a transaction, UPDATE the next range of, say, 5,000 rows by id, commit, and record the last id in a progress table so a restart resumes.

Then read lag from pg_stat_replication's replay_lag on the primary, or from a heartbeat table, and if it exceeds a threshold sleep and re-check before continuing; also read n_dead_tup on the target table and slow down if it climbs past a limit.

The transaction is short, so it never pins the cleanup horizon. Each batch is idempotent, updating only rows where the new column is still NULL, so re-running after a crash is harmless.

The script logs rows per second and lag each minute, and it responds to a stop file so an operator can pause it instantly.

"Why does one long transaction pin cleanup for every table, not just the one being backfilled?"

Postgres decides what vacuum may remove using a single horizon: the oldest transaction ID that any open transaction might still need to see. That horizon is per database, not per table, because a transaction could read any table at any point.

So while the backfill transaction is open, every table's vacuum can only remove dead rows older than the backfill's start, and a hot table elsewhere accumulates eight hours of dead versions it cannot clear.

The same logic applies to a long-running SELECT in REPEATABLE READ, to an idle-in-transaction session, and to a standby with hot_standby_feedback. InnoDB's purge behaves identically with its oldest read view. That is why the single most important property of a backfill is short transactions.

"Twenty minutes of lag happened. What did it actually cost, and what do you tell stakeholders?"

Two costs. Any feature reading from replicas served data up to twenty minutes stale, so users may have seen missing orders or old balances, and any read-your-writes routing with a short sticky window failed for that period; I would check support tickets for that window.

And for those twenty minutes, a failover would have lost up to twenty minutes of commits, so our effective RPO was twenty minutes rather than seconds.

To stakeholders I state both plainly, with the window's start and end, whether any customer impact was observed, and the process change: backfills now run with a lag-aware loop, under a role with limits, in a scheduled window, and with a named operator watching.

The lesson is presented as a process gap, not as the migration author's mistake.

Q182. "How should schema migrations be managed in a CI/CD pipeline? What are the non-negotiable rules?"

Reveal answer

Strong answer Migrations are code: versioned files in the repository, applied by a tool — Flyway or Liquibase in the Java world — that records each applied migration in a schema-history table and applies only what is new, in order. In CI (continuous integration — the automated build-and-test pipeline), every migration runs against a disposable database on every build, so a broken migration fails a pull request instead of a production deploy. The non-negotiable rules:

  1. Never edit an applied migration. Flyway checksums each file; editing one breaks validation, and worse, environments that already ran the old version now silently diverge from ones that will run the new one. Fixes are always a new migration.
  2. Migrations run before the application deploys, and the schema they produce must be compatible with both the old and new application versions — because during rollout, and during any rollback, both versions run against it. This is why expand–migrate–contract exists.
  3. One logical change per migration, and destructive steps (drops, renames) in their own separate migration, deployed only after the code that stopped using them has been stable.

Land it The two rules that prevent real outages: never rewrite history, and never ship a schema that only one version of the app can live with.

Likely follow-ups
"Two developers create migration V42 on separate branches. What happens and how do you prevent it?"

With Flyway's versioned migrations, both branches pass CI alone, and when the second one merges, Flyway finds two files with the same version and refuses to run, or, worse, if the versions differ but one is lower than an already-applied version, Flyway rejects it as out of order unless outOfOrder is enabled.

The prevention is timestamps as versions, such as V20260828_1432__add_index.sql, so collisions are practically impossible, plus a CI check that runs the full migration set from an empty database on every merge to main, which catches ordering problems immediately.

Liquibase uses changeset IDs and author names, which avoids the numeric collision but not the ordering issue. Some teams add a merge-queue step that reruns CI after rebase for exactly this reason.

"Should migrations run automatically on deploy, or by a human?"

Automatically for the additive, fast ones, and as a separate gated step for anything long or risky.

The deploy pipeline runs the migration step before the application rollout, with a lock in the schema-history table so only one runner executes; it aborts the deploy if the migration fails.

Migrations classified as heavy, such as backfills or index builds on large tables, are not run by the deploy at all: they are executed by a separate job with a human watching, usually from the same repository with a marker that the deploy step skips.

The classification is enforced by a linter in CI, so a developer cannot accidentally put a full-table rewrite into the automatic path. Fully manual migrations lead to drift between environments, so manual is the exception, never the default.

"How do you keep the schema of staging and production from drifting?"

The schema-history table is the contract: every environment must have applied exactly the same list of migrations, and CI compares.

A nightly job dumps the schema of each environment with pg_dump --schema-only or mysqldump --no-data, normalizes it, and diffs it against the schema produced by running all migrations on an empty database; any difference means someone made a manual change, and it opens a ticket with the diff.

Production access for manual DDL is restricted to a break-glass role whose use pages the team. Flyway's validate command at startup adds a last check that applied checksums match the files.

Drift is not prevented by policy; it is detected by the diff and corrected by a migration that encodes the manual change.

"How does the migration tool interact with a transaction, and why does that matter for CREATE INDEX CONCURRENTLY?"

Flyway wraps each migration in a transaction by default on Postgres, so a failed migration rolls back cleanly, which is a good default. But CREATE INDEX CONCURRENTLY cannot run inside a transaction block, so the migration fails with an error.

The fix is to mark that migration as non-transactional, which in Flyway is done per script with the executeInTransaction=false script configuration, and to make it idempotent with IF NOT EXISTS, because a non-transactional migration that fails halfway leaves partial state that Flyway records as failed and must be repaired.

MySQL DDL is never transactional anyway, since each DDL statement commits implicitly, so a multi-statement MySQL migration that fails halfway always needs a repair step. That is one reason for one change per migration.

Q183. "Your migration tool supports down-migrations. Do you trust them as your rollback strategy?"

Reveal answer

Strong answer No — and I say that as someone who still writes them where they are cheap. Down-migrations have two honest problems.

First, they are the least-tested code in the system: written hopefully, exercised never, and expected to work for the first time during an emergency.

Second, many changes have no true inverse — the down for "drop column" can recreate the column but not the data it held, and the down for a backfill cannot un-know what was written meanwhile.

So my strategy is roll forward: when a migration causes trouble, I write a new migration that corrects it, tested the same way as any other. That keeps history linear and every environment on the same path.

The complements that make this safe: destructive steps are separated and delayed (so there is rarely anything to undo urgently), and before any genuinely risky migration I note the backup position so point-in-time recovery is the true last-resort rollback — for the data, which is the part down-migrations can never give back.

Land it Schema can be rolled back; data usually cannot — so plan to roll forward, and let backups, not down-scripts, be the last resort.

Likely follow-ups
"Give me a concrete example where a down-migration made things worse."

A team added a NOT NULL column with a default, deployed, and then rolled back the application because of an unrelated bug. The deploy tooling ran the down-migration, which dropped the column.

Ten minutes later they redeployed the fixed application, the up-migration re-added the column with the default, and every value users had entered in the ten minutes between was gone, replaced by the default. Nobody noticed for a day.

The down-migration did exactly what it said, and that was the problem: it destroyed data to restore a schema.

Had they rolled forward, the old application version would have simply ignored the extra column, because the expand step is backward compatible by design, and nothing would have been lost.

"So how do you roll back a migration that genuinely broke production?"

It depends on what broke. If the migration made the schema incompatible with the running application, the fastest fix is a new forward migration that restores compatibility, for example re-adding a dropped column, which is a minute to write and goes through the same pipeline.

If the migration corrupted data, for example a backfill with a wrong formula, the fix is a corrective migration computed from a source of truth, or, if none exists, point-in-time recovery of the affected table to a side instance and a repair by comparison.

If the migration is still running and causing harm, I stop it, which is why long migrations must be pausable. In every case the record of what happened stays in the schema history, which is what makes the next incident's timeline reconstructible.

"Where are down-migrations genuinely useful?"

In development and CI, where a developer switches branches many times a day and needs a quick way to return the local database to a previous state without rebuilding it; there the data is disposable and the down script is a convenience.

In review environments that are created and destroyed per pull request, the same applies. And for purely additive changes such as adding an index, where the down is a DROP INDEX with no data implications, the down is harmless and documents intent.

So I write them where they are trivially correct and treat them as developer tooling, and I make sure the production pipeline never executes them automatically, because production rollback is a forward migration or a restore.

Q184 · Scenario. "A migration that took ninety seconds in staging ran for four hours in production and caused an incident. What went wrong with the process, and what does 'testing DDL properly' mean to you?"

Reveal answer

Strong answer The process failure is that staging answered "is this migration correct?" while nobody asked "how does this migration behave at production scale?" — and those are different questions. Ninety seconds against a hundred thousand staging rows says nothing about five hundred million production rows, production's concurrent traffic, or its long-running queries queuing behind the DDL lock. Testing DDL properly means:

  1. Run it against a production-sized copy — ideally a restore of last night's actual backup, which also quietly proves the backups restore. Measure wall-clock time, disk consumed (a table rewrite needs roughly the table's size again in free space), and WAL or binlog generated (which predicts the replication-lag hit).
  2. Check the operation's lock class first, not after: in MySQL, does it run as INSTANT, INPLACE, or COPY; in Postgres, which lock does it take and for how long. Vendor documentation plus a dry run, not folklore.
  3. Rehearse the runbook, not just the SQL: the lock_timeout and retry wrapper, the pause-and-resume plan for a backfill, the abort criteria and who decides.
  4. For anything measured in hours, stop and redesign — batch it, or use pg_repack or gh-ost — because a four-hour irreversible statement in production is not a migration, it is a hostage situation.

Land it Staging validates correctness; only a prod-sized copy validates duration, locks, and disk — and duration is the thing that causes the outage.

Likely follow-ups
"You cannot afford a full production-sized copy for every migration. What is the minimum that still catches this?"

Two cheap substitutes.

A lock-class check that needs no data at all: classify the statement using the engine's documentation or a linter like Squawk, which flags a type change or a non-concurrent index build in seconds in CI. And a scaled test: restore only the affected tables, or a representative sample of a few tens of millions of rows, and measure the operation's time, then extrapolate linearly for rewrites and index builds; if the extrapolation is over a few minutes, the migration goes to the online-tool path.

For the full rehearsal, a weekly restore of production to a scratch instance for backup verification doubles as the test bed, so heavy migrations are simply scheduled to be tried on that week's restore. The cost is one instance, not one per migration.

"The migration is four hours in and you decide to abort. What are the consequences on each engine?"

In Postgres, a DDL statement in a transaction rolls back cleanly; the table rewrite's new file is discarded and the original is untouched, so aborting costs the four hours and nothing else, and the lock releases immediately.

The exception is CREATE INDEX CONCURRENTLY, which leaves an invalid index to drop.

In MySQL, an INPLACE operation that is cancelled also cleans up its temporary files, but a COPY-algorithm ALTER that is killed must roll back its copy, and a large partially copied table can take significant time to remove; the original is intact.

pt-online-schema-change and gh-ost leave the shadow table and possibly triggers behind if killed with a hard signal, and they document the cleanup. The abort criteria and the cleanup commands belong in the runbook before the migration starts.

"How do you predict the replication lag a migration will cause?"

Measure the WAL or binlog it generates on the rehearsal. In Postgres, compare pg_current_wal_lsn() before and after the migration with pg_wal_lsn_diff to get bytes; in MySQL, compare the binlog position or the Binlog_bytes_written status.

Then compare that volume to the replica's measured apply rate: if a replica applies 50 MB per second and the migration produces 30 GB of log in a burst, the replica will lag about ten minutes even if the primary finishes in two.

A rewrite of a 200 GB table produces at least 200 GB of log. That calculation decides whether the migration is done natively in one go or through a throttled tool that spreads the log over hours.

It also tells the on-call what lag alert to silence and for how long.

Q185. "Logical versus physical backups — what is the real difference that matters at scale?"

Reveal answer

Strong answer A logical backup (pg_dump in Postgres, mysqldump) exports the database as statements and data — essentially instructions to rebuild it. A physical backup (pg_basebackup, Percona XtraBackup) copies the actual data files.

Logical wins on flexibility: it restores across versions and even engines, and can restore a single table. Physical wins on speed and fidelity: it captures the whole cluster and restores at raw copy speed. The difference that matters at scale is restore time.

Restoring a logical dump means re-executing everything — reinserting every row and, expensively, rebuilding every index from scratch; on a 2-terabyte database that can take a day or more. Restoring a physical backup is copying files and starting up: closer to an hour.

Since restore time during a disaster is your downtime, serious setups use physical backups plus continuous log archiving as the recovery backbone, and keep logical dumps as a complement — for per-table rescue, portability, and long-term archives.

Going deeper The restore-time gap is narrower than it used to be, and a senior should know the levers.

pg_dump with --format=directory and --jobs=8 dumps tables in parallel, and pg_restore --jobs=8 restores and builds indexes in parallel, so a logical restore of a terabyte can be brought down from a day to a few hours on a big machine; it still cannot match copying files.

Physical backups have their own modern tooling: pgBackRest and Barman for Postgres provide incremental and differential backups, parallel compression, and automatic WAL archiving with retention policies, and XtraBackup does incremental backups for InnoDB by tracking changed pages.

Cloud volume snapshots are the fastest physical backup of all when the database is crash-consistent on one volume, restoring in minutes regardless of size, and they are the usual primary mechanism on managed services, with logical dumps kept only for portability.

A restore drill is the only measurement that counts; whatever the tool, the number to write down is hours from "we need it back" to "queries are answering."

Land it Choose backups by restore time, not backup convenience — the dump that takes a day to replay is a day of downtime you signed up for in advance.

Likely follow-ups
"Can you restore a physical backup to a different major version, or a different machine architecture?"

No to major versions: a physical backup is the on-disk format of one major version, and Postgres 15 files cannot be started by Postgres 17; a major upgrade after restore requires pg_upgrade on the restored cluster, which is fast with the link mode but is a separate step.

Minor versions within a major are fine.

Architecture and operating system matter too, because the files depend on endianness, alignment, and the collation library: restoring onto a machine with a different glibc version can silently corrupt text index ordering, which is why Postgres records the collation version and warns.

MySQL physical backups from XtraBackup have similar rules, tied to the InnoDB format of the server version. Logical dumps are the way across any of those boundaries.

"How do you restore one table from a physical backup?"

Restore the whole cluster to a side instance, which is the honest answer for Postgres, then pg_dump the one table from that instance and load it into production.

With WAL archiving, the side restore can be taken to any point in time, so this is also how a single-table point-in-time recovery works.

It takes as long as a full restore, which is why teams that need frequent per-table rescue keep logical dumps as a complement.

MySQL is better here: with innodb_file_per_table, XtraBackup supports exporting a single table's tablespace, and the table can be imported into a running server with ALTER TABLE ... IMPORT TABLESPACE, which restores one table in minutes without touching the rest.

"What does a logical backup miss that a physical one captures?"

A logical dump captures what SQL can express: tables, data, indexes as definitions, views, functions, and, with pg_dumpall, roles and tablespaces.

It does not capture the physical layout, statistics, or, in Postgres versions before 18, the optimizer statistics at all, so a restored database has empty statistics until ANALYZE runs, which is a classic post-restore performance surprise; Postgres 18 can dump statistics as of Aug 2026.

It does not capture unlogged tables' data, or configuration files like postgresql.conf and pg_hba.conf. It also does not capture the WAL, so it cannot be replayed forward: a logical dump is a point, while a physical backup plus archive is a range.

Physical backups capture everything on disk, including the configuration if the tool is told to.

Q186 · Scenario. "At 14:32 a bad deploy ran an UPDATE without a WHERE clause on the payments table. It is now 14:50. You have nightly physical backups and continuous WAL archiving. Walk me through the actual recovery decision."

Reveal answer

The real test Whether you know not to restore over production — the side-instance extract is the senior move.

Strong answer This is the textbook case for point-in-time recovery (PITR): restore the base backup, then replay the archived write-ahead log — the journal of every change — and stop the replay just before the disaster. My decision tree:

  1. Stop the compounding first: if downstream jobs are reading the corrupted column, pause them. Eighteen minutes of legitimate writes have happened since 14:32 — that fact drives everything.
  2. Reject the naive move: restoring production to 14:31 would throw away those eighteen minutes of good orders and payments. Full-restore-in-place is only right if the damage is total and recent data is worthless.
  3. Instead, PITR on a side instance: restore yesterday's base backup to a scratch server and replay WAL to 14:31:59. Production keeps serving everything except the damaged column.
  4. Extract and repair: dump just the payments table from the side instance and repair production in place with an UPDATE joining old values back by primary key — surgical, auditable, and only touching rows the bad UPDATE hit.
pitr-side-instance-outline.txt
# On a scratch server: restore base backup, then configure recovery
restore_command = 'aws s3 cp s3://wal-archive/%f "%p"'
recovery_target_time = '2026-08-23 14:31:59'
recovery_target_action = 'pause'   # inspect before promoting
# touch recovery.signal, start postgres, verify the data looks right

# Extract the good table state and repair prod by comparison:
pg_dump -t payments --data-only side_db > payments_1431.sql

# MySQL equivalent: restore XtraBackup copy, then replay binlogs:
mysqlbinlog --stop-datetime="2026-08-23 14:31:59" binlog.0042 | mysql

Land it PITR to a side instance and repair production surgically — restoring over prod trades eighteen minutes of real customer data for convenience, and that trade is almost never right.

Likely follow-ups
"How do you find the exact moment to stop the replay if nobody knows the precise time of the bad UPDATE?"

The log has it.

In Postgres, pg_waldump over the WAL segments around the suspected time lists each transaction with its commit time, and with wal_level logical or a large enough update the relation and row counts point at the payments table; a transaction touching a million rows at once stands out.

Then I set recovery_target_xid to the transaction just before it, or recovery_target_lsn, which is more precise than a time.

In MySQL, mysqlbinlog --base64-output=DECODE-ROWS -vv over the binlog around 14:32 shows each event with its timestamp and table map; the bad UPDATE appears as a giant block of row events, and --stop-position with the byte offset just before it is exact.

The application's deploy timestamp and the slow log entry for the UPDATE narrow the search to seconds.

"You repaired production from the side instance. How do you verify the repair and what could still be wrong?"

Verification is a comparison: for each row the bad UPDATE touched, the repaired value in production should equal the side instance's value at 14:31:59, unless a legitimate write changed that row after 14:32.

So I list rows changed after 14:32 from application logs or updated_at and exclude them from the blind repair, handling them by hand with the business.

What could still be wrong: downstream systems that consumed the bad values during the eighteen minutes, such as an accounting export or a search index, need re-running; cached values in Redis need invalidating; and rows inserted after 14:32 that copied values from corrupted rows, for example refunds computed from the wrong amount, need tracing.

The repair is done when the reconciliation against the payment gateway matches.

"The WAL archive has a gap at 09:00. What are your options?"

Replay stops at the gap, so PITR from last night's base backup can only reach 09:00. The options, in order: check whether the missing segments still exist in pg_wal on the primary or on any standby, because the archiver failed but the files may not have been recycled yet, and copy them into the archive; check whether a standby has the data at a later point and take a base backup from it, which restarts the timeline from there; or, if the primary itself is healthy, which it is in this scenario, take a fresh base backup from it now and use the current WAL from that point, which does not help with the 14:32 repair but restores protection going forward. For the repair, the side instance at 09:00 plus the application's audit log of payments between 09:00 and 14:32 may still reconstruct the values.

"What guardrail stops an UPDATE without a WHERE from ever running again?"

Several layers. In MySQL, sql_safe_updates = 1 for interactive and application accounts makes the server reject UPDATE and DELETE statements without a key-based WHERE; it can be set in init_connect for specific users. Postgres has no built-in equivalent, but the pg_safeupdate extension does the same.

At the application layer, the data-access framework can refuse to execute an update without a predicate, and the ORM's bulk update methods can be wrapped.

In code review, a linter flags any UPDATE or DELETE literal lacking WHERE. And structurally, the deploy that ran the statement should never have had rights to run ad-hoc SQL on the primary: the migration path is the only path for schema and bulk data changes, and it goes through review and rehearsal.

Q187 · Scenario. "Your backup job has been green for a year. During a real outage, the restore fails. How does this happen to competent teams, and what practice prevents it?"

Reveal answer

Strong answer It happens because the green checkmark measures the wrong thing: it proves a job ran and produced bytes, not that those bytes can become a working database.

The classic failure modes are all invisible to the job's own success signal: the backup captured the wrong directory after a server migration; the WAL archive has a silent gap, so replay stops halfway; the encryption key or the credentials to fetch the backup exist only on the server that just died; the dump was truncated by a disk-full that the script did not propagate as a failure; or the restore needs a version or extension the recovery host lacks.

The practice that prevents it is the restore drill: on a schedule — weekly for critical systems — automatically restore the latest backup to a scratch instance, replay logs to a recent point, run sanity checks (row counts on key tables, checksums, application smoke queries), record how long it took, and alert if any step fails.

That converts restore from a hope into a tested code path, and the measured duration keeps the recovery-time promise honest.

Land it A backup you have never restored is a hope, not a backup — the drill is the only green checkmark that means anything.

Likely follow-ups
"What does the restore drill check, concretely, beyond 'it started'?"

A checklist with numbers. The restore completes without errors and WAL replay reaches a target within the last hour, proving the archive has no gaps. Row counts of the five largest tables match the production counts recorded at the same timestamp within a small tolerance.

A checksum of a sample of rows from a critical table matches production. The application's smoke tests run against the restored instance and pass, which proves roles, extensions, and functions came back too. pg_checksums or CHECK TABLE reports no corruption.

Elapsed time for each phase is recorded and compared with the RTO. And the drill runs from a clean machine using only the documented runbook and the credentials from the vault, not from the DBA's laptop, so it proves the documentation as well as the bytes.

"Restores take six hours and the RTO is one hour. What do you change?"

First I find where the six hours go from the drill's timing: usually it is downloading the backup from cold storage, then replaying a day of WAL, then cache warm-up.

Each has a lever: keep the latest backup on fast storage in the same region rather than archival storage; take base backups more often, or use incremental backups with pgBackRest or XtraBackup, so replay covers hours not a day; restore onto a machine with fast NVMe.

If that still misses one hour, the honest answer is that backups alone cannot meet the RTO and a standby replica is required for the fast path, with backups covering the human-error case.

I present the RTO as a cost curve: an hour needs a warm standby, six hours needs only the backups we have.

"Backups are on a managed cloud database. Do you still drill?"

Yes, because the provider guarantees the snapshot exists, not that our recovery works.

A managed restore creates a new instance from a snapshot, which takes time we have not measured, comes up with a new endpoint our configuration does not know, may lack parameter groups, extensions, or users that were configured outside the snapshot, and its point-in-time window has a retention we should verify.

A quarterly drill of "restore to a point in time yesterday, connect the application to it in staging, run the smoke tests, and time the whole thing" catches all of that.

It also catches the encryption key problem: a snapshot encrypted with a key in an account we cannot reach during the outage is not a backup. The drill is cheaper on a managed service, not unnecessary.

Q188. "Explain RPO and RTO in plain words, and map the common backup strategies onto them."

Reveal answer

Strong answer RPO — recovery point objective — is how much recent data you are willing to lose: the gap between the disaster and the last moment you can recover to.

RTO — recovery time objective — is how long you are willing to be down while recovering. They are bought separately.

A nightly dump gives an RPO of up to 24 hours (everything since last night is gone) and an RTO of however long the replay takes — often hours.

Physical base backups plus continuous WAL or binlog archiving give an RPO of seconds to minutes (you can replay to just before the failure) with an RTO of the restore-plus-replay time.

A hot standby replica gives an RTO of seconds — promote it — and near-zero RPO for hardware failure, but it is not a backup against human error, which is the next question.

The senior move is to get the business to state its tolerated RPO and RTO in numbers first, because "we need backups" is not a requirement — "lose at most five minutes, back within one hour" is, and it prices the architecture.

Land it RPO is data you lose, RTO is time you are down — pick the numbers with the business first and let them choose the machinery, not the other way around.

Likely follow-ups
"Business says RPO zero and RTO five minutes. What does that actually cost?"

RPO zero means no acknowledged commit can be lost, so every commit must be durable on at least two machines before the client is told: synchronous replication to a standby in a different failure domain, with the latency cost on every write and the availability coupling that if the standby is unreachable, writes stall or a second standby must be in the quorum.

RTO five minutes means automatic failover with a failover manager, a proxy layer that repoints clients in seconds, and drills proving the whole chain works.

Plus backups for the human-error case, because none of that protects against a bad UPDATE. In money terms, that is at least three database servers, a consensus store, engineering time to build and test it, and a permanent operational duty.

I would quote that back and ask which flows really need zero.

"Is the RPO the same for hardware failure and for human error?"

No, and that distinction is where most plans are dishonest. For hardware failure, a synchronous standby gives RPO zero and RTO minutes.

For human error, the standby is useless because it faithfully copied the mistake, so the RPO is determined by how far back you can go and how precisely: with continuous WAL archiving, you can recover to the second before the mistake, so RPO is effectively zero but the RTO is the full side-restore and repair time, which is hours.

With nightly dumps only, the human-error RPO is up to a day. So a complete statement has four numbers: RPO and RTO for infrastructure failure, and RPO and RTO for data-destroying mistakes, and the second pair is usually the weaker one.

"How does a delayed replica fit into the RPO and RTO map?"

It sits between backups and a hot standby for the human-error case. A replica applying changes one hour behind gives a warm copy that a mistake has not reached yet, if noticed within the hour.

The RTO for that case is minutes: pause the delayed replica, advance it to just before the mistake using recovery_target on Postgres or START REPLICA UNTIL on MySQL, and extract or promote.

The RPO is near zero for the rows that were damaged, because the replay stops right before the bad transaction.

Its limits: it only helps for mistakes noticed within the delay, it costs a full extra server, and it does not replace backups for long-noticed corruption or for a total site loss. It is the cheapest big improvement to the human-error row of the table.

Q189 · Scenario. "A manager says: 'We have two replicas — why are we paying for backups?' The next week someone deletes a customer's rows on the primary, and you check the replica. What do you find, and what is the honest answer to the manager?"

Reveal answer

Strong answer On the replica I find the rows already gone — replication's whole job is to copy every change faithfully and fast, so the DELETE reached both replicas within seconds.

Replication protects against hardware and availability failures: a dead disk, a dead server, a dead zone.

It offers zero protection against the most common disaster, which is a correct system executing a wrong instruction — bad DELETEs, bad deploys, bad migrations, and compromised credentials all replicate perfectly.

Backups protect against exactly that class, because they are a point in the past that the mistake cannot reach. The honest answer to the manager is that replicas and backups answer different failures and we need both.

Then I offer the middle trick worth knowing: a delayed replica — one deliberately kept behind, via recovery_min_apply_delay = '1h' in Postgres or SOURCE_DELAY = 3600 in MySQL. When a bad statement hits the primary, you have an hour to pause the delayed replica before the mistake reaches it, giving you a warm pre-disaster copy without a full restore.

It narrows the recovery window but still does not replace backups — it only covers mistakes noticed within the delay.

Land it Replication copies your mistakes at full speed — replicas buy availability, backups buy history, and only history undoes human error.

Likely follow-ups
"Walk me through using the delayed replica when the DELETE is noticed forty minutes later."

The replica is an hour behind, so the DELETE will reach it in twenty minutes. First, stop the apply immediately: on Postgres, SELECT pg_wal_replay_pause(); on MySQL, STOP REPLICA SQL_THREAD. Now the replica holds a state from an hour ago, and I have time.

Next, find the exact position of the DELETE in the log using the methods from the PITR question, and advance the replica to just before it: on Postgres, set recovery_target_lsn and resume; on MySQL, START REPLICA UNTIL SQL_BEFORE_GTIDS = 'the delete's GTID'.

The replica now contains the customer's rows as they were the moment before deletion, including everything written during the forty minutes.

Then I dump those rows and insert them into the primary, and finally resume or rebuild the delayed replica, because it can no longer simply continue past a point I skipped.

"What other failure does a replica not protect against?"

Corruption that replicates, and correlated failures. A bug in the application that writes wrong values replicates perfectly.

A storage-level corruption on the primary usually does not replicate in Postgres, because WAL carries logical page changes, but a corrupted page written by a bad kernel or disk can be shipped by full-page writes, and in MySQL a corrupted row image in the binlog is applied faithfully.

Correlated failures: both primary and replica in the same rack, zone, account, or behind the same credentials, so a region outage or a compromised admin account takes both. And an operator mistake in the replication setup itself, such as promoting the wrong node.

Backups in a separate account, immutable, in another region, are the only thing outside every one of those blast radii.

"The manager agrees to backups but wants the cheapest option that still makes sense. What is it?"

Physical base backups from the replica, weekly, with continuous WAL or binlog archiving to object storage, retained for thirty days, encrypted, in a separate account with object lock.

The replica already exists, so the backup adds no load to the primary; object storage for a few terabytes costs tens of dollars a month; WAL archiving is a one-line archive_command or a binlog upload script. pgBackRest or XtraBackup automate the rest.

Add a monthly restore drill on a temporary instance that is deleted afterwards, which costs a few hours of compute.

That gives near-zero RPO for both hardware and human error at the price of a few hundred dollars a month and a day of setup, which is the number I would put next to the cost of losing one customer's data.

Q190. "How do you take a consistent backup of a database that is actively taking writes, without locking it?"

Reveal answer

Strong answer A naive file copy of a running database is torn — different files captured at different moments, describing a state that never existed. Consistency comes from one of two mechanisms, neither of which locks out writers.

Physical backups pair the copy with the journal: pg_basebackup copies data files while recording the WAL generated during the copy, and restoring replays that WAL to roll the files forward into one consistent moment.

XtraBackup does the same with InnoDB's redo log — copying files and the log of changes made during the copy, then applying it. A filesystem or volume snapshot works the same way conceptually: crash-consistent, made whole by log replay at startup.

Logical backups instead use MVCC: pg_dump runs inside one long repeatable snapshot, so every table it exports reflects the same instant; mysqldump --single-transaction does the identical trick for InnoDB tables — no table locks needed.

The honest caveat on the logical path: that long snapshot pins old row versions for the duration of the dump, so a multi-hour dump on a busy primary is itself a bloat source — one more reason large systems dump from a replica.

Land it Consistency comes from either journal replay or a single MVCC snapshot — locking the database is the answer of last resort, and modern tooling never needs it.

Likely follow-ups
"What does pg_basebackup actually do at the start and end, and why does it need WAL?"

It calls pg_backup_start, which forces a checkpoint and records the WAL position where the backup began, then copies the data directory file by file over the replication connection while the database keeps writing, so the files are individually inconsistent, and at the end calls pg_backup_stop, which records the end position and writes a backup label.

On restore, Postgres reads the label, knows it is starting from a torn copy, and replays WAL from the start position through at least the end position, which repairs every page to the state it had at the end of the copy.

Without the WAL spanning the copy, the files are unusable. The --wal-method=stream option streams that WAL alongside the copy so the backup is self-contained; with an archive, the archived WAL serves the same role.

"A volume snapshot of a running database. When is it safe and when is it a trap?"

It is safe when the snapshot is atomic across everything the database needs: data files, WAL, and, for MySQL, the redo log and binlog, all on the same volume or in a consistent multi-volume snapshot group; then it is crash-consistent, and starting from it is the same as recovering from a power loss, which both engines handle.

The trap is data and WAL on different volumes snapshotted at different instants: the WAL may reference pages the data snapshot never saw or vice versa, and recovery either fails or silently produces a wrong state.

Another trap is file-system caching: the snapshot captures what is on disk, and with Postgres relying on the OS cache the last few seconds may be missing, which is fine only because WAL was fsynced.

I test every snapshot mechanism by restoring and checking, never by assuming.

"Why does mysqldump --single-transaction not work for MyISAM tables, and are there other gotchas?"

--single-transaction relies on InnoDB's MVCC snapshot: it starts a transaction with a consistent snapshot and reads every table at that point.

MyISAM has no MVCC, so its tables are read live and can change during the dump, and the only way to make them consistent is a global read lock, which blocks writes. Modern schemas are all InnoDB, but system tables and forgotten legacy tables can bite.

Other gotchas: DDL during the dump breaks the snapshot for the affected table, because ALTER TABLE takes a metadata lock that conflicts with the dump's open transaction, so the dump can stall or produce an inconsistent table; the snapshot pins undo history for the whole dump; and mysqldump is single-threaded, so mydumper or MySQL Shell's util.dumpInstance with parallel threads are the practical tools for large databases.

Q191. "Beyond taking backups: what does a grown-up policy for retention, encryption, and storage location look like?"

Reveal answer

Strong answer The classic frame is 3-2-1: three copies of the data, on two different kinds of storage, one of them offsite.

Retention is tiered, not flat — recent dailies for operational mistakes, weeklies and monthlies reaching back far enough to cover slowly-discovered corruption, and whatever the compliance regime requires beyond that; the key question is "how late could we plausibly notice a problem?", because retention shorter than the noticing window is decorative.

Encryption applies in transit and at rest, with the keys stored separately from the backups — encrypted backups whose key lives on the database server die with the server.

Offsite means a different failure domain in the full sense: another region, and critically another account or credential boundary, ideally with object-lock immutability, so the ransomware or the fat-fingered script that can destroy production cannot also destroy the backups.

That last property — production credentials cannot delete backups — is the one I verify personally, because it is the difference between an incident and an extinction event.

Land it The test of the whole policy is one question: can any single credential, machine, or mistake destroy both the database and its backups — and the answer must be no.

Likely follow-ups
"How do you make sure production credentials cannot delete the backups? Be specific."

The backups live in a bucket in a separate cloud account owned by a security or platform team, and the production account has a role that can only write new objects and list, not delete or overwrite; the bucket has object lock in compliance mode with a retention period, so even the owning account cannot delete an object before it expires.

Versioning is on so an overwritten object keeps its previous version. The backup tool's credentials in production are scoped to that write-only role. Deletions happen only through the lifecycle policy that expires objects after the retention period.

I verify it by trying: from a production host, attempt to delete a backup object and confirm the access-denied error, and I put that test in the quarterly drill so a permission change gets caught.

"How do you manage the encryption keys so a backup is restorable in five years but not readable by an attacker?"

Backups are encrypted with a data key that is itself encrypted by a key in a managed key service such as AWS KMS or HashiCorp Vault, in the backup account, not the production account.

Key rotation creates new versions without invalidating old ciphertext, so a five-year-old backup still decrypts with its key version as long as the key is never deleted; the key deletion policy is the one setting that could make every backup worthless, so it has a waiting period and a separate approval.

Access to decrypt is granted to a restore role that a human assumes with multi-factor authentication and that logs every use. The restore drill exercises the decrypt path from a clean machine, which is the only way to know the key access actually works.

"Regulation says keep financial records seven years. Does that mean seven years of database backups?"

Usually not, and treating it that way is expensive and fragile, because a seven-year-old physical backup requires a seven-year-old database version to restore.

The requirement is about the records, so the better design is to export the required data in an open, self-describing format, such as CSV or Parquet with a schema, to immutable archival storage on a schedule, and to keep database backups only as long as operational recovery needs, typically thirty to ninety days.

The archive is readable by any tool in seven years, is cheap in cold storage, and can be searched without restoring a database. Legal and compliance sign off on exactly which tables and columns the archive contains, and that document is part of the retention policy.

Q192 · Scenario. "Someone accidentally ran DROP TABLE on a production table. You discover the only backups are nightly logical dumps at 02:00, and it is now 16:00. Give me the honest damage assessment and how you handle the next two hours."

Reveal answer

The real test Honesty under bad constraints — no heroics, clear comms, and squeezing every recoverable source.

Strong answer The honest assessment first: with only a 02:00 dump, the table as of 02:00 is recoverable, and the fourteen hours since are lost from backups — that is the RPO we chose by having nightly dumps, now realized. My next two hours:

  1. Contain: make sure the application fails gracefully (or is partially disabled) so the missing table does not cascade into corrupt writes elsewhere.
  2. Restore the known good part immediately: extract the table from the 02:00 dump into a side schema, verify it, then load it back. The service is degraded-but-running with data as of 02:00.
  3. Challenge the "only dumps" assumption before accepting fourteen hours of loss: are binlogs or WAL still on disk or archived even though nobody set up formal PITR? MySQL binlogs often survive with days of retention — replaying 02:00 to 15:59 for that table can recover almost everything. Any replica with delayed apply, any snapshot, any recently stopped standby is also worth checking.
  4. Reconstruct the remainder from secondary sources: application event logs, message queues, upstream systems, even caches — often much of the lost window can be rebuilt.
  5. Communicate precisely and early: what is restored, what window is at risk, next update time. No optimism, no vagueness.

Afterwards: log archiving for real PITR, restore drills, and revoking casual DROP rights in production — this incident was priced years earlier when nightly-dumps-only was accepted.

Land it State the realized RPO plainly, restore what you have, then attack the loss window from binlogs and secondary sources — and never let the postmortem forget that the fourteen-hour gap was a choice, not bad luck.

Likely follow-ups
"The binlogs are there and cover 02:00 to now. Walk me through replaying just that table."

First I restore the table from the 02:00 dump into the production database, so its state matches the binlog's starting point.

Then I need the binlog position corresponding to 02:00, which the dump file header records when the dump was taken with --source-data, or which I find by timestamp. I run mysqlbinlog --start-position=...

--stop-datetime="16:00 minus the DROP" --database=shop binlog files, filtered to the one table, which mysqlbinlog cannot do natively, so I use --database plus a filter script, or replay everything into a scratch database and copy the table out.

The DROP TABLE event itself must be excluded, which the stop position handles. Row-based events for a table that now has the same schema apply cleanly. Then I compare counts against application logs and reconnect the application.

"On Postgres with no WAL archiving, are there any other recovery avenues for a dropped table?"

A few slim ones. If a standby exists with a replay delay or if replication was broken at the time, the table may still exist there.

If the pg_wal directory on the primary still contains the segments since 02:00, which depends on max_wal_size and checkpoint frequency and is unlikely over fourteen hours, a base backup from last night plus those segments would allow PITR, so the first action is to copy pg_wal to safe storage before it is recycled.

Cloud volume snapshots taken by infrastructure teams for other reasons sometimes exist.

And a dropped table's files are unlinked at the next checkpoint, so on a filesystem that supports it, an immediate volume snapshot and file recovery tools have occasionally worked for experts, but that is a last resort with low odds.

"What do you say to leadership in the first fifteen minutes?"

Three sentences with numbers. What is confirmed: the orders table was dropped at 15:58; the service is degraded in these specific ways. What we can recover and by when: the table as of 02:00 within one hour from the nightly dump.

What is at risk: fourteen hours of changes, which we are attempting to recover from binlogs and application logs, with a confidence update at 17:00. Then the next update time.

I avoid guessing at the final loss, because an optimistic guess that is later revised destroys trust, and I avoid blame.

After the incident, the message is that this outcome was determined by a backup design decision made years ago and that the fix is a specific, priced change to log archiving and restore drills.

"How do you prevent an accidental DROP TABLE structurally?"

Remove the ability from the accounts that are used routinely.

Application roles get DML on their tables and no DDL. Human accounts on production are read-only by default, with a separate break-glass role that has DDL rights, requires a second approver to assume, and is logged and time-limited.

Schema changes flow only through the migration pipeline, which reviews and rehearses them.

In Postgres, an event trigger on ddl_command_start can block DROP TABLE unless a session variable is set, which turns an accident into an error message; MySQL has no event triggers, but the permissions model does the same job.

And the last layer is recoverability: continuous log archiving and a delayed replica, so that when the structural guards fail, the loss is minutes, not fourteen hours.

Drill · Observability & guardrails

This group tests whether you build the systems that make 3am calls rare: the right dashboard, the right alerts, and the timeouts and permissions that turn would-be incidents into log lines.

Q193. "You inherit a production database with no monitoring. What goes on your dashboard, and why does each panel earn its place?"

Reveal answer

Strong answer Eight panels, each answering a question I will actually ask during an incident or a capacity review:

  • Connections against the maximum — saturation with a hard wall; the metric that turns into refused logins.
  • QPS and TPS (queries and transactions per second) — the load baseline; every other panel is meaningless without knowing whether traffic changed.
  • p99 statement latency — the time the slowest one percent of statements take; averages hide the pain users actually feel.
  • Replication lag — read staleness for replicas and the data-loss window if I must fail over right now.
  • Lock waits and blocked sessions — contention shows here minutes before it shows as latency.
  • Dead tuples and vacuum/wraparound age (history list length on MySQL) — the maintenance-debt gauges; both fail slowly, then suddenly.
  • Disk headroom with growth rate — as time-until-full, not percent; the only panel with a truly fatal endpoint.
  • Buffer or cache hit ratio — a trend line telling me when the working set is outgrowing memory, months before it becomes an emergency.

The pattern: half are leading indicators (lag, locks, vacuum age, disk trend) chosen so the dashboard warns before users do.

Land it Every panel must answer a question you will actually ask — a dashboard of leading indicators pages you before the users do, which is the whole point.

Likely follow-ups
"Where do those metrics come from, and what would you use to collect them?"

From the database's own statistics views, scraped by an exporter.

For Postgres, postgres_exporter reads pg_stat_database for transactions and hit ratio, pg_stat_activity for connection states and waits, pg_stat_replication for lag, pg_stat_user_tables for dead tuples and vacuum times, pg_database for wraparound age, and pg_stat_statements for per-query latency, and Prometheus stores them with Grafana on top.

For MySQL, mysqld_exporter reads SHOW GLOBAL STATUS, information_schema, and performance_schema, with the same stack; Percona's PMM packages all of it with prebuilt dashboards. Host metrics come from node_exporter.

On managed services the provider's monitoring gives host and some engine metrics, but the query-level view still needs pg_stat_statements or performance_schema scraped by your own exporter.

"Why p99 rather than average latency, and how do you actually get p99 from the database?"

Average latency hides tail pain: a thousand queries at one millisecond and ten at two seconds average to 21 milliseconds, which looks fine while one percent of users wait two seconds.

p99 says what the slowest one in a hundred experienced, which is what support tickets describe.

Getting it from the database is the awkward part: pg_stat_statements provides mean, min, max, and standard deviation per statement, not percentiles, so true p99 comes from the application's driver-level timing histograms, or from sampling with auto_explain or log_min_duration_statement and computing percentiles from the log.

MySQL's performance_schema has events_statements_histogram_global, which does provide latency buckets directly. For the dashboard I use the application's histogram of query time labelled by statement, which is the customer's view anyway.

"You have one panel's worth of space on the main service dashboard. Which database metric goes there?"

Connection pool wait time from the application side, for example HikariCP's pending threads and acquire time.

It is the single metric that reflects every database problem as the application experiences it: a slow query, a lock chain, a connection storm, replication routing to a dead replica, or a saturated primary all show up as threads waiting for a connection.

It is also the metric that separates database trouble from application trouble, because if pool wait is zero and the service is slow, the database is not the cause.

The full database dashboard is one click away; the service dashboard needs the one line that says "is the database hurting us right now."

Q194. "Which database conditions should page a human at night, and which should just open a ticket? Give thresholds."

Reveal answer

Strong answer The dividing rule: page only when a human must act now to prevent user harm; everything trending-but-not-urgent becomes a ticket.

Pages: the database unreachable, obviously; disk above roughly 85 to 90 percent — or better, less than a few hours of headroom at the current write rate; connections above 90 percent of max_connections; replication lag beyond what the product tolerates for stale reads — the SLO, the service-level objective we promised; transaction-ID wraparound age past a comfortable fraction of the shutdown horizon, say one billion, because past a point the database will protect itself by refusing writes; and a stopped WAL archiver or backup failure, since it silently converts the next incident into data loss.

Tickets: dead-tuple ratio creeping up, cache hit ratio drifting down, slow-query count growing week over week, an index bloat estimate crossing a line.

Two disciplines make the pages trustworthy: every page links to a runbook with the first three commands to run, and any page that fires without requiring action gets tuned or demoted — an on-call that learns to ignore pages has no pages at all.

Land it Page on "act now or users bleed", ticket on trends — and treat a page that needed no action as a bug in the alert, not a cost of doing business.

Likely follow-ups
"How do you set the replication lag threshold when different features tolerate different staleness?"

The page threshold is set by the most sensitive feature that reads from the replica, because that is where harm begins; if account balances are read from replicas with a five-second tolerance, then the page is at five seconds sustained for a minute, and everything else is covered by it.

If that makes the page too noisy, the fix is not to raise the threshold but to move the sensitive reads to the primary or behind read-your-writes routing, so the replica's tolerance becomes the next most sensitive feature's.

I document the mapping of features to tolerances so the threshold has a reason attached. A separate, higher threshold catches the failover risk: lag above, say, five minutes on the failover candidate pages regardless of features, because it means a promotion would lose that much.

"What does the runbook attached to the 'connections above 90 percent' page contain?"

The first three commands: the query to group sessions by user, application_name, and client address; the query to count idle-in-transaction sessions; and the pooler's status command if one exists.

Then the decision tree: if one source dominates, terminate its idle sessions and cap its role; if all sources grew together, check for a reconnect storm after a recent blip and for a deploy that changed pool sizes; if the sessions are mostly active and waiting on locks, follow the lock-chain runbook instead.

Then the safe mitigations with exact commands, the escalation contact, and the note on how to get in via reserved connections when the limit is already hit. And a link to the last three incidents of this type, because the pattern usually repeats.

"How do you keep alerts from rotting over a year?"

Three practices. Every page that fires gets a one-line disposition in the incident channel: acted, tuned, or demoted, and a monthly review counts them per alert; any alert with more than a couple of no-action pages in a month is changed or deleted.

Thresholds are expressed relative to baselines where possible, such as time to disk full, rather than fixed percentages that stop making sense as the system grows.

And alert definitions live in version control next to the dashboards, reviewed like code, so a threshold change has a reason in its commit message.

The measure of health is simple: on-call should be able to say that every page in the last quarter required a human action, and if they cannot, the alert set is too big.

Q195. "How do you use pg_stat_statements or performance_schema as an always-on profiler? Describe your actual ritual."

Reveal answer

Strong answer pg_stat_statements (and MySQL's performance_schema, most readably through the sys schema views) aggregates every statement the server runs, normalized so literals collapse into one entry, with calls, total and mean time, and rows. It is profiling you never have to remember to turn on.

My ritual: a recurring review — weekly on busy systems — sorted by total execution time, not mean.

Mean time finds the dramatic slow query; total time finds the five-millisecond query called two hundred times per second that quietly owns 30 percent of the database, which per-request tracing never surfaces. For each of the top ten I ask: expected? cacheable? missing an index?

callable less often? The other half of the ritual is reset cadence: these counters accumulate forever, so after a major release I snapshot and reset (SELECT pg_stat_statements_reset();) so the numbers describe the code that is running now, not a blend with last quarter's.

Between resets, dashboards can graph deltas instead. During incidents the same view gives instant before-and-after comparisons: which statement's time exploded at 14:32.

Land it Sort by total time, not mean — the query that hurts you is usually cheap, frequent, and invisible to everything except the aggregate view.

Likely follow-ups
"What does pg_stat_statements cost, and what are its configuration traps?"

The overhead is small, typically a few percent of CPU at most, because it hashes the query's parse tree and updates counters in shared memory. The traps are configuration.

pg_stat_statements.max, default 5000, limits distinct entries; on a system with many query shapes it fills and the least-used entries are evicted, so a long-tail query disappears from the view, and the dealloc counter in pg_stat_statements_info tells you how often that happens.

pg_stat_statements.track should be top, not all, or nested function statements inflate counts. Queries with IN lists of varying length produce separate entries unless query ID normalization handles them, which Postgres 16 improved.

Applications that build SQL with literals instead of parameters produce one entry per literal and fill the table instantly; that itself is a finding worth fixing.

"Show me the exact query you run in the weekly review."

SELECT queryid, calls, round(total_exec_time::numeric, 0) AS total_ms, round(mean_exec_time::numeric, 2) AS mean_ms, rows, round(100 * total_exec_time / sum(total_exec_time) OVER (), 1) AS pct, left(query, 80) FROM pg_stat_statements ORDER BY total_exec_time DESC LIMIT 20.

The pct column is what makes it useful: it shows the share of all database time each statement owns, and the top five usually own half.

I also run the same ordered by calls, to find chatty statements that a cache would remove, and by shared_blks_read, to find statements causing disk reads.

In MySQL, SELECT * FROM sys.statement_analysis ORDER BY total_latency DESC LIMIT 20 gives the same view with latency already formatted, and sys.statements_with_full_table_scans is the shortcut to missing indexes.

"How do you connect a statement in pg_stat_statements back to the code that issued it?"

Two techniques.

The application adds a comment to every SQL statement naming the service and the call site, such as /* svc=checkout, op=CreateOrder */, which libraries like sqlcommenter or a Hibernate statement inspector do automatically; pg_stat_statements strips comments from the normalized text by default, so this works best with log-based sampling or with the comment placed where the tool keeps it, and the MySQL performance_schema keeps the comment in the digest text.

The other is application_name per service plus per-service database users, so the pg_stat_statements userid column and the logs attribute statements to a service, and the service's own tracing shows which endpoint runs which query.

With both in place, the weekly review's top statement maps to a file and a function in under a minute.

Q196 · Scenario. "Last month, an ad-hoc query ran for 40 minutes on the primary, starved IO, and caused a customer-facing incident. What single guardrail would have made it a non-event, and how exactly do you deploy it?"

Reveal answer

Strong answer A statement timeout. With a 30-second cap, that query dies at second 30 with an error — a log line and an annoyed analyst instead of a 40-minute incident. Deploying it properly:

  1. Set it per database user, not globally: ALTER ROLE app_user SET statement_timeout = '30s' for the application role, something looser like 10 or 15 minutes for the analytics role, and no default cap for the migration and maintenance role — because a global value either strangles legitimate long work (vacuums, index builds, backfills) or is too loose to protect anything. Role-level settings encode the right budget per workload.
  2. MySQL's equivalent is max_execution_time, settable globally, per session, or per statement — with the honest caveat that it applies to SELECTs, so runaway writes there need monitoring plus kill policies instead.
  3. Pair it with the sibling guardrails from the same family: idle_in_transaction_session_timeout for abandoned transactions and lock_timeout for DDL, so all three classes of "held too long" are capped.
  4. Socialize it: the timeout will occasionally kill a legitimate query, and that is the system working — the response is to run that query with an explicit longer budget in the right role, not to raise the default.

The principle: timeouts cap tail risk. Every unbounded query is a small probability of an unbounded incident, and the timeout converts that tail into a bounded, visible error.

Land it Set statement_timeout at the role level as a default guardrail — a query that fails at 30 seconds is a log line, while the same query without a cap is next month's incident.

Likely follow-ups
"A batch job legitimately runs for two hours. How does it coexist with the timeout?"

It runs under its own role with its own budget: ALTER ROLE batch_jobs SET statement_timeout = '3h', or the job sets it per session at the start with SET statement_timeout.

The point of role-level settings is exactly that different workloads get different limits without any of them being unbounded.

But a two-hour statement is also a design smell: a single statement running that long holds its snapshot, pins cleanup, and cannot be paused, so I would ask the job's owner whether it can be batched into short statements, which usually it can.

If it genuinely must be one statement, for example a large aggregate, it belongs on the reporting replica, where a three-hour timeout harms nobody.

"MySQL's max_execution_time only covers SELECT. What do you do about a runaway UPDATE?"

Three layers. A monitoring rule that alerts when any transaction in information_schema.innodb_trx has been running longer than a threshold, with the query text.

An automatic killer, pt-kill, configured to kill statements from application users exceeding a time limit, excluding the migration and batch users, and to log every kill.

And, structurally, the guard that prevents long UPDATEs from being written: batched updates as the team standard, sql_safe_updates for interactive accounts, and code review flagging unbounded writes.

innodb_lock_wait_timeout also bounds how long a writer waits for a lock, which limits the damage a stuck writer does to others even if it runs long itself. As of Aug 2026 MySQL still has no statement-level timeout for DML, so those layers are the answer.

"The timeout is in place, but a query that takes 29 seconds still hurts. Is the guardrail enough?"

No; the timeout caps the worst case, it does not make the normal case good.

A query that takes 29 seconds on the primary, many times a day, is a performance bug that the weekly pg_stat_statements review should catch and an index or a rewrite should fix.

The timeout for the application role should also be much lower than 30 seconds for the web request path, perhaps five seconds, because no user is waiting longer than that anyway; the 30-second figure was a starting point.

The other protection for a 29-second query is where it runs: analysts on the replica, not the primary. Timeouts, routing, and review are three separate controls, and the incident becomes a non-event only when all three are in place.

Q197. "What does a healthy query-review culture look like for new SQL going to production?"

Reveal answer

Strong answer SQL is code and gets reviewed like code — but with one addition: for hot-path queries, the review includes evidence, not opinion.

Concretely: any new query on a high-traffic path arrives in the pull request with its EXPLAIN (ideally EXPLAIN ANALYZE) output from a production-sized dataset, because a plan against a hundred staging rows proves nothing.

Reviewers look for a short list: sequential scans on large tables, estimated rows wildly off actual, sorts that should be satisfied by an index, and row-by-row patterns like N+1 access hiding behind an ORM (object-relational mapper).

Migrations get the same treatment with linting — tools like squawk for Postgres flag dangerous DDL patterns (a blocking type change, a non-concurrent index build) automatically in CI, so the reviewer's attention goes to judgment calls.

Two cultural details make it stick: the checklist is written down so review quality does not depend on who is available, and the rule is scoped honestly — cold admin queries do not need the ceremony; the checkout path does.

The payoff compounds: every prevented bad query is an incident, a page, and a postmortem that never happened.

Land it Review hot-path SQL with a plan from prod-sized data attached — opinions about query speed are worthless, and the EXPLAIN is cheap to demand.

Likely follow-ups
"Most of our SQL is generated by the ORM. How do you review something nobody wrote?"

By reviewing what it produces, not what was typed. In development and CI, SQL logging is on, and a test fixture captures the statements a code path issues; a test asserts the count, so an endpoint that suddenly issues 101 queries fails as an N+1 regression.

For hot paths, the pull request includes the generated SQL and its EXPLAIN from a production-sized copy, obtained by running the endpoint against it. Hibernate's statistics and tools like the JPA query counter make the numbers cheap to get.

Reviewers then look at the same short list: sequential scans, bad estimates, missing indexes, and query counts. The ORM is not the enemy; the lack of visibility into what it does is, and the review process exists to create that visibility.

"What does the written checklist actually say?"

For a query on a hot path: the EXPLAIN ANALYZE output attached, from a dataset of production scale; no sequential scan on a table above a stated size unless justified; estimated rows within an order of magnitude of actual; no sort that an existing index could satisfy; all filters sargable, meaning no function wrapped around an indexed column; parameters bound, not concatenated; row limits present on any list query; and the number of round trips per request stated. For a migration: the lock class of each statement, the expected duration from a rehearsal, CONCURRENTLY or NOT VALID used where applicable, a lock timeout set, and destructive steps separated. The checklist is a page, lives in the repository, and is linked from the pull request template.

"How do you avoid the review becoming a bottleneck with one database expert?"

By making the expert's knowledge into tooling and teaching. Automated linting in CI, Squawk for Postgres migrations and an EXPLAIN-based check that fails on sequential scans over large tables, handles the mechanical part with no human.

The expert then reviews only what the tooling flags and trains two or three other engineers by pairing on reviews for a quarter, after which those engineers review most changes. A weekly thirty-minute session walking through the top pg_stat_statements entries doubles as training.

And the scope rule keeps the load bounded: only hot-path queries and migrations need the full review. The measure of success is that the expert is no longer on the critical path for a routine pull request within six months.

Q198 · Scenario. "During an incident you open the processlist and see 300 connections, all logged in as the same user, 'app'. Why is this itself a finding for the postmortem, and what is the fix?"

Reveal answer

Strong answer Because at the worst possible moment — mid-incident — the database cannot tell me which service is flooding it. Every session says "app", so I am reduced to guessing from query text and client addresses while the clock runs. The fix is per-service database users, which pays off four ways:

  1. Attribution: pg_stat_activity and the processlist show usename per session, so "checkout is holding 200 connections" becomes a fact I can read, not infer. Setting application_name in the JDBC connection string (or MySQL connection attributes) adds even finer labeling cheaply — worth doing regardless.
  2. Least privilege: the reporting user gets SELECT on its schemas and nothing else; the checkout user cannot TRUNCATE the ledger; nobody's leaked credential can DROP a table it never needed.
  3. Per-role guardrails: connection caps (ALTER ROLE svc_reports CONNECTION LIMIT 20), statement timeouts, and work_mem budgets attach to roles — one misbehaving service hits its ceiling instead of the shared one.
  4. Clean revocation: rotating or cutting off one compromised or runaway service does not require touching every other service's credentials.

The migration is mundane — create roles, grant minimal rights, roll credentials service by service — and it converts future incidents from detective work into a GROUP BY.

Land it A shared database user means zero attribution and shared blast radius — per-service users turn "who is doing this?" into a query instead of an investigation.

Likely follow-ups
"How do you roll out per-service users without an outage?"

Create the new role with the minimal grants, and grant it on future tables too with ALTER DEFAULT PRIVILEGES in Postgres, or the schema-level grants in MySQL. Test it in staging by running the service's integration tests under the new user, because missing grants show up as permission errors immediately.

Then deploy the service with the new credentials while the old shared user still exists, watching for permission errors in the logs. Do one service at a time.

When every service has moved, revoke the shared user's write rights, wait a week to catch anything that was still using it, then drop it. Connection limits per role are set after migration, from observed counts.

Secrets go through the vault so the rotation is a configuration change, not a code change.

"What is the connection-count cost of per-service users and per-role limits?"

The users themselves cost nothing.

The limits have to add up: if the database can serve 300 connections and there are ten services, the per-role limits must sum to a number that still leaves reserved slots for operators and the pooler, and each service's limit must exceed its pool size times its instance count, or deployments that scale out will hit refused connections.

That arithmetic is why a pooler usually accompanies this change: pgBouncer can have per-user or per-database pool sizes, so the cap is enforced in the pooler and the database sees a small fixed number.

I write the numbers in a table in the runbook: service, instances, pool size, role limit, so the next scale-up updates it rather than discovering the cap in production.

"Does application_name alone solve the attribution problem without new users?"

For attribution during an incident, largely yes: setting ApplicationName in the JDBC URL or connection attributes in MySQL, with the service name and even the pod name, makes the processlist readable immediately and costs one configuration line, so it is the first thing to do today.

What it does not give is enforcement: application_name can be set by any client to anything, so it cannot carry permissions, connection limits, or timeouts, and a compromised credential is still the shared one with full rights. Per-service users are what make the guardrails attach.

So the sequence is application_name this afternoon for visibility, per-service roles over the following weeks for control, and both together in the postmortem's action items.

Q199 · Scenario. "You put pgBouncer in transaction-pooling mode in front of Postgres, and your Java services start throwing 'prepared statement S_1 does not exist'. Explain the failure and your options."

Reveal answer

The real test Whether you understand what transaction pooling sacrifices: session state.

Strong answer In transaction pooling, a client owns a real server connection only for the duration of one transaction; the next transaction may be served by a completely different server connection.

That is the mode's superpower — thousands of client connections multiplexed over a few dozen server ones — and also the failure here.

Anything that lives in session state on a specific server connection silently stops being reliable: server-side prepared statements, SET parameters, temporary tables, advisory locks.

The Postgres JDBC driver (JDBC being Java's standard database access layer) prepares statements server-side after a statement has run five times — the prepareThreshold — and names them S_1, S_2, and so on.

The prepare happened on one server connection; the execute landed on another that has never heard of S_1. Options, in the order I would consider them:

  1. Upgrade pgBouncer: from version 1.21 it understands protocol-level prepared statements in transaction mode (max_prepared_statements) and tracks them across server connections — the clean modern fix.
  2. Disable server-side preparation in the driver: prepareThreshold=0 in the JDBC URL. Costs a little parse overhead per execution; entirely safe.
  3. Fall back to session pooling for the affected services — keeps all session semantics but gives up most of the multiplexing benefit, so it is the last resort.

ProxySQL plays the equivalent role for MySQL, with its own multiplexing caveats around session variables.

Land it Transaction pooling trades away session state for multiplexing — know which session features your stack secretly relies on before you flip the mode, because the driver's five-execution prepare threshold is exactly the kind of thing nobody remembers until 2am.

Likely follow-ups
"What else in a typical Java application breaks under transaction pooling, and how do you find it?"

Anything that assumes the same server connection across transactions.

SET statements outside a transaction, such as a session time zone or search_path set by the pool's connection init, are applied to whichever server connection happened to be assigned and then lost; the fix is to set them per transaction with SET LOCAL or in the role's defaults with ALTER ROLE. Advisory locks acquired in one transaction and released in another, used by some schedulers like ShedLock, break; session-level advisory locks must become transaction-level ones.

Temporary tables vanish between transactions. LISTEN/NOTIFY does not work, since the listener needs a persistent connection. Cursors WITH HOLD are lost.

I find them by grepping the code for SET, pg_advisory_lock, CREATE TEMP, and LISTEN, and by running the integration tests through pgBouncer in transaction mode in CI.

"How much does prepareThreshold=0 actually cost, and is there a middle ground?"

With prepareThreshold=0 the driver still uses the extended protocol with parameters, it just uses unnamed statements that are parsed and planned on every execution.

For simple indexed queries the parse and plan cost is around a hundred microseconds, which on a two-millisecond query is a few percent; for complex queries with many joins the planning can be several milliseconds, which is noticeable.

The middle ground is pgBouncer 1.21 or later with max_prepared_statements set to a few hundred, which tracks named statements per client and re-prepares them on each server connection as needed, so the driver keeps its prepared statements and pgBouncer keeps multiplexing.

Measuring is easy: compare mean_exec_time and mean_plan_time in pg_stat_statements with pg_stat_statements.track_planning on.

"pgBouncer is single-threaded. When does it become the bottleneck, and what then?"

One pgBouncer process handles tens of thousands of transactions per second on one core, since it only forwards bytes, but with TLS termination and very high query rates a single process saturates its core.

The signs are pgBouncer's own CPU at 100 percent and client wait time rising while the database is idle.

The remedies: run several pgBouncer processes on the same port using so_reuseport, which Linux load-balances between them; run one pgBouncer per application host as a sidecar, which also removes a network hop; or move to a multi-threaded pooler such as PgCat or Odyssey.

Each pgBouncer instance holds its own server pool, so the total server connections must be recomputed as instances multiply, which is the arithmetic that catches people out.

Q200. "How do you do capacity forecasting for a database — deciding when you need to act, before an alert forces you?"

Reveal answer

Strong answer I forecast on the handful of resources with walls: disk, connections, memory relative to working set, and replication or vacuum keeping pace with write rate. The method is deliberately simple — trend lines, not percentages.

Current disk usage is uninteresting; the slope is everything: at this month's growth rate, when does headroom hit zero?

Same for connections against max_connections as services scale out, working set against buffer memory (watching the hit-ratio drift), and write volume against what vacuum and replicas absorb at peak.

Each gets a "date we hit the wall" estimate, and — the part juniors miss — the act-by date sits weeks or months before the wall, because the remedies (bigger volumes, sharding, a pooler rollout, archiving old data) take weeks to execute safely.

I review the curves monthly, deliberately outside incident pressure, and any wall closer than two remedy-lead-times becomes a scheduled project now. The cultural point: capacity work triggered by an alert has already failed, because you are executing a weeks-long fix inside a days-long countdown.

Land it Forecast in dates, not percentages — and act two lead-times before the wall, because the alert version of this conversation happens with the countdown already running.

Likely follow-ups
"Show me the actual arithmetic for disk."

Take the database size from pg_database_size or the sum of data_length plus index_length weekly for the last three months.

Fit a line, or simply compute the average weekly growth from the first and last points: say 2.1 TB now, 1.5 TB three months ago, so 50 GB a week.

The volume is 3 TB, and I need 20 percent free for rewrites and temporary files, so usable headroom is 2.4 TB minus 2.1 TB, which is 300 GB, about six weeks.

Growing a cloud volume takes hours, but archiving or a table rewrite to reclaim space takes weeks to plan, so the act-by date is now.

I also check whether growth is accelerating by comparing the last month's slope to the quarter's, because a launch can double the rate and a linear forecast would be wrong.

"How do you forecast connections and working set, which are not simple lines?"

Connections scale with instance count, not time, so I forecast from the deployment plan: services times instances times pool size, against max_connections minus reserved slots, and the act-by trigger is any planned scale-out that pushes the sum above 80 percent, which is when the pooler rollout must be done.

Working set is forecast from the hit ratio trend at peak and from pg_buffercache's measure of hot data: if hot data grows 3 percent a month and is at 70 percent of memory, the crossover is about a year out, and the remedies, more RAM or archiving cold rows, take weeks.

Write rate against vacuum and replicas is forecast by watching the peak-hour lag and dead-tuple trend; when peaks start leaving debt that quiet hours no longer clear, that is the wall approaching.

"What would you do if the forecast says sharding is eighteen months away?"

Use the eighteen months. In the first quarter, verify the forecast is not driven by waste: archive cold data, fix the top queries, and check whether the bigger instance class buys another year, because those often push the wall out.

In parallel, do the cheap preparation: a shard key on every table, a single data-access layer, globally unique IDs, and analytics off the primary.

By month six, decide between hand-built sharding, a sharding layer such as Citus or Vitess, and a distributed SQL database, with a prototype of the top candidate against real traffic. Months nine to fifteen, build and migrate the first tenant cohort.

That leaves a quarter of slack, which every migration needs. The alternative, starting at month sixteen, is the panicked version of the same plan with no slack.

"Who reviews the capacity curves, and how do you make the review happen?"

The database owner and the on-call lead, monthly, in a thirty-minute meeting with a fixed agenda: one dashboard of the five walls with their time-to-wall numbers, the list of remedies in flight, and any forecast that moved by more than a month since last time.

It happens because it is on the calendar and produces a written note with dates that feeds the team's planning, so the project to add a pooler or archive a table appears in the roadmap next to features, with the wall date as its deadline.

When the meeting is skipped twice, the next incident is the reminder, so I treat the review as an on-call duty rather than an optional ritual. The output is small; the discipline of producing it is the point.

Quick reference — Transactions and ACID

ACID
Atomicity all-or-nothing · Consistency constraints hold · Isolation concurrent transactions do not see each other's mess · Durability committed means survives a crash.
write-ahead log
The database writes what it intends to do before doing it. Redo replays committed work after a crash; undo rolls back what never committed.
You are always in a transaction
Autocommit just means one statement per transaction. There is no “outside”.
The two opposite sins
A transaction held open across a network call holds locks for the whole round trip. A million single-row commits pays the log flush a million times. Batch, but bound the batch.

Quick reference — Isolation levels

The anomalies
Dirty read (uncommitted data) · non-repeatable read (same row, different value) · phantom (same query, new rows) · lost update (two read-modify-writes, one wins silently).
MySQL default
REPEATABLE READ. Snapshot for plain SELECTs, but current reads for SELECT ... FOR UPDATE and writes — which is why the two can disagree inside one transaction.
PostgreSQL default
READ COMMITTED. Each statement sees a fresh snapshot, so two statements in one transaction can see different data.
gap and next-key locks
How InnoDB blocks phantoms: it locks the gaps between index entries, not just the rows. This is why an unindexed WHERE can lock far more than you expect.
Optimistic vs pessimistic
Optimistic: read, then check nothing changed at write (a version column). Pessimistic: FOR UPDATE up front. Choose by how often you actually collide.

Quick reference — Indexes and query plans

B+tree
Sorted keys in pages, with all the data in the leaves. High fanout means very few page reads to reach any row.
clustered index (InnoDB)
The table is the primary-key B+tree. A secondary index stores the primary key, so it needs a double lookup to fetch other columns.
PostgreSQL heap
No clustered index. Rows live in a heap and every index points at them, which is why index-only scans depend on the visibility map.
leftmost-prefix rule
An index on (a, b, c) serves a; a+b; a+b+c. It does not serve b alone. This one rule explains most “why is my index not used” questions.
covering index
Contains every column the query needs, so the table is never touched. Shows as index-only scan.
Index killers
A function or a cast on the indexed column, a leading wildcard LIKE '%x', and low selectivity. If the planner thinks it will read most of the table, a scan is genuinely cheaper.

Quick reference — Locks, pools, replicas

Lock kinds
Shared (read) versus exclusive (write); row versus table. A lock wait is one transaction waiting; a deadlock is two waiting on each other.
Deadlock prevention
Consistent lock ordering. If every transaction touches rows in the same order, a cycle cannot form.
Pool sizing
Connections are not free — each is memory and a scheduling unit in the database. 600 connections to one Postgres is a self-inflicted outage; a small pool with a queue is faster.
replication lag
Asynchronous replicas are behind by some amount, always. Reading your own write from a replica returns yesterday.
read-your-writes
The fix: route a user to the primary for a short window after their write, or wait on a log position.

10 · RecapWhat You Can Do Now

  • You can explain ACID with a crash story, not four adjectives — and say what the write-ahead log buys
  • You can walk the four isolation levels anomaly by anomaly, and explain what repeatable read really repeats in InnoDB versus PostgreSQL
  • You can choose between optimistic and pessimistic locking for a given write pattern, and defend it
  • You can design a composite index for a real query, predict when the planner will ignore it, and prove the fix with EXPLAIN
  • You can read a deadlock log, find the head of a lock-wait chain, and kill the right session
  • You can do the fleet math on connection pools before it takes the site down
  • You can reason about replication lag, read-your-writes, and what failover really costs
  • You answer "the database is slow" with an ordered checklist instead of a guess
🧠 Flex your memory

Close the page and write down, from memory: the four isolation levels with the anomaly each one forbids, and the two-step walkthrough of how MVCC lets a reader and a writer touch the same row without blocking. Then reach back to Chapter E3's tuning section: which three root causes can all present as "connection pool exhausted" — and which pool-side metric separates them?