PostgreSQL
PostgreSQL is useful when relationships, constraints, and transactional state transitions matter.
What, why, when and how
What is it?
PostgreSQL is a relational database supporting SQL queries, constraints, indexes and transactions with selectable isolation behavior.
Why is it needed?
Related records often need enforceable local invariants and flexible access through joins and indexed queries.
When should I use it?
Use it when relational modeling and transactional correctness fit the workload, with measured connection and storage capacity.
When should I choose something else?
A local transaction cannot roll back an external SMS or payment. Avoid holding locks during slow network calls or assuming one database instance has unlimited capacity.
How do I use it?
Define constraints and indexes, make related changes atomic, choose isolation deliberately, and bound connection and lock occupancy.
Can you show a concrete example?
An inventory update decrements quantity only where it is positive and returns the new value. Competing buyers cannot both consume the last unit, while payment still needs a separate durable workflow.
Read the diagram
Inventory s7 starts with quantity 1; UPDATE only where quantity > 0; return result; Winner gets 0; competing update returns no row
Follow the detailed diagrams below to trace the additional state changes and failure cases behind these answers.
PostgreSQL is useful when relationships, constraints, and transactional state transitions matter. The interview question is not whether a relational database can scale in the abstract. It is whether the selected query and write boundaries fit the workload, and whether the application respects finite connections, lock time, storage, and replication capacity.
Learning goals
Transactions; constraints; MVCC basics; isolation; row locks; composite indexes; connection pooling; replica lag; partitioning; operational limits.
Observe atomicity, isolation and visibility separately
Stock starts at quantity 1. Two transactions attempt an atomic UPDATE ... SET quantity=quantity-1 WHERE quantity>0 RETURNING quantity. Under the intended row-update contract, one returns quantity 0; the other returns no row after the relevant concurrency resolution. A prior SELECT followed by an unconditional UPDATE recreates the lost-update/oversell risk.
UPDATE stock SET quantity = quantity - 1
WHERE sku = 's7' AND quantity > 0
RETURNING quantity;Read the diagram
Stock s7 starts at quantity 1; A and B request conditional decrement; Winner UPDATE returns quantity 0; Loser UPDATE returns no row; Local atomicity does not include provider payment
Atomicity prevents a partially committed local transaction. Constraints define local consistency invariants. Isolation determines interactions among concurrent transactions; read committed can use a fresh snapshot per statement, so two reads within one transaction can observe a newly committed change. Stronger isolation can abort conflicting work and requires whole-transaction retry under a stable business identity. Durability depends on the configured commit and recovery contract.
MVCC keeps row versions for visibility; vacuum and long-lived snapshots affect cleanup. A B-tree or specialized index supports a query shape, while EXPLAIN/actual plans show remaining scans, joins and sorts. Connection pooling bounds connection count but not necessarily active query work: a pool of 100 expensive queries can still overload storage. Bound concurrency and deadlines separately.
Read replicas can lag; route a required read-after-write by primary or a verified watermark. Replication, failover fencing, backups and restore tests answer different recovery questions. Keep external calls outside transactions holding locks; a local outbox can connect committed state to asynchronous publication.
Show answer and explanation
Answer: A successful local stock transaction does not prove a payment provider succeeded. Preserve the hold/order identity, resolve uncertain payment and compensate according to recorded facts.
Step-by-step reasoning
1. Put invariants in the database
Use primary keys, unique constraints, foreign keys, and check constraints for rules they can express. For a scarce resource, use a conditional update or a short transaction with appropriate locking. A SELECT followed by an unconditional UPDATE is not an atomic reservation even when both statements read current data.
2. Choose isolation deliberately
Read Committed gives statement-level snapshots and is not a promise that every multi-statement business rule is serializable. Stronger isolation or explicit locks may be needed for cross-row invariants. Serializable transactions can abort and require a retry of the whole transaction. Keep external effects out of retryable transactions unless separately protected.
3. Bound connection and lock occupancy
A connection pool limits concurrent database sessions; it does not manufacture database throughput. Keep transactions short and release connections promptly. A thousand serverless invocations each opening several connections can exhaust the database before CPU is fully used. Add queue deadlines and reject work when waiting becomes useless.
4. Observe maintenance and growth
Use query plans and representative data to tune indexes. Track slow queries, lock waits, connection wait time, disk growth, replication lag, and vacuum health. Long transactions can hold old snapshots and complicate cleanup. Partitioning can help retention and pruning but does not automatically distribute writes across independent servers.
Contracts and state
The following sketch makes the decision boundary concrete. Field names and capacity assumptions are illustrative; adapt them to the stated product contract.
UPDATE seat
SET state = 'held', hold_id = :hold, expires_at = :expiry
WHERE event_id = :event AND seat_id = :seat
AND state = 'available'
RETURNING seat_id;
-- one returned row: acquired; zero: conflict
-- commit before returning successful acquisitionWorked example
Two buyers attempt the conditional reservation. One update obtains the row and commits the held state. The other does not obtain an available seat and must return a conflict, not success. Keep payment authorization outside the row-locking transaction. A later confirmation checks the hold identity and validity, so a slow payment cannot claim a seat that has since changed owners.
Failure walkthrough
Increasing application replicas increases outstanding queries and lock contention. Successful throughput can fall while connection count rises. Bound the pool, inspect the query and transaction duration, and apply backpressure before adding more callers. A replica can serve tolerant reads, but a stale replica must never decide whether the last seat is available.
Read the diagram
Buyer A conditional update → A commits held state → Buyer B checks same row → Condition no longer matches → B receives conflict
Decisions and trade-offs
| Tool | Use | Caution |
|---|---|---|
| Unique constraint | One identity per business key | Handle conflict explicitly |
| Row lock | Serialize conflicting updates | Keep transaction short |
| Serializable isolation | Protect suitable multi-row invariants | Retry aborted transactions |
| Read replica | Tolerant read scale | Lag is not correctness authority |
Check your understanding
Why should a provider payment call not run while holding a seat row lock?
Show answer and explanation
Answer: Network latency and ambiguous timeouts can hold locks and connections for a long time. Commit a bounded reservation first, call the provider through a durable workflow, and confirm only if the hold is still valid.
Transfer to a new scenario
Acquire a reservation with a conditional update and keep transaction duration short.
Why can increasing serverless concurrency reduce successful database throughput?
Primary documentation
Read the first-party engineering account or official technical reference. Company engineering posts describe the scope and date of that publication; the interview reconstruction and scenarios here are original teaching examples.
Use transactions to enforce a business rule
For a reservation, one transaction can update a resource and insert its ownership record. A unique constraint is stronger than checking existence in application code before inserting. A conditional update can enforce available >= quantity without exposing a read/write race. Keep the transaction short and choose indexes that let it find the intended rows quickly.
MVCC lets readers observe a snapshot while writers create new row versions. Isolation levels define what anomalies remain possible; a transaction does not automatically imply serializable behavior. Serializable transactions may abort and need a bounded retry of the whole transaction. Locks, dead rows and long-running snapshots can create operational pressure even when query volume is modest.
Connection pooling limits concurrent database sessions; it does not make arbitrary parallel application work cheap. A thousand serverless invocations each opening ten connections can exhaust a database rapidly. Budget active transactions, statement timeouts and pool wait separately. Read replicas can offload acceptable-stale queries, but recent-write reads and ownership decisions need an appropriate authority.
Read the diagram
Tool / Use / Caution; Unique constraint / One identity per business key / Handle conflict explicitly; Row lock / Serialize conflicting updates / Keep transaction short; Serializable isolation / Protect suitable multi-row invariants / Retry aborted transactions; Read replica / Tolerant read scale / Lag is not correctness authority
Operational sketch
BEGIN;
UPDATE inventory SET available=available-1
WHERE sku=$1 AND available>=1 RETURNING sku;
-- require one returned row
INSERT INTO reservations(id,sku,state) VALUES($2,$1,'held');
COMMIT;A tempting mistake
Never hold row locks while waiting on a remote payment API. Persist a workflow state, commit, then make the remote call with a stable identity and reconcile its result.
Transfer exercise
Why can a unique constraint still be needed when application code checks for duplicates?
Show answer and explanation
Answer: Two concurrent requests can both pass the check before either inserts. The constraint adjudicates the conflict at the authoritative write boundary.
Shared foundation: Transactions and Isolation
Transactions and Isolation: Predict write skew, enforce a shared invariant and retry whole transactions safely. Work its failure history before extending this design.