PostgreSQL – 20 Production Scenarios (with Answers)

Senior backend interviews use database incidents to test more than syntax. They reveal whether you can distinguish planner choices from schema problems, lock waits from deadlocks, and correctness guarantees from performance symptoms.

This article frames practical reasoning across PostgreSQL indexes, transactions, replication, and migrations. It focuses on evidence, concurrency trade-offs, operational safeguards, and the application behavior needed to keep database changes safe under production load.

All 20 answers below are free. Want the full set, every answer with a worked example?

Cloud, DevOps & System Design for Java Backend (200 Qs: Docker, Kubernetes, AWS, CI/CD, Terraform, databases, system design)

Get the guide

Section 1: Indexes Under Load

1. A query became slow after a release. How do you prove a stale plan is the cause?

Prove a stale plan by comparing the plan chosen before and after the release with the plan actually executed, while separating bad estimates from a bad cached plan. A replan that immediately restores performance is strong evidence, but it should be confirmed against representative parameter values rather than treated as proof by itself.

A cached plan can become inappropriate when:

  • Table data distribution changed, but optimizer statistics were not refreshed.
  • A prepared statement was planned using an unrepresentative parameter, especially with parameter-sensitive predicates.
  • A release changed SQL text, bind types, schema objects, or session settings.
  • The plan was valid but estimates became wrong because of correlation or skew that ordinary column statistics do not capture.

Diagnose it in production without guessing:

  1. Capture the exact SQL, bind values, database session settings, plan hash or shape, execution time, row counts, and buffer or I/O counts. pg_stat_statements and EXPLAIN (ANALYZE, BUFFERS) are useful in PostgreSQL; use the equivalent plan cache and actual-plan tooling for another database.
  2. Compare estimated rows with actual rows at each important operator. A large estimate error indicates statistics or cardinality problems; the same bad plan across values suggests a plan-choice problem.
  3. Run a controlled replan, such as EXPLAIN (ANALYZE, BUFFERS) with a literal or a forced custom plan where supported. If the new plan is consistently faster for the affected values, investigate plan caching.
  4. Refresh statistics and invalidate or evict the affected prepared plan, then retest. If statistics are current, consider better statistics, a query rewrite, or database-specific plan management.
ANALYZE orders;
EXPLAIN (ANALYZE, BUFFERS)
SELECT * FROM orders WHERE customer_id = 42;

Do not “fix” this by disabling plan caching globally or forcing an index without measuring the cost for other parameter values. Replanning consumes CPU, while a forced plan can regress common cases.

Interview takeaway: I would prove a stale plan by showing that a controlled replan chooses a materially better plan for the same bind values, then fix the underlying statistics or parameter-sensitivity issue.

2. Why can a composite index miss a filter that appears in its indexed columns?

A normal composite B-tree index is ordered lexicographically, so its leading columns determine where the engine can seek. An index on (tenant_id, status, created_at) is excellent when the leading key is constrained, but a predicate on status alone usually cannot jump directly into the relevant portions of that index.

For an index on (a, b, c):

  • a = ? AND b = ? can seek to a narrow range, and c can further narrow or order that range.
  • a = ? AND c = ? can use a for the seek; c may be a residual filter or help through an engine-specific optimization.
  • b = ? or c = ? alone generally requires scanning many index entries because all values of the preceding column come first.
  • A range on a leading column often limits useful use of later columns for seeking, although later columns can still help with filtering or ordering depending on the optimizer.

Diagnose and correct it as follows:

  1. Inspect the actual plan, not just whether the index appears in the schema. Look for an index scan with many rows removed by filter, or a full scan of the index.
  2. Check predicate shape and types. Functions, casts, expressions, and an OR can prevent a seek even when the column is present.
  3. Design the key order from real access patterns: equality and tenant partitioning often come first, followed by the most useful range or ordering column. Add a separate (status, ...) index only if that workload justifies it.
  4. Remember that some optimizers support skip-scan-like strategies, but they have version- and cost-dependent behavior and are not a substitute for the correct leading key.
CREATE INDEX orders_tenant_status_created
    ON orders (tenant_id, status, created_at);

-- A different access path may need:
CREATE INDEX orders_status_created
    ON orders (status, created_at);

Every additional index consumes storage and makes inserts, deletes, and relevant updates more expensive, so validate the design with production-shaped plans and write load.

Interview takeaway: The key point is that composite indexes are ordered structures, not unordered sets of columns: the leading-key pattern must match the query’s access path.

3. How can a covering index reduce reads while increasing write latency?

A covering index contains every column needed to answer a query, allowing an index-only or covering scan that avoids fetching table rows. It reduces read I/O and random heap lookups, but it enlarges the index and makes every affected insert, delete, and update maintain more index data.

The read benefit comes from:

  • The engine can return projected columns directly from the index instead of visiting the base table.
  • A smaller index is often cheaper to scan than a wide table, especially for selective queries.
  • In PostgreSQL, an index-only scan still needs visibility information; pages not marked all-visible can require heap checks, so “covering” does not guarantee zero table reads.
  • Included columns are payload, not normally additional search keys. PostgreSQL supports INCLUDE; other databases use features such as included columns or covering secondary indexes.
CREATE INDEX orders_customer_status_i
    ON orders (customer_id, status)
    INCLUDE (created_at, total);

