Databases Senior cheat sheet: interview answers
Every question of this level with its correct answer and explanation, on one page for a quick review before the interview.
1. How does PostgreSQL decide whether a row version is visible to a transaction?
Correct answer: By comparing row
xmin/xmaxwith the snapshotxminis the creating transaction andxmaxthe deleting or updating one. A snapshot lists which transactions were still in progress, so the row is visible only if its creator committed before it.2. What is transaction ID wraparound, and why is it dangerous?
Correct answer: 32-bit IDs get reused; unfrozen rows force a write stop
Autovacuum freezes old rows long before the limit. Disabling autovacuum or holding very long transactions can push a database toward a forced shutdown.
3. What is table bloat and what usually causes it?
Correct answer: Dead row versions that aren't reused fast enough
Tune autovacuum per table (lower scale factors for hot tables), avoid long transactions, and rebuild bloated objects online with
pg_repackorREINDEX CONCURRENTLY.4. What is the purpose of the write-ahead log (WAL)?
Correct answer: Crash recovery and streaming changes to replicas
Data pages can be written to disk later in the background. WAL also powers physical replication, logical decoding and point-in-time recovery.
5. What does
synchronous_commit = offtrade away?Correct answer: A crash may lose the last few committed transactions
It can be set per transaction, e.g. for analytics events you can afford to lose, while payments keep full durability.
6. How do B-tree storage engines and LSM-tree storage engines differ for writes?
Correct answer: B-trees update in place; LSM trees append and merge
Cassandra, RocksDB and ScyllaDB use LSM trees for write-heavy workloads. PostgreSQL and MySQL InnoDB use B-trees.
7. Why do row-oriented databases struggle with analytics queries over billions of rows?
Correct answer: They read whole rows even for a few columns
OLTP (many small transactions) and OLAP (big scans) have different needs. Analytics often moves to ClickHouse, BigQuery, Snowflake or DuckDB.
8. Why can too many indexes hurt a write-heavy table beyond disk space?
Correct answer: Every write must modify each index, adding WAL and I/O
Updates that touch an indexed column also lose the HOT optimization. Drop unused indexes found via
pg_stat_user_indexes.9. What is write skew?
-- Rule: at least one doctor must be on call. -- T1 and T2 both see 2 doctors on call, each takes one off. UPDATE doctors SET on_call = false WHERE id = 1; -- T1 UPDATE doctors SET on_call = false WHERE id = 2; -- T2Correct answer: Two updates on different rows together break a rule
Repeatable Read (snapshot isolation) allows it. Serializable isolation, explicit locks (
FOR UPDATEon the rows checked) or a constraint prevent it.10. How does PostgreSQL implement the Serializable level?
Correct answer: Serializable Snapshot Isolation, aborting risky transactions
It doesn't block readers, but aborts are expected under contention, so the app must retry. Read-only deferrable transactions can avoid aborts entirely.
11. How can you build a job queue on PostgreSQL that many workers poll safely?
SELECT id FROM jobs WHERE status = 'queued' ORDER BY id FOR UPDATE SKIP LOCKED LIMIT 1;Correct answer:
FOR UPDATE SKIP LOCKEDgives each worker its own rowLibraries like pg-boss and graphile-worker use this. It works well for moderate throughput and keeps jobs transactional with your data.
12. What are advisory locks in PostgreSQL?
Correct answer: Application-defined locks on arbitrary numbers
pg_try_advisory_lock(key)returns false if someone else holds it. Session-level locks must be released explicitly; with poolers in transaction mode, prefer transaction-level ones.13. Many requests update the same counter row (
UPDATE stats SET views = views + 1 WHERE id = 1). What's the problem and a fix?Correct answer: All updates serialize on one row lock, a hot row
Each update waits for the previous one to commit. Sharded counters (N rows summed on read) or counting in Redis with periodic flushes remove the contention.
14. Why should the uniqueness of an idempotency key be enforced with a unique constraint rather than a 'check, then insert'?
Correct answer: Concurrent duplicates can both pass a check
Insert the key first (
ON CONFLICT DO NOTHING), and only the request that inserted it does the work. Others return the stored result.15. Why is a distributed lock in Redis (e.g. Redlock) not enough on its own to protect data correctness?
Correct answer: A paused client can write after the lock expires
Locks with timeouts are fine for efficiency (avoiding duplicate work). For correctness, the resource must reject writes with an older token, or use database transactions and constraints.
16. What is the trade-off between synchronous and asynchronous replication?
Correct answer: Sync: safer but slower commits; async: the reverse
A common setup is one synchronous standby (or quorum) for durability plus asynchronous replicas for reads.
17. A user updates their profile and immediately sees the old data. Reads go to replicas. What's the issue and fix?
Correct answer: Replication lag breaks read-your-writes
Options include sticky primary reads after writes, waiting for the replica to replay a given WAL position, or reading critical data only from the primary.
18. What does logical replication allow that physical streaming replication doesn't?
Correct answer: Selected tables, across major versions
It's used for zero-downtime major upgrades and for feeding other systems. Physical replication copies the whole cluster exactly and replicas are read-only.
19. What is change data capture (CDC)?
Correct answer: Streaming row-level changes from the database log
Reading the log avoids dual writes from the application, which can diverge when one write fails. It pairs well with the outbox pattern.
20. What is 'split brain' in a failover setup?
Correct answer: Two nodes both accept writes as the primary
Failover tools like Patroni use a consensus store (etcd, Consul) and fencing so only one primary can accept writes.
21. What do RPO and RTO mean?
Correct answer: RPO: acceptable data loss; RTO: acceptable recovery time
An RPO near zero needs synchronous replication; a short RTO needs automated failover. Backups with PITR cover mistakes like accidental deletes, which replicas copy instantly.
22. When does table partitioning in PostgreSQL help most?
Correct answer: Very large tables queried by a key, often time
Dropping a monthly partition replaces a huge
DELETE. Queries that don't filter on the partition key may get slower because they touch all partitions.23. What makes a good shard key?
Correct answer: High cardinality, even load, fits common queries
A time-based key sends all new writes to one shard (a hotspot). Queries that cross shards are expensive, so keep a tenant's data together.
24. Why is consistent hashing used in distributed data stores?
Correct answer: Adding a node moves only a small share of keys
Virtual nodes smooth out uneven distribution. Cassandra, DynamoDB and many caches use variants of it.
25. What problems appear once data is sharded across databases?
Correct answer: Cross-shard joins and transactions become hard
That's why sharding is usually a last step after optimizing queries, adding replicas, caching and partitioning. Tools like Citus or Vitess hide part of the complexity.
26. How can you generate unique IDs across shards without a central sequence?
Correct answer: Time-ordered IDs like UUID v7 or Snowflake
Per-shard sequences collide across shards. Time-ordered IDs stay roughly sortable and index-friendly.
27. What does the CAP theorem say?
Correct answer: On a partition, choose consistency or availability
Partitions can't be avoided, so the real choice is what happens during one. PACELC adds that without partitions you trade latency for consistency.
28. What does 'eventual consistency' mean?
Correct answer: Replicas converge; reads may be stale for a while
Many systems offer stronger options per request, like quorum reads or read-your-writes sessions. Know which guarantees your code relies on.
29. What is linearizability?
Correct answer: Each operation seems to happen at a single instant
It's what people often mean by 'strong consistency'. It costs latency across regions, because nodes must coordinate.
30. In a quorum system with N replicas, why do
R + W > Nreads and writes give up-to-date reads?Correct answer: Every read set overlaps with every write set
With N=3, W=2, R=2, any two replicas share at least one. Edge cases (sloppy quorums, concurrent writes) still need conflict resolution.
31. A query is fast in development but slow in production with the same indexes. What should you check first?
Correct answer: The production plan with
EXPLAIN (ANALYZE, BUFFERS)With 100 rows every plan is fast. Skewed data (one tenant with millions of rows) can make a plan good for most values and terrible for a few.
32. What problem can prepared statements with generic plans cause?
Correct answer: A generic plan can ignore actual parameter values
plan_cache_mode = force_custom_planforces per-value planning when needed. Most of the time generic plans save planning time.33. Which pitfalls come with PgBouncer in transaction pooling mode?
Correct answer: Session state like
SETandLISTENisn't preservedEach transaction may run on a different server connection. Use transaction-scoped settings (
SET LOCAL) and recent PgBouncer versions that support protocol-level prepared statements.34. How do you safely backfill a new column on a table with 500 million rows?
Correct answer: Update in small batches by primary key ranges
A single giant update holds locks for long, bloats the table and can stall replicas. Batches are resumable if something fails.
35. How do you add a foreign key or
NOT NULLcheck to a big table without blocking writes for a long time?Correct answer: Add it as
NOT VALID, thenVALIDATE CONSTRAINTFor
NOT NULL, add aCHECK (col IS NOT NULL) NOT VALID, validate it, thenSET NOT NULL, which can use the validated check and skip a full scan.36. How can you count unique visitors over huge data sets cheaply when approximate results are fine?
Correct answer: A HyperLogLog sketch, e.g. Redis
PFCOUNTHyperLogLog keeps about 12 KB per counter in Redis with around 1% error. Sketches can also be merged across days or shards.
37. What's a typical reason to cap
max_connectionsin PostgreSQL and pool instead of raising it to thousands?Correct answer: Too many backends cause contention and cut throughput
Throughput usually peaks with a number of active connections near a small multiple of CPU cores. A pooler queues the rest cheaply.
38. What are the trade-offs of 'shared tables with
tenant_id' versus 'a schema or database per tenant' in a SaaS app?Correct answer: Shared is simplest but needs strict filtering
Many SaaS apps start shared with RLS and move large or regulated tenants to dedicated databases later. Index on
(tenant_id, ...).39. What is event sourcing?
Correct answer: Storing changes as events, the source of truth
It gives a full audit trail and lets you build new read models later. The cost: complex queries need projections, and event schemas are hard to change.
40. What is CQRS in the context of data storage?
Correct answer: Separating the write model from read models
Read models are updated asynchronously, so they're eventually consistent. It's useful for complex domains or very different read and write loads, overkill for simple CRUD.
41. Why is a 'dual write' (write to the database, then publish to Kafka) risky, and what's the alternative?
Correct answer: One write can fail and leave systems inconsistent
The outbox stores the event in the same transaction as the change; a relay publishes it at least once. Consumers must be idempotent.
42. How would you model time-series data, like metrics every second from 10,000 devices, in PostgreSQL?
Correct answer: Partition by time, index
(device_id, time)Time partitions make retention a cheap
DROP. Continuous aggregates or materialized rollups keep dashboards fast.43. What is DynamoDB's single-table design?
Correct answer: Several entities in one table, with designed keys
DynamoDB has no joins, so you model for queries first. It scales predictably but makes new, unplanned query patterns hard.
44. Why is using Redis as the only store for important business data risky?
Correct answer: Data lives in memory, so a crash can lose writes
AOF with
appendfsync alwaysis durable but slow;everyseccan lose about a second. Keep the source of truth in a durable database and use Redis for derived data.45. When does a search engine like Elasticsearch or OpenSearch make sense next to PostgreSQL?
Correct answer: For advanced search at scale
Search indexes are derived data: keep them in sync via CDC or an outbox, and accept a small delay. Start with PostgreSQL full-text search if it's enough.
46. What is a star schema used for?
Correct answer: Analytics: a fact table linked to dimension tables
It's denormalized on purpose for fast aggregations in data warehouses. Operational databases stay normalized.
47. How can you do a major PostgreSQL version upgrade with minimal downtime?
Correct answer: Logical replication to a new cluster, then switch
pg_upgradeis fast but needs downtime. Logical replication keeps the old cluster running until the cutover; sequences and DDL need extra care.48. Why are logical dumps (
pg_dump) alone not enough as a backup strategy for a large, busy database?Correct answer: They're slow and capture only one moment
Dumps are still useful for moving single databases or schemas. Tools like pgBackRest or managed snapshots handle physical backups.
49. Which measures protect sensitive columns (e.g. personal data) in a database?
Correct answer: Least privilege, encryption and audit logging
Also limit who can access backups and replicas, which contain the same data. Mask data when copying production into staging.
50. What does
pg_stat_activityhelp you diagnose during an incident?Correct answer: Which sessions run what and what they wait on
Combine it with
pg_locksto find the blocking session.pg_cancel_backendcancels a query;pg_terminate_backendends the session.51. How should a team approach choosing a database for a new product?
Correct answer: Start from the data model and access patterns
Every extra datastore adds operations, backups and consistency problems. Add specialized stores when a real need appears.
52. What is the role of
shared_buffersand the OS page cache in PostgreSQL performance?Correct answer: Both cache pages; a fitting working set avoids disk
A common starting point is about 25% of RAM for
shared_buffers.EXPLAIN (BUFFERS)shows hits versus reads.53. Why might a query using
ORacross different columns be slow, and what can help?SELECT * FROM users WHERE email = $1 OR phone = $2;Correct answer: One index can't serve both; try a
UNIONWith indexes on both columns, a BitmapOr combines them. Without one of them, the planner falls back to scanning the table.
54. What does the
fillfactorstorage setting do for a heavily updated table?Correct answer: Leaves free space in pages for HOT updates
A fillfactor of, say, 80 trades some space for fewer index updates and less bloat on update-heavy tables.
55. What are extended statistics (
CREATE STATISTICS) for?Correct answer: Teaching the planner about column correlations
By default the planner assumes columns are independent and multiplies selectivities, which underestimates rows for correlated columns.
56. Why can a
LIMITquery sometimes be slower than the same query withoutLIMIT?Correct answer: The planner may walk an index, expecting quick matches
This happens with skewed or correlated data. Better statistics, a composite index matching filter and order, or rewriting the query helps.
57. What is a wide-column store like Cassandra designed for?
Correct answer: Very high write throughput across many nodes
You model one table per query. There are no joins and limited secondary indexes, so access patterns must be known up front.
58. When does a graph database (like Neo4j) fit better than a relational one?
Correct answer: When queries traverse many-hop relationships
Relational databases can do it with recursive CTEs, but deep traversals get slow and awkward. For shallow relationships SQL is fine.
59. How do MongoDB write concerns and read concerns relate to consistency?
Correct answer: They set how durable writes are and what reads see
With
w: 1a write acknowledged only by the primary can be rolled back after a failover.majorityfor both gives much stronger guarantees.60. What is a vector database (or the
pgvectorextension) used for?Correct answer: Finding nearest embeddings by similarity
Approximate indexes like HNSW trade a little accuracy for speed.
pgvectorkeeps vectors next to the rest of your data and transactions.61. Why is it risky to rely on database-generated timestamps from different servers to order events?
Correct answer: Server clocks drift and jump out of order
Even NTP-synced clocks differ by milliseconds. Last-write-wins by timestamp can silently drop updates.
62. What is the main risk of
ON DELETE CASCADEchains in a large schema?Correct answer: One delete can silently remove lots of related data
Use cascades where child rows truly have no meaning alone. For large or important data, prefer soft deletes or explicit, batched cleanup.
63. For
WHERE tenant_id = $1 AND created_at > $2 ORDER BY created_at, which composite index order is best?Correct answer:
(tenant_id, created_at)With the equality column first, all rows for the tenant are adjacent and already sorted by time. A range column first would scatter each tenant across the index.
64. How can PostgreSQL prevent two overlapping bookings of the same room at the database level?
ALTER TABLE bookings ADD CONSTRAINT no_overlap EXCLUDE USING gist (room_id WITH =, during WITH &&);Correct answer: An exclusion constraint over a range column
It's race-free, unlike checking for overlaps before insert. It needs the
btree_gistextension for the equality part onroom_id.65. When is hash partitioning useful?
Correct answer: To spread a table evenly by a key
Range partitioning by time is better for retention. Hash partitioning only prunes for equality on the key.
66. An order flow spans the orders, payments and shipping services, each with its own database. How do you keep them consistent without distributed transactions?
Correct answer: A saga of local transactions with compensations
Two-phase commit couples services and blocks when the coordinator fails. Sagas accept temporary inconsistency and need idempotent, retryable steps.
67. Long analytics queries on a streaming replica get cancelled with 'conflict with recovery'. Why?
Correct answer: WAL replay must remove rows the query still reads
max_standby_streaming_delayorhot_standby_feedbackreduce cancellations, at the cost of replication delay or bloat on the primary. A separate analytics replica or warehouse is cleaner.68. What is a safe sequence for dropping a column in a system with rolling deploys?
Correct answer: Stop using it in code first, then drop it later
Old instances still running during deploy would fail on a missing column.
DROP COLUMNitself is fast in PostgreSQL: it only marks the column as dropped.69. Right after a database failover, latency spikes even though the new primary has the same hardware. What's a likely cause?
Correct answer: A cold cache: hot data isn't in memory yet
Replicas serving reads stay warmer. Extensions like
pg_prewarmcan load important tables and indexes into memory ahead of time.70. A user asks to delete all their personal data (GDPR). What's often overlooked?
Correct answer: Copies in backups, replicas, logs and caches
Common approaches: limited backup retention, crypto-shredding (deleting a per-user encryption key) and pseudonymizing data in analytics.
71. Why should migrations be tested against a production-sized copy of the data?
Correct answer: Locks and rewrites behave differently at scale
Measure duration and locks on realistic data, and use masked copies so personal data doesn't leak into staging.
72. After a deploy, hundreds of new app instances open connections at once and the database becomes unresponsive. What helps?
Correct answer: A pooler in front and staggered startup with backoff
Connection storms waste CPU on authentication and process creation. Serverless platforms are especially prone to this.
73. What is TOAST in PostgreSQL?
Correct answer: Storing large values compressed and out of line
Big
text,jsonborbyteavalues are TOASTed. Updating one key in a largejsonbvalue still writes the whole value again.74. How do you keep a denormalized value like
posts.comments_countcorrect under concurrency?Correct answer: Update it atomically in the comment's transaction
Read-modify-write in the app loses updates. For very hot counters, consider sharded counters or async aggregation with occasional reconciliation.
75. Why might a unique index on
emailbe unsuitable once you add soft deletes?Correct answer: A deleted row still holds the email; use a partial index
Partial unique indexes enforce uniqueness only among active rows. Decide too whether email checks should be case-insensitive (
lower(email)).