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 guideProve 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:
Diagnose it in production without guessing:
pg_stat_statements and EXPLAIN (ANALYZE, BUFFERS) are useful in PostgreSQL; use the equivalent plan cache and actual-plan tooling for another database.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.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.
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.Diagnose and correct it as follows:
OR can prevent a seek even when the column is present.(status, ...) index only if that workload justifies it.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.
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:
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:
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.
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.-- 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.
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.
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.LIMIT can still favor an index when the ordering matches.Diagnose and fix it carefully:
EXPLAIN alone.ANALYZE, and consider higher statistics targets or extended statistics for correlated columns.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.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.
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:
deadlock_timeout; it raises SQLSTATE 40P01. A lock wait can continue until the blocker commits, a timeout fires, or the client gives up.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:
lock_timeout or client timeout so requests fail predictably.Interview takeaway: I distinguish a recoverable queue from a cycle, then fix transaction scope and lock ordering while retrying deadlock victims safely.
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:
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.REPEATABLE READ, but its behavior changes under READ COMMITTED, for unique indexes, and for the exact search predicate.FOR UPDATE locked the whole range.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:
SERIALIZABLE, or a deliberately stronger table lock, accepting lower concurrency.Interview takeaway: FOR UPDATE protects known rows, not an abstract predicate, so constraints or deliberate range/serialization protection are needed for insert-sensitive invariants.
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:
COMMIT or while executing a statement.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.
SERIALIZABLE, READ ONLY, DEFERRABLE option, trading startup delay for fewer serialization failures.Interview takeaway: Under PostgreSQL Serializable, a 40001 is the database asking the caller to rerun a complete, idempotent transaction with bounded retries.
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:
READ COMMITTED, each statement takes a snapshot when it starts. A first SUM and a later SUM can therefore differ after another transaction commits.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:
REPEATABLE READ or SERIALIZABLE, then retry the complete transaction on its documented conflict error.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.
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:
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.backend_xmin old.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:
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.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)
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:
pg_last_wal_replay_lsn() on a replica until it is at least the token, with a short deadline.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:
pg_last_wal_replay_lsn() and inspect pg_stat_replication for receive, flush, and replay positions.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.
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:
SELECT application_name,
client_addr,
state,
sent_lsn,
write_lsn,
flush_lsn,
replay_lsn,
sync_state
FROM pg_stat_replication;
Reduce the exposure by:
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.
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:
pg_drop_replication_slot() only after confirming it is no longer needed. Do not manually delete files from pg_wal.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:
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.
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.pg_stat_io adds more database I/O detail.Run a controlled comparison:
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.
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:
In production, verify that:
Interview takeaway: Primary routing gives immediate consistency by placement, whereas replay-LSN waiting gives causal consistency by proof and trades it for bounded latency.
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:
lock_timeout for migration statements, separately from statement_timeout.idle in transaction session is often the real defect.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.
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:
NOT VALID, which records the rule without immediately scanning old rows; new and changed rows are still checked.NOT VALID constraint is not a shortcut around correctness: it leaves old rows unchecked until validation.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.
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:
new_name as nullable, without changing the existing old_name path.new_name in small, restartable batches. Monitor errors and compare the columns.new_name, while continuing dual writes long enough to cover rollback of older binaries.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.
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:
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.
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:
pg_stat_replication for write, flush, and replay positions rather than relying on one generic lag number.Interview takeaway: I would throttle a backfill against measured WAL and replay capacity, because transaction size is only one part of replication pressure.
EXPLAIN (ANALYZE, BUFFERS) and current statistics to separate a stale or misestimated plan from an unsuitable index.SELECT ... FOR UPDATE locks rows that exist in the chosen scan; it does not automatically lock gaps where a concurrent insert could occur.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.
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.
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.
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.
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.
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.
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

0 Comments