SELECT status, created_at, total
FROM orders
WHERE customer_id = 42;

Evaluate the trade-off instead of adding columns mechanically:

  1. Measure the current plan with actual row counts and buffer or logical-read metrics. Confirm that table lookups are the dominant cost.
  2. Add only columns needed by a frequent, performance-sensitive query, and check maximum index-row size and storage growth.
  3. Measure insert, delete, and update latency. An update to an included column may require index maintenance even when the search keys do not change; MVCC engines may create new index entries or versions as part of normal updates.
  4. Recheck index-only behavior after deployment. In PostgreSQL, vacuum and visibility-map coverage affect whether heap visits disappear.

A covering index is therefore a deliberate read-versus-write trade: it can lower latency and I/O for hot reads while increasing maintenance work, cache pressure, and write amplification.

Interview takeaway: I would add a covering index only when measured table lookups justify its extra storage and write-maintenance cost.

4. A unique constraint rejects a value that looks absent. How can NULL semantics explain it?

NULL is not an ordinary value, so both the “does this row exist?” check and unique enforcement can behave differently from intuition. The exact result is database-specific: PostgreSQL normally allows multiple NULLs in a unique constraint, while SQL Server’s ordinary unique index commonly permits only one NULL; PostgreSQL can explicitly request NULLS NOT DISTINCT.

Common ways NULL creates a misleading diagnosis are:

  • WHERE email = NULL is not true; it evaluates to unknown and finds no rows. Use WHERE email IS NULL.
  • In a composite unique key, PostgreSQL’s default NULL-distinct behavior means rows containing NULL generally do not conflict with each other. Other engines have different rules.
  • An application check such as “select, then insert” is race-prone. Another transaction may insert the same non-NULL value before the insert, and the unique constraint correctly rejects it.
  • A value that looks absent may differ by collation, case folding, trailing-space rules, normalization, or an invisible character; that is not NULL semantics, but it is a common companion symptom.
-- Correct NULL test
SELECT 1
FROM users
WHERE email IS NULL;

-- PostgreSQL 15+: make NULLs conflict
CREATE UNIQUE INDEX users_email_one_null
    ON users (email) NULLS NOT DISTINCT;

Diagnose the rejection by checking the actual bound value and its type, whether it is SQL NULL or an empty string, the database and version, and the constraint definition. Then reproduce inside concurrent transactions and rely on the constraint as the final arbiter; handle a unique-violation exception rather than trusting a prior existence check.

  1. If NULL should be ignored, use a database-appropriate filtered or partial unique index, or retain the default NULL-distinct rule.
  2. If exactly one NULL is required, use the database’s explicit option or a carefully designed expression/filtered constraint.
  3. If NULL should never occur, declare the column NOT NULL and validate it at the application boundary.

Interview takeaway: I would inspect both the database’s NULL rule and the exact bound value, because SQL NULL can make a row look absent while uniqueness behavior remains database-specific.

5. Why might PostgreSQL ignore a selective index for a small result set?

PostgreSQL chooses a sequential scan when its cost model says reading the table directly is cheaper than traversing the index and then fetching heap pages, even if the predicate is selective. A small table, a warm cache, favorable row correlation, stale statistics, or a high estimated random-I/O cost can all make that decision reasonable.

Check these signals in the actual plan:

  • EXPLAIN (ANALYZE, BUFFERS) shows estimated rows versus actual rows and whether the sequential scan touched few shared buffers.
  • The table may fit in cache, making sequential access cheap and index-plus-heap access relatively expensive.
  • The planner may estimate too many matches because statistics are stale, the column is skewed, or predicates are correlated.
  • A function, implicit cast, expression, or incompatible operator can make the predicate non-sargable, so the index is not a usable access path.
  • Low correlation between index order and heap order increases random heap-fetch cost; a LIMIT can still favor an index when the ordering matches.

Diagnose and fix it carefully:

  1. Run the actual plan with representative data and bind values; do not infer from a plain EXPLAIN alone.
  2. Refresh statistics with ANALYZE, and consider higher statistics targets or extended statistics for correlated columns.
  3. Check data types and rewrite predicates so the indexed column remains searchable. Add a partial or covering index only when it matches a frequent workload.
  4. Treat random_page_cost, effective_cache_size, and related settings as environment-wide cost-model inputs, not per-query hints. Change them only after measuring storage and cache behavior.
  5. Use a temporary SET enable_seqscan = off only as a diagnostic experiment; it is not a production fix.
ANALYZE orders;
EXPLAIN (ANALYZE, BUFFERS)
SELECT id
FROM orders
WHERE status = 'READY'
LIMIT 10;

A sequential plan is not evidence that PostgreSQL missed an index; it is evidence that, according to current estimates and costs, the index path was expected to be more expensive. Compare estimates with reality before changing planner settings.

Interview takeaway: I would first validate estimates and buffer behavior, because PostgreSQL may be correctly rejecting an index whose random heap work costs more than a sequential scan.

Section 2: Locks and Isolation

6. Requests hang during checkout. How can lock waits differ from deadlocks?

A lock wait is a transaction waiting for a lock that another transaction currently holds; it can eventually proceed. A deadlock is a cycle of waiters, so none can proceed, and the database must abort one transaction to break the cycle.

The operational difference is important:

  • A lock wait normally indicates contention, a slow transaction, or an unexpectedly broad lock. It increases latency but does not imply correctness failure.
  • A deadlock usually comes from inconsistent lock ordering, such as one code path updating the order then inventory while another updates inventory then order.
  • PostgreSQL detects deadlocks after deadlock_timeout; it raises SQLSTATE 40P01. A lock wait can continue until the blocker commits, a timeout fires, or the client gives up.
  • In production, inspect the waiting session, its blocker, transaction age, query, and lock mode. PostgreSQL exposes this through pg_stat_activity and pg_blocking_pids; other databases provide equivalent lock-wait views.
SELECT pid, wait_event_type, wait_event,
       now() - xact_start AS xact_age,
       pg_blocking_pids(pid) AS blockers,
       query
FROM pg_stat_activity
WHERE wait_event_type = 'Lock';

A practical response is:

  1. Find the blocker and determine why its transaction is still open: slow SQL, network-dependent work, an idle session, or a missing commit.
  2. For ordinary waits, reduce transaction scope, add appropriate indexes, and set a bounded lock_timeout or client timeout so requests fail predictably.
  3. For deadlocks, make every path acquire resources in the same order, keep transactions short, and retry the complete transaction after a recognized deadlock error.
  4. Do not solve every wait by lowering the timeout: that can improve latency while increasing rollbacks and hiding a real contention problem.

Interview takeaway: I distinguish a recoverable queue from a cycle, then fix transaction scope and lock ordering while retrying deadlock victims safely.

7. Why can SELECT ... FOR UPDATE still allow a concurrent insert?

SELECT ... FOR UPDATE locks rows that already exist and match the statement; it is not automatically a lock on every possible row or on the predicate’s gaps. Therefore another transaction may insert a new matching row unless a constraint, isolation mechanism, or stronger table/index locking prevents it.

The exact behavior depends on the database and isolation level:

  • In PostgreSQL’s usual READ COMMITTED and REPEATABLE READ, a row lock protects existing tuples, but a range predicate does not acquire ordinary gap locks. A concurrent insert can create a row matching the predicate.
  • InnoDB commonly uses next-key or gap locking under REPEATABLE READ, but its behavior changes under READ COMMITTED, for unique indexes, and for the exact search predicate.
  • A unique constraint can make a concurrent insert wait or fail, but that is enforcement of uniqueness, not proof that FOR UPDATE locked the whole range.
  • PostgreSQL SERIALIZABLE uses predicate-style conflict tracking and may abort a transaction rather than block every phantom insert.
BEGIN;
SELECT id FROM inventory
WHERE sku = 'A-17' AND available > 0
FOR UPDATE;
-- This locks matching existing rows only.
-- A separate INSERT can still create a new matching row.
COMMIT;

Choose the protection based on the invariant:

  1. If there must be one row, enforce it with a unique constraint and handle duplicate-key or serialization errors.
  2. If a range must remain unchanged, use a database-specific range-locking strategy, SERIALIZABLE, or a deliberately stronger table lock, accepting lower concurrency.
  3. Often the safest design is to lock a stable parent or counter row, then perform the insert, with a foreign key or unique constraint as the final guard.
  4. Test the actual engine, index, isolation level, and execution plan; the SQL phrase alone does not specify locking semantics.

Interview takeaway: FOR UPDATE protects known rows, not an abstract predicate, so constraints or deliberate range/serialization protection are needed for insert-sensitive invariants.

8. How does PostgreSQL Serializable isolation report conflicts, and how should code react?

PostgreSQL’s SERIALIZABLE isolation uses Serializable Snapshot Isolation: transactions can run concurrently, but PostgreSQL tracks dangerous read/write dependencies and aborts a transaction when the committed result could not be serialized. The application must catch SQLSTATE 40001 and retry the entire transaction, not just the failed statement.

Important details are:

  • The error is a normal concurrency outcome, not evidence that the database is corrupt. It can occur at COMMIT or while executing a statement.
  • A retry must start a fresh transaction, because the failed transaction is no longer usable. Reusing the same connection transaction or retrying one SQL statement is incorrect.
  • Keep retries bounded and use jittered backoff. If conflicts remain frequent, shorten transactions, index predicates, reduce overlapping work, or reconsider the isolation requirement.
  • External effects such as publishing an event or sending a request must not happen blindly inside a retryable unit. Use an outbox or another idempotent design.
  • PostgreSQL can show predicate locks as SIReadLock in pg_locks; logs and application metrics should count 40001 separately from ordinary failures.
for (int attempt = 1; attempt <= 3; attempt++) {
    try {
        return inTransaction(() -> performCheckout());
    } catch (SQLException e) {
        if (!"40001".equals(e.getSQLState()) || attempt == 3)
            throw e;
        Thread.sleep(25L * attempt); // add jitter in real code
    }
}
throw new AssertionError();

Make the retry boundary include all reads, writes, and commit; make the business operation idempotent; then monitor retry rate and latency.

  1. Make the retry boundary include all reads, writes, and commit; make the business operation idempotent; then monitor retry rate and latency.
  2. A read-only transaction that can safely wait may use PostgreSQL’s SERIALIZABLE, READ ONLY, DEFERRABLE option, trading startup delay for fewer serialization failures.
  3. Spring transaction retries require an outer retry boundary; self-invocation does not apply a separate proxy-based transaction.

Interview takeaway: Under PostgreSQL Serializable, a 40001 is the database asking the caller to rerun a complete, idempotent transaction with bounded retries.

9. A transaction sees changing totals. Which isolation behavior permits that, and what fixes it?

Changing totals during one logical operation usually means the transaction is using read committed behavior: each statement gets its own view of committed data, so two aggregate queries can observe different commits. Use one statement for the decision, a repeatable transaction snapshot, or explicit locking/serialization when the total must remain stable.

The distinction is between statements and transactions:

  • In PostgreSQL READ COMMITTED, each statement takes a snapshot when it starts. A first SUM and a later SUM can therefore differ after another transaction commits.
  • A single aggregate statement is internally consistent, but it is not necessarily consistent with a later statement in the same transaction.
  • REPEATABLE READ keeps one snapshot for the transaction. In PostgreSQL, a conflicting concurrent update can instead produce a serialization failure, which the application must retry.
  • READ UNCOMMITTED is often implemented as READ COMMITTED by MVCC databases, so changing the label may not provide dirty reads or solve this problem.
BEGIN;
SET TRANSACTION ISOLATION LEVEL REPEATABLE READ;
SELECT SUM(amount) FROM ledger WHERE account_id = 42;
-- Other statements in this transaction use the same snapshot.
COMMIT;

Diagnose and fix it deliberately:

  1. Check the database’s effective isolation level and identify whether the total is read once or repeatedly across statements.
  2. If consistency is only needed for one result, combine the calculation into one SQL statement or use a single snapshot-producing query.
  3. If several reads and writes form one invariant, use REPEATABLE READ or SERIALIZABLE, then retry the complete transaction on its documented conflict error.
  4. Use FOR UPDATE only when locking the relevant existing rows actually protects the invariant; it does not automatically prevent inserts matching a predicate. Stronger isolation and locking reduce concurrency, so measure contention rather than applying them globally.

Interview takeaway: The changing total is a snapshot-boundary problem: use one statement or a stronger transaction boundary, then handle the resulting concurrency failures.

10. Why can a long transaction prevent vacuum from reclaiming PostgreSQL dead tuples?

PostgreSQL’s MVCC keeps old row versions until no active transaction could still need to see them. A long-running transaction holds an old snapshot, so VACUUM may be able to mark dead tuples but cannot remove versions newer than that snapshot; table and index bloat can then grow.

Common causes and signals include:

  • A session that is idle in transaction after a query has taken its snapshot. It may hold the snapshot while the application waits on a remote call or user action.
  • A genuinely long query, an open cursor, or a transaction that batches too much work can keep backend_xmin old.
  • Prepared transactions and replication slots can also retain old horizons, although they are different from an ordinary client transaction.
  • Inspect pg_stat_activity for xact_start, state, query, and backend_xmin; compare transaction age with vacuum progress and table statistics. pg_stat_user_tables helps reveal growing dead tuples and delayed vacuuming.
SELECT pid, usename, state,
       now() - xact_start AS xact_age,
       backend_xmin, query
FROM pg_stat_activity
WHERE xact_start IS NOT NULL
ORDER BY xact_start;

A safe remediation sequence is:

  1. Find the owning service and why the transaction remains open; do not immediately terminate sessions without understanding the work they may be doing.
  2. Commit or roll back at smaller logical boundaries, keep network calls outside the transaction, close cursors, and avoid holding a transaction across request or user lifetimes.
  3. Set a carefully chosen idle_in_transaction_session_timeout to clean up abandoned sessions, and enforce application and connection-pool timeouts. This protects vacuum but can abort callers that legitimately pause.
  4. After the horizon advances, vacuum can reclaim eligible versions. Existing bloat may require extra maintenance, and aggressive cleanup can itself create I/O and lock pressure.

Interview takeaway: Vacuum is constrained by the oldest required snapshot, so the durable fix is to prevent abandoned or unnecessarily long transactions from holding that horizon open.

Preparing for a full interview loop? Full interview kit (600 Qs: Java, Spring Boot, database, DevOps, cloud, system design, microservices)

Section 3: Replication Behavior

11. Reads return older data after a successful write. How should the client handle replica lag?

Treat read-after-write as an explicit consistency requirement, not something a load balancer can guarantee. After writing to the primary, either route the dependent read to that primary, or carry a replication position and wait until the chosen replica has replayed it; otherwise accept that the read may be stale.

An asynchronous replica acknowledges neither the write nor its replay before the client continues. The write response can include a causal token such as the primary's WAL LSN. A later read uses that token to select a suitable replica and checks its replay position. This is stronger than sleeping for an arbitrary delay, because lag varies with load and network conditions.

Useful client policies include:

  • Route the whole request or session to the primary when correctness matters and the read is cheap enough.
  • Poll pg_last_wal_replay_lsn() on a replica until it is at least the token, with a short deadline.
  • Fall back to the primary, return a retryable response, or serve explicitly stale data after the deadline.
  • Do not use pg_last_xact_replay_timestamp() as an exact ordering token; clock skew and periods without transactions make it a poor guarantee.
-- On the writer, after the write
SELECT pg_current_wal_lsn();

-- On a replica, before the dependent read
SELECT pg_last_wal_replay_lsn() >= '0/16B6C50'::pg_lsn;

To diagnose this in production:

  1. Log the writer endpoint, read endpoint, write LSN, and wait duration with the request ID.
  2. Compare the token with pg_last_wal_replay_lsn() and inspect pg_stat_replication for receive, flush, and replay positions.
  3. Measure the fallback rate and bound the wait so a lagging replica cannot consume all request threads.

Interview takeaway: I would make the consistency policy explicit: primary routing for strict reads, or LSN-based waiting with a bounded fallback for scalable read-after-write.

12. How can an asynchronous replica lose committed writes during failover?

An asynchronous replica can lose committed writes because the primary acknowledges a transaction after recording and flushing its WAL locally, without waiting for any standby to receive or replay that WAL. If the primary fails before the relevant WAL reaches a surviving replica, promotion produces a database that is valid but missing transactions the client was already told had committed.

The loss is normally bounded by the unsent or unflushed-on-standby WAL at the failure point, but it is not necessarily bounded by time. Network partitions, a stalled receiver, storage failure, or a replica that is technically connected but far behind can all enlarge the gap. Promoting the old primary later also creates split-brain risk, so fencing or a reliable consensus mechanism is required.

Check these positions before and during a failover:

  • The primary's current WAL LSN and each standby's write, flush, and replay LSN.
  • The commit acknowledgment policy: asynchronous, synchronous, or quorum-based synchronous replication.
  • Whether WAL archiving can recover the missing range, and whether the archive is complete and durable.
  • Application effects such as duplicate requests, because a client may retry a transaction that actually committed on the failed primary.
SELECT application_name,
       client_addr,
       state,
       sent_lsn,
       write_lsn,
       flush_lsn,
       replay_lsn,
       sync_state
FROM pg_stat_replication;

Reduce the exposure by:

  1. Use synchronous or quorum replication when the required RPO is zero or close to zero, accepting commit latency and reduced availability during standby failure.
  2. Keep a tested WAL archive and recovery process for gaps that a standby cannot cover.
  3. Fence the old primary before promotion and reconcile any acknowledged-but-missing application operations after recovery.

Interview takeaway: A successful client commit means durable on the acknowledged primary, not necessarily present on a failover target, unless the replication acknowledgment policy says otherwise.

13. Why does a replication slot cause disk growth when a consumer stops?

A replication slot prevents PostgreSQL from recycling WAL that a consumer might still need. When the consumer stops, the slot's restart position stops advancing, so pg_wal retains every required segment; a long outage can therefore fill the volume and eventually stop the primary.

For a physical slot, the standby must receive the retained WAL. For a logical slot, the decoding consumer must advance the confirmed position, and catalog xmin retention can also delay cleanup of old row versions. The slot is intentionally durable across consumer restarts, so PostgreSQL cannot infer that an inactive consumer has been abandoned.

SELECT slot_name, slot_type, active,
       restart_lsn, confirmed_flush_lsn,
       pg_size_pretty(
         pg_wal_lsn_diff(pg_current_wal_lsn(), restart_lsn)
       ) AS retained
FROM pg_replication_slots;

Diagnose and fix it as follows:

  1. Identify the owning consumer and determine whether it is stopped, blocked, disconnected, or permanently decommissioned.
  2. Restart or repair the consumer and confirm that its slot position advances; for logical decoding, verify the consumer acknowledges processed changes.
  3. Drop an abandoned slot with pg_drop_replication_slot() only after confirming it is no longer needed. Do not manually delete files from pg_wal.
  4. Set an operational limit such as max_slot_wal_keep_size where supported, and alert on retained bytes and free disk. If the limit invalidates a slot, rebuild or reinitialize that consumer rather than assuming it can continue.

Important trade-offs:

  • A limit protects disk availability but can force a replica or logical subscriber to resynchronize.
  • More frequent monitoring reduces the chance that a stopped consumer becomes a primary outage.
  • A slot is not a substitute for a tested archive and backup strategy.

Interview takeaway: A slot trades automatic WAL recycling for delivery safety, so every slot needs an owner, a disk-growth alert, and a recovery policy.

14. A replica falls behind only during batch jobs. How would you separate I/O from WAL pressure?

Separate the two possibilities by comparing WAL production and replication positions with storage and replay metrics during the batch. A WAL-pressure problem shows an unusually large or fast-growing LSN gap and often high receiver or replay work; an I/O problem shows saturated disk latency or throughput even when WAL volume is ordinary.

Batch jobs can cause both: large updates generate WAL, dirty many pages, create checkpoints, and compete with the replica's WAL writes and data reads. Replay may also wait on locks held by long-running queries. “Replication lag” is therefore a symptom, not proof that the network is the bottleneck.

-- On the primary
SELECT now(), pg_current_wal_lsn();

-- On the primary, for each standby
SELECT application_name, sent_lsn, write_lsn,
       flush_lsn, replay_lsn,
       pg_size_pretty(pg_wal_lsn_diff(sent_lsn, replay_lsn)) AS gap
FROM pg_stat_replication;

Correlate those samples with:

  • pg_stat_wal WAL bytes and records, checkpoint activity, and batch transaction rate.
  • iostat or equivalent device latency, queue depth, and read/write utilization on primary and replica.
  • Replica CPU, WAL receiver status, replay throughput, and lock waits; on PostgreSQL 16 and later, pg_stat_io adds more database I/O detail.
  • Network throughput and packet loss, so a receive gap is not mistaken for disk saturation.

Run a controlled comparison:

  1. Repeat a representative batch with smaller commits and record WAL generated per row and replica catch-up time.
  2. Throttle or pause the batch while watching whether replay recovers; separately test storage headroom and network health.
  3. If WAL pressure dominates, reduce unnecessary updates, batch commits, tune indexes carefully, and provision replay capacity. If I/O dominates, improve storage or reduce competing reads and checkpoints. If locks dominate, shorten transactions and change query timing.

Interview takeaway: I would classify lag from LSN rates, replay state, and device metrics together, then fix the limiting resource rather than tuning replication blindly.

15. How do session routing and waiting for pg_last_wal_replay_lsn differ for read-after-write?

Routing a session to the primary avoids replica lag for that session, while waiting for pg_last_wal_replay_lsn() makes a replica safe for one causal read after it catches up. Routing is immediate but costs primary capacity; LSN waiting preserves read scale but adds variable latency and needs a timeout and fallback.

Session routing is about choosing a connection or endpoint. It does not make a read on an already-selected replica current, and a connection pool can accidentally move later operations to another host unless routing is enforced per request or transaction. It also does not help a read sent to a replica before the write's WAL has arrived.

-- Writer: obtain after the write
SELECT pg_current_wal_lsn();

-- Replica: wait/poll before the dependent query
SELECT pg_last_wal_replay_lsn() >= '0/16B6C50'::pg_lsn;

-- Then execute the application read on this same replica connection

Choose based on the consistency scope:

  • Use primary routing for read-after-write when the result must be immediate or the wait budget is very small.
  • Use a causal LSN token for request-level consistency while allowing unrelated reads to use replicas.
  • Use a bounded polling loop, then route to the primary or return a retryable result if the replica cannot catch up.
  • Keep the token with the request context; a database session alone cannot carry causality across separate pooled connections.

In production, verify that:

  1. The LSN is captured after the write completes and comes from the writer that accepted it.
  2. The target replica is actually replaying and its replay LSN advances toward the token.
  3. The wait and fallback are observable, because frequent timeouts indicate a capacity or topology problem rather than a client bug.

Interview takeaway: Primary routing gives immediate consistency by placement, whereas replay-LSN waiting gives causal consistency by proof and trades it for bounded latency.

Section 4: Safe Migrations

16. A migration times out while traffic continues. How can its lock acquisition create the outage?

A migration can cause an outage even when it eventually times out because acquiring its DDL lock may queue behind an existing transaction, and the queued lock can block normal application queries. The timeout usually aborts the waiting statement; it does not necessarily remove the original blocker or undo other pressure created by the queue.

For example, PostgreSQL commonly takes an ACCESS EXCLUSIVE lock for table changes. That conflicts with ordinary reads and writes. If a transaction has left a row lock, cursor, or idle-in-transaction session open, the migration waits. New application statements may then queue behind the migration or behind one another, depending on the lock mode and database. In MySQL, metadata locks produce a similar failure mode: a DDL statement waits for an old transaction, while later statements can also wait for metadata access.

SELECT pid, wait_event_type, wait_event, state,
       xact_start, query_start, query
FROM pg_stat_activity
WHERE datname = current_database();

SELECT a.pid, a.query, l.mode, l.granted,
       pg_blocking_pids(a.pid) AS blockers
FROM pg_stat_activity a
JOIN pg_locks l ON l.pid = a.pid
WHERE NOT l.granted;

A safe response is to:

  1. Set a short lock_timeout for migration statements, separately from statement_timeout.
  2. Check the blocking session and its owner before cancelling or terminating it; an idle in transaction session is often the real defect.
  3. Run the migration during a controlled low-traffic window, or use an online/non-blocking variant where the database supports one.
  4. Make the migration runner cancel and roll back cleanly after timeout, then retry only after the blocker is understood.

A short lock timeout limits blast radius, but it does not make a blocking DDL operation safe. The trade-off is that migrations may need retries and operational coordination, while terminating a session can roll back legitimate business work.

Interview takeaway: I would treat migration lock acquisition as production traffic, bound it with lock_timeout, and diagnose the blocker rather than assuming a timeout makes the operation harmless.

17. Why can adding a NOT NULL constraint scan a large PostgreSQL table?

Adding NOT NULL can scan a large PostgreSQL table because the database must prove that every existing row satisfies the constraint before it can enforce it for future writes. The scan can consume I/O and hold a table-level schema lock long enough to disrupt traffic.

The important distinction is between checking existing data and changing the catalog metadata. ALTER TABLE ... SET NOT NULL is not merely a declaration: without proof, PostgreSQL verifies that no row contains a null. On a large table that means reading the table, and concurrent writers may also be affected by the lock required for the alteration. The exact optimization depends on the PostgreSQL version. Modern PostgreSQL versions can avoid a second full scan when a valid check constraint already proves the column is non-null; verify the target version rather than assuming this behavior.

ALTER TABLE customer
  ADD CONSTRAINT customer_email_nn
  CHECK (email IS NOT NULL) NOT VALID;

ALTER TABLE customer
  VALIDATE CONSTRAINT customer_email_nn;

ALTER TABLE customer
  ALTER COLUMN email SET NOT NULL;

ALTER TABLE customer
  DROP CONSTRAINT customer_email_nn;

For a large production table:

  1. Measure the existing null count and fix or explicitly handle those rows first.
  2. Add the check as NOT VALID, which records the rule without immediately scanning old rows; new and changed rows are still checked.
  3. Validate it in a planned window. Validation still reads the table, so monitor I/O, lock waits, and replica replay.
  4. Use the validated constraint to let supported PostgreSQL versions infer non-nullness, then remove the redundant check only after confirming the resulting definition.
  • A NOT VALID constraint is not a shortcut around correctness: it leaves old rows unchecked until validation.
  • If the table is heavily written, validation and the final catalog change can still contend with concurrent DDL or long transactions.
  • An application-level null check is not a substitute for the database constraint.

Interview takeaway: I would separate proving old data is valid from enforcing the rule on new writes, and confirm the PostgreSQL version before relying on scan-avoidance optimizations.

18. How would you roll out a column rename without breaking old application versions?

I would not rename a live column in one deploy; I would use an expand-and-contract rollout. Add the new column, make old and new application versions compatible, migrate data and reads, and only remove the old name after every client and job has stopped using it.

A direct rename is usually metadata-only, but it immediately makes SQL containing the old identifier fail. That includes older application binaries, reporting jobs, scripts, stored procedures, and ad hoc operational tools. A compatibility view can help in some designs, but it does not make every ORM mapping or write path safe, and a view cannot transparently solve all dual-write semantics.

A typical rollout is:

  1. Add new_name as nullable, without changing the existing old_name path.
  2. Deploy code that reads the old value or uses a compatibility accessor, and writes both columns. Make the write idempotent and define which value wins if they diverge.
  3. Backfill new_name in small, restartable batches. Monitor errors and compare the columns.
  4. Deploy code that reads only new_name, while continuing dual writes long enough to cover rollback of older binaries.
  5. Stop old binaries and background consumers, enforce the new column's constraints, then remove the old column in a later migration.
UPDATE account
SET display_name_new = display_name
WHERE display_name_new IS NULL
  AND id > :last_id
  AND id <= :batch_end;

The difficult part is not the rename command; it is consistency during the transition. A database trigger can provide dual writes when many clients cannot be upgraded together, but it adds hidden behavior and write overhead. Application dual writes are easier to observe, but every writer must be found and changed. Keep rollback possible until the compatibility window has genuinely ended.

Interview takeaway: A safe rename is a compatibility rollout with dual reads or writes, not a single DDL statement followed by hope.

19. Deploys fail because two migration runners start together. How should migration locking work?

Migration runners should serialize through a lock owned by the same database they are changing, with a unique lock key and a bounded acquisition timeout. One runner applies migrations; the others wait or exit cleanly, and the migration history table remains the source of truth.

A database lock is preferable to an in-process mutex because application instances may run on different hosts. PostgreSQL advisory locks are useful for this purpose. A session-level advisory lock lasts until the connection closes, while a transaction-level lock lasts until commit or rollback. The runner must keep the owning connection open for the entire migration and must release it on every failure path. On databases without equivalent advisory locks, use the migration tool's documented locking mechanism or a carefully designed lock table with a unique row and lease/ownership rules.

BEGIN;
SELECT pg_advisory_lock(4815162342);
COMMIT;

-- Run migrations while this same session remains open.
-- On success or failure:
SELECT pg_advisory_unlock(4815162342);

A robust runner should:

  1. Acquire the lock before reading or modifying migration state, with a short timeout rather than an unbounded startup hang.
  2. Record migration identity, checksum, and completion atomically when the database supports transactional DDL.
  3. Keep each migration small and make failed execution roll back or leave an explicitly recoverable state.
  4. Have waiting runners exit, retry with backoff, or continue serving traffic without attempting migrations themselves.
  5. Alert if the lock owner disappears, a migration exceeds its expected duration, or history contains a partial or checksum-mismatched result.

Do not combine a database lock with a separate scheduler lock and assume they are equivalent; split-brain ownership can still occur if the scheduler's lease expires while the database session continues. Also avoid running migrations from every application startup unless the framework's locking and failure behavior are well understood.

Interview takeaway: The database being migrated should arbitrate migration ownership, and the lock must cover the complete read, execute, and record-history sequence.

20. A backfill overloads production. How can batching still create replication lag?

Batching limits the size of each transaction, but it does not limit the total WAL generated by a backfill. If the primary produces WAL faster than a replica can receive, flush, or replay it, even small commits accumulate replication lag.

An UPDATE can generate WAL for each changed row and for affected indexes. A backfill also competes with foreground queries for CPU, cache, I/O, and vacuum capacity. Frequent commits reduce rollback and lock duration, but they add commit and WAL overhead; a loop with no pause may simply turn one large burst into a sustained stream. Long-running queries on a replica, replica hot-standby conflicts, and hot_standby_feedback can make the backlog or its side effects worse.

WITH batch AS (
  SELECT id
  FROM orders
  WHERE id > :last_id
    AND processed_at IS NULL
  ORDER BY id
  LIMIT :batch_size
)
UPDATE orders o
SET processed_at = now()
FROM batch b
WHERE o.id = b.id;

-- Commit, measure lag, then continue from the last key.

Diagnose and control it by:

  1. Measure primary WAL generation and, on PostgreSQL, inspect pg_stat_replication for write, flush, and replay positions rather than relying on one generic lag number.
  2. Check replica CPU, I/O, replay waits, long-running read queries, and conflicts. Confirm whether the bottleneck is network, flush, or replay.
  3. Use a stable keyset range, bounded batches, and commits between batches. Avoid offset pagination, which gets slower and can skip or repeat rows as data changes.
  4. Throttle on observed lag: pause or reduce batch size when the replica falls behind, and resume only after it recovers.
  5. Run during lower write volume, remove unnecessary index maintenance if safely possible, and verify the backfill is restartable and idempotent.
  • A smaller batch improves transaction and lock behavior, but may not reduce average WAL per row.
  • A trigger or generated value can move work into foreground writes and may be worse for latency.
  • Do not delete or recycle required WAL merely to hide lag; replicas must receive it to remain consistent.

Interview takeaway: I would throttle a backfill against measured WAL and replay capacity, because transaction size is only one part of replication pressure.

Key Takeaways

  • Use EXPLAIN (ANALYZE, BUFFERS) and current statistics to separate a stale or misestimated plan from an unsuitable index.
  • Composite indexes follow their leading-column ordering, so a predicate on a later column may not provide an efficient index range scan.
  • Covering indexes can reduce heap reads while increasing index size, maintenance work, and write latency.
  • NULL is not an ordinary value, so unique-constraint behavior depends on database semantics and the chosen NULL policy.
  • A lock wait blocks behind another transaction, while a deadlock requires the database to abort one participant to break a cycle.
  • SELECT ... FOR UPDATE locks rows that exist in the chosen scan; it does not automatically lock gaps where a concurrent insert could occur.
  • Serializable transactions may fail with a serialization error and should be retried from a fresh transaction when the operation is safe to repeat.
  • Read-after-write behavior requires an explicit consistency strategy, such as session routing, a replay position, or a stronger read target.
  • Long-running transactions can keep old snapshots visible and prevent PostgreSQL vacuum from reclaiming dead tuples.
  • Online migrations need staged schema changes, bounded backfills, controlled lock acquisition, and observability for WAL, locks, and replica replay.

Frequently Asked Questions

Which evidence should I collect before changing an index?

Capture the actual query, bind values or representative parameters, execution time, row counts, and EXPLAIN (ANALYZE, BUFFERS) output. Compare estimated and actual cardinalities, check table and index statistics, and inspect whether the plan changed after data growth or a deployment. Also measure write volume and index size, because a faster read plan may impose unacceptable maintenance cost.

What is a practical way to investigate database blocking?

Start with the blocked session, its wait event, transaction age, and the session holding the conflicting lock. Reconstruct the transaction dependency chain rather than stopping at the first blocker. Check application logs and connection-pool behavior to find work performed while a transaction is open. For recurring incidents, record lock duration, query fingerprints, and transaction boundaries so the fix addresses the cause.

How should an application retry a failed transaction?

Retry only errors that are known to be transient and only when the operation is safe to repeat. A retry must start a completely new transaction; it cannot reuse a transaction that has already failed or a connection left in an aborted state. Bound the retry count, add backoff and jitter, preserve idempotency, and avoid retrying integrity or validation failures.

How can a team tell whether replica lag is caused by WAL volume or slow replay?

Compare the primary's WAL generation rate with the replica's receive and replay positions over time. Inspect network transfer, disk write latency, replay process activity, checkpoint behavior, and the size of the replay backlog. Batch jobs that generate WAL without saturating replica resources point toward WAL volume; high I/O wait or slow replay with modest WAL pressure points toward the replica's storage or workload.

What makes a production backfill safer than a single large update?

Use small, bounded batches selected by a stable key, commit each batch, and pause when lock contention, latency, WAL growth, or replica lag crosses a threshold. Make the operation restartable and avoid repeatedly scanning completed rows. Test the index and constraint strategy beforehand, schedule work around traffic where possible, and monitor both the primary and every replica affected by the generated WAL.

Conclusion

The strongest database answers connect internal behavior to observable symptoms and application decisions. Explain what the planner, lock manager, transaction system, replica, or migration is doing; show which measurements would confirm that explanation; then describe a safe mitigation and its trade-offs. For Java backend developers, that last step includes transaction boundaries, retries, routing, idempotency, and deployment sequencing. These habits turn familiar database concepts into reliable production reasoning rather than isolated definitions.

Which question would you find the hardest? Tell me in the comments.

Explore More Java Interview Resources

Cloud, DevOps & System Design for Java Backend (200 Qs: Docker, Kubernetes, AWS, CI/CD, Terraform, databases, system design)
https://topmate.io/logicbrace/2294488

Full interview kit (600 Qs: Java, Spring Boot, database, DevOps, cloud, system design, microservices)
https://topmate.io/logicbrace/2294498

Complete Java Full Stack Developer Kit (900 Qs: Core Java, Spring Boot & Microservices, Cloud/DevOps/System Design, React & Angular)
https://topmate.io/logicbrace/2306382

PostgreSQL – 20 Production Scenarios (with Answers)

Post a Comment

0 Comments

Close Menu