PostgreSQL
PostgreSQL (usually just "Postgres") is an open-source relational database. It stores data in tables with a fixed schema, lets you query it with SQL, and wraps changes in ACID transactions. It has been under active development for over 30 years, and it's the database most teams reach for first when they don't have a specific reason to pick something else.
A few properties are worth separating:
- Relational and transactional: Data lives in tables linked by keys, and any group of reads and writes can be wrapped in a transaction that commits or rolls back as one unit. Constraints (primary keys, unique, foreign keys,
CHECK) are enforced by the database, not by your code. - Single primary: One server accepts writes. Replicas can serve reads, but a stock Postgres deployment doesn't spread writes across machines. This is the most important limit to understand.
- Extensible: Postgres has a rich type system (JSONB, arrays, ranges, full-text search) and an extension mechanism that adds whole new capabilities: PostGIS for geospatial queries, pgvector for embeddings, Citus for sharding, TimescaleDB for time series.
In interviews, Postgres is the safe answer for anything with relationships, money, inventory or bookings: anywhere correctness matters more than raw write throughput. Interviewers rarely want to hear about Postgres internals for their own sake. They want to know that you understand what it guarantees, how far one box goes, and what you'll do when you outgrow it. That's what we'll cover.
The Data Model
Postgres organizes data as databases containing schemas (namespaces) containing tables. Each table has typed columns, and each row is a tuple. Relationships are expressed with foreign keys and joined at query time.
CREATE TABLE users (
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
email TEXT NOT NULL UNIQUE,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE TABLE orders (
id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
user_id BIGINT NOT NULL REFERENCES users(id),
status TEXT NOT NULL CHECK (status IN ('pending', 'paid', 'shipped')),
total_cents BIGINT NOT NULL CHECK (total_cents >= 0),
metadata JSONB NOT NULL DEFAULT '{}'
);
CREATE INDEX orders_user_id_idx ON orders (user_id);
The schema does real work here. The database guarantees that no order points at a missing user, that no two users share an email, and that totals are never negative, no matter how many services write to these tables or how buggy one of them is.
The metadata JSONB column shows something that matters in interviews: Postgres isn't strictly "rigid schema." JSONB stores a binary, indexable JSON document in a column. You can query inside it (metadata->>'coupon' = 'SPRING') and index it with a GIN index. A common, sensible design is relational columns for the fields you filter, join and constrain on, plus a JSONB column for the long tail of optional attributes. That often removes the reason people give for choosing a document database.
When you propose Postgres, sketch the two or three core tables and their keys. It takes thirty seconds and makes every later discussion (indexes, sharding key, hot rows) concrete.
Architecture
Postgres runs as a set of operating-system processes on one machine.
- Postmaster and backends: A supervisor process listens for connections and forks one backend process per client connection. That backend parses, plans and executes every query on the connection.
- Shared buffers: A shared memory cache of 8 KB pages, the unit Postgres reads and writes. Postgres also leans on the operating system's page cache, which is why
shared_buffersis typically set to about a quarter of RAM rather than most of it. - Write-ahead log (WAL): An append-only log of every change, written before the change reaches the data files. It's the basis of durability, crash recovery, replication and point-in-time restore.
- Background workers: the checkpointer and background writer (flush dirty pages), the WAL writer, the autovacuum launcher and workers (clean up old row versions), and WAL senders (stream changes to replicas).
Connections Are Expensive
Because each connection is a full process with its own memory (often several MB once it has run a few queries), Postgres doesn't handle thousands of direct connections well. The default max_connections is 100, and most production servers run in the low hundreds. Meanwhile a fleet of 200 app servers with a pool of 20 connections each wants 4,000.
The standard fix is a connection pooler such as PgBouncer (or RDS Proxy on AWS) between the app and the database. In transaction pooling mode, a client only holds a real server connection for the duration of a transaction, so thousands of mostly idle client connections can share a hundred or so server connections.
"We'll put PgBouncer in front of Postgres" is a small detail that signals real experience. It comes up whenever you have many stateless app servers or serverless functions talking to one database. Note the catch: in transaction mode, session state like
SETvariables, advisory session locks and some prepared statement setups don't carry across transactions.
How Writes Work
Let's trace an UPDATE orders SET status = 'paid' WHERE id = 42 inside a transaction.
- The backend finds the row (through the primary key index) and loads its page into shared buffers if it isn't there already.
- It writes a new version of the row into a page, rather than overwriting the old one. More on why below.
- It appends a WAL record describing the change to the in-memory WAL buffer.
- On
COMMIT, the WAL is flushed to disk withfsync. Once that returns, the commit is durable, and the client gets its answer. - The modified data page stays "dirty" in memory. A checkpoint later writes dirty pages to the data files, after which older WAL can be recycled.
The important point is that a commit only waits for a sequential append to the WAL, not for random writes to table and index files. If the server crashes, Postgres replays the WAL from the last checkpoint on startup and recovers every committed transaction. Many small commits flushing concurrently are grouped into a single fsync, which is how one server sustains thousands to tens of thousands of commits per second on good SSDs.
There's a knob worth knowing: synchronous_commit = off lets a commit return before its WAL hits disk. A crash can lose the last fraction of a second of commits (by default up to about three times wal_writer_delay, so roughly 600 ms), but it can't corrupt the database. It's a reasonable choice for data like analytics events and a bad one for payments, and you can set it per transaction.
MVCC: Why Updates Create New Rows
But what is actually happening under the hood? Postgres implements concurrency with multi-version concurrency control (MVCC). Every tuple carries two hidden fields:
xmin: the ID of the transaction that created this version.xmax: the ID of the transaction that deleted or replaced it (empty while it's current).
An UPDATE marks the old tuple's xmax and inserts a new tuple with a fresh xmin. A DELETE just sets xmax. Each query runs against a snapshot: a record of which transactions had committed when the snapshot was taken. A tuple is visible to you if its creator committed before your snapshot and its deleter hadn't.
This buys the property that makes Postgres pleasant under load: readers never block writers, and writers never block readers. A long analytics query and a stream of updates to the same table don't wait on each other. Writers only block other writers that touch the same row.
The cost is garbage. Every update leaves a dead tuple behind, and indexes keep pointing at old versions until they're cleaned. VACUUM (run automatically by autovacuum) reclaims dead tuples once no running transaction can still see them. Three practical consequences follow:
- Update-heavy tables bloat. A counter row updated 1,000 times a second produces 1,000 dead tuples a second. HOT updates (heap-only tuples) help when no indexed column changes and there's room on the same page, since the index doesn't need a new entry. Lowering a table's
fillfactorleaves that room. - Long-running transactions are dangerous. An open transaction (even an idle one someone forgot to commit) holds back the cleanup horizon for the whole database, so dead tuples pile up everywhere.
- Transaction ID wraparound. Transaction IDs are 32-bit. Vacuum must periodically "freeze" old tuples so that IDs can be reused. If it falls far enough behind, Postgres eventually refuses writes to protect data. It's rare on a well-tuned system, but it has caused real multi-hour outages at large companies.
A hot single row, like a global like counter or one inventory row for a flash-sale item, is a bad fit for Postgres for two reasons at once: every update serializes on the row lock, and every update creates a dead tuple. Shard the counter into N rows, or move it to Redis and write back in batches.
How Reads Work
When a query arrives, the planner turns SQL into an execution plan using table statistics (row counts, value distributions, gathered by ANALYZE). It chooses between a sequential scan, an index scan, a bitmap scan or an index-only scan, picks a join order, and chooses join algorithms (nested loop, hash join, merge join). EXPLAIN ANALYZE shows the plan and the real timings.
Indexes
Postgres has more index types than most databases, and picking the right one is a good way to show depth:
| Index | Good for | Example |
|---|---|---|
| B-tree (default) | Equality and range on sortable values | WHERE user_id = 7 ORDER BY created_at DESC |
| Hash | Equality only | Rarely better than B-tree in practice |
| GIN | "Contains" queries over many values per row | JSONB keys, arrays, full-text tsvector |
| GiST | Overlap and nearest-neighbor | PostGIS geometries, ranges, exclusion constraints |
| BRIN | Huge tables naturally ordered on disk | Append-only events filtered by time |
| HNSW / IVFFlat (pgvector) | Approximate nearest-neighbor on vectors | Semantic search over embeddings |
A few features let you shape indexes precisely:
- Composite indexes follow the leftmost-prefix rule: an index on
(user_id, created_at)servesWHERE user_id = ?andWHERE user_id = ? ORDER BY created_at, but notWHERE created_at > ?alone. - Partial indexes index only some rows:
CREATE INDEX ON orders (created_at) WHERE status = 'pending'stays tiny if most orders are shipped. - Expression indexes index a computed value:
ON users (lower(email)). - Covering indexes (
INCLUDE (...)) store extra columns in the index so a query can be answered by an index-only scan without touching the table at all.
Every index speeds up reads and slows down writes, since each insert or non-HOT update must update every index on the table. A table with ten indexes does roughly ten times the index maintenance per write.
Full-Text Search, Geospatial and Vectors
Postgres can stand in for a dedicated search or geo system at moderate scale:
- Full-text search:
tsvectorcolumns, language-aware stemming, ranking withts_rank, and GIN indexes. Fine for searching a few million documents. Elasticsearch is better once you need relevance tuning, fuzzy matching, facets at scale or sharded search over billions of documents. - PostGIS: the reference open-source geospatial engine. "Restaurants within 2 km of this point" is one indexed query with
ST_DWithin. - pgvector: vector columns and approximate nearest-neighbor indexes. Good enough for many RAG and recommendation prototypes with millions of vectors, which keeps embeddings next to the metadata you filter on.
In an interview, "we'll start with Postgres full-text search or PostGIS and move to Elasticsearch or a dedicated geo index if we outgrow it" is often a stronger answer than adding a new system on day one. Just say where the line is.
Transactions and Isolation
Postgres supports the standard isolation levels, though it implements them in its own way:
| Level | What you get in Postgres | Anomalies still possible |
|---|---|---|
| Read Committed (default) | Each statement sees a fresh snapshot | Non-repeatable reads, lost updates with read-modify-write, write skew |
| Repeatable Read | The whole transaction sees one snapshot (snapshot isolation) | Write skew |
| Serializable | Snapshot isolation plus conflict detection (SSI) | None; some transactions abort and must retry |
(Read Uncommitted is accepted but behaves like Read Committed: Postgres never shows uncommitted data.)
Two details stand out. At Repeatable Read, if two transactions update the same row, the second writer waits for the first, and if the first commits, the second fails with a serialization error instead of silently overwriting. And Serializable uses serializable snapshot isolation, which lets transactions run without blocking and aborts one when it detects a dangerous pattern of reads and writes. Your code must catch 40001 serialization failures and retry the whole transaction.
Most applications run at Read Committed and use explicit locking where it matters:
-- Reserve a seat: lock the row so concurrent buyers wait their turn
BEGIN;
SELECT status FROM seats WHERE id = 'A12' FOR UPDATE;
-- application checks status = 'available'
UPDATE seats SET status = 'held', held_by = 123, held_until = now() + interval '10 minutes'
WHERE id = 'A12';
COMMIT;
-- Or, as a single atomic conditional update (no explicit lock needed)
UPDATE seats SET status = 'held', held_by = 123
WHERE id = 'A12' AND status = 'available'; -- 0 rows updated means someone beat you
Postgres has several locking tools beyond FOR UPDATE:
FOR UPDATE NOWAIT: fail immediately instead of waiting for a locked row.FOR UPDATE SKIP LOCKED: skip rows other transactions have locked. This turns a table into a reasonable job queue: each worker runsSELECT ... WHERE status = 'queued' ORDER BY id LIMIT 10 FOR UPDATE SKIP LOCKEDand gets a different batch with no contention.- Advisory locks: application-defined locks on an arbitrary number (
pg_advisory_xact_lock(hashtext('user:42'))), handy for "only one worker processes this account at a time." - Exclusion constraints: with a GiST index, "no two bookings for the same room may have overlapping time ranges" can be enforced by the database itself.
Deadlocks are detected automatically: after deadlock_timeout (1 second by default), Postgres checks for a cycle and aborts one of the transactions.
For more on isolation anomalies, two-phase commit and sagas, see transactions.
Replication and High Availability
Streaming Replication
Physical streaming replication ships the WAL from the primary to one or more standbys, which replay it continuously. Because they replay the exact byte-level changes, standbys are identical copies of the whole cluster, and with hot standby enabled they can serve read-only queries.
Replication is asynchronous by default: the primary commits locally and streams WAL afterwards. Two consequences matter in interviews:
- Replication lag. A replica might be a few milliseconds to several seconds behind (longer under heavy write load or a long-running query on the replica). A user who writes and then immediately reads from a replica may not see their own write. Fixes: read your own writes from the primary for a short window after a write, or route by session, or wait until the replica has replayed past the write's WAL position (LSN).
- Data loss on failover. If the primary dies, anything committed but not yet streamed is lost when a standby is promoted.
Synchronous replication (synchronous_standby_names) makes a commit wait until one or more standbys confirm they have the WAL. You can choose how strong the wait is: flushed to the standby's disk (the default, on), or applied and visible (remote_apply). Synchronous replication gives zero data loss on failover at the price of a network round trip on every commit, so it's usually done to a standby in the same region (a different availability zone), with asynchronous replicas further away.
Failover Isn't Built In
Postgres itself doesn't detect a dead primary or promote a standby. Something outside has to:
- Managed services (Amazon RDS Multi-AZ, Aurora, Cloud SQL, Azure) handle it for you, typically in tens of seconds to a couple of minutes.
- Patroni is the common self-managed choice. Each node runs an agent that holds a leader lease in a consistent store (etcd, ZooKeeper or Consul). If the primary's agent stops renewing, the agents elect the most up-to-date standby and promote it, and the others follow the new primary. The lease prevents two primaries.
Clients find the current primary through a DNS name, a virtual IP, or a proxy (HAProxy, PgBouncer) that the failover tooling updates.
Logical Replication and CDC
Logical replication sends row-level changes (insert this row, update that one) rather than WAL bytes. It's used to replicate a subset of tables, to replicate between different major versions (for low-downtime upgrades), and above all for change data capture. Tools like Debezium read changes from a replication slot and publish them to Kafka, which feeds search indexes, caches, analytics and other services.
This is the clean way to keep Elasticsearch or a cache in sync with Postgres without dual writes, and it's the backbone of the transactional outbox pattern: write the business row and an outbox row in one transaction, and let CDC publish the outbox row as an event.
Replication slots hold WAL until the consumer has read it. If a CDC consumer stops, WAL piles up on the primary until the disk fills. Mention monitoring slot lag (or setting
max_slot_wal_keep_size) when you put CDC in a design.
Scaling Postgres
Scaling Postgres is a ladder. Climb only as far as your numbers require, and say which rung you're on.
1. Vertical scaling and tuning. A single modern server with dozens of cores, hundreds of GB of RAM and NVMe storage handles a lot: tables with billions of rows, multiple TB of data, and on the order of tens of thousands of write transactions and well over a hundred thousand simple indexed reads per second, depending heavily on the workload. Most products never outgrow this, especially with good indexes and a pooler.
2. Caching. Put Redis in front of hot, read-heavy data (profiles, product pages). This often removes the majority of read load.
3. Read replicas. Add standbys and route read-only queries to them. This scales reads nearly linearly, but not writes, and you must handle replication lag.
4. Partitioning. Declarative partitioning splits one logical table into child tables by range, list or hash:
CREATE TABLE events (
id BIGINT, user_id BIGINT, created_at TIMESTAMPTZ NOT NULL, payload JSONB
) PARTITION BY RANGE (created_at);
CREATE TABLE events_2026_11 PARTITION OF events
FOR VALUES FROM ('2026-11-01') TO ('2026-12-01');
Queries filtered on created_at touch only the relevant partitions (partition pruning), each partition has smaller indexes, and dropping a month of old data is an instant DROP TABLE instead of a huge DELETE that bloats the table. Partitioning is all on one server, so it helps manageability and query speed, not write capacity.
5. Sharding. When one primary can't take the write load or hold the data, split rows across multiple independent Postgres clusters by a shard key (user ID, tenant ID). Options:
- Application-level sharding: the app maps a key to a shard (often through a lookup table or consistent hashing over many logical shards) and talks to that shard directly.
- Citus: an extension that distributes tables across worker nodes by a distribution column, routes single-shard queries, and runs multi-shard queries in parallel.
- Distributed SQL databases that speak the Postgres protocol, like CockroachDB, YugabyteDB or Google Spanner's Postgres interface, built from the ground up to shard and replicate with consensus.
Sharding costs you cross-shard joins, cross-shard transactions and global unique constraints, so pick a shard key that keeps each request inside one shard. For a multi-tenant SaaS app, that's almost always the tenant ID.
A strong interview answer does the arithmetic before reaching for sharding. "We expect 2,000 writes per second and 5 TB after three years. One Postgres primary with a replica handles that comfortably, so we won't shard, but we'll key everything by
tenant_idso we can move to Citus later." That's better than sharding a system that doesn't need it.
Notable Features
A few more features make Postgres a Swiss Army knife:
- Upserts:
INSERT ... ON CONFLICT (key) DO UPDATEperforms an atomic insert-or-update, which makes idempotent writes easy: store an idempotency key with a unique constraint andON CONFLICT DO NOTHING. RETURNING: get the inserted or updated row back without a second query.- CTEs and window functions: rankings, running totals and "top N per group" in plain SQL.
- LISTEN/NOTIFY: lightweight pub/sub between database sessions. Useful for "wake up a worker when a job is inserted," but it isn't durable, so don't build a message bus on it.
- Row-level security: policies that restrict which rows a role can see, used for multi-tenant isolation.
- Foreign data wrappers: query another Postgres, MySQL or even a CSV file as if it were a local table.
- Point-in-time recovery: a base backup plus archived WAL lets you restore to any moment, for example to just before someone ran a bad
DELETE.
PostgreSQL in an Interview
When to Use It
Postgres is a good default for:
- Core business data with relationships: users, orders, products, accounts, permissions.
- Anything needing strong consistency and transactions: payments, ledgers, inventory, bookings, seat reservations. Constraints and row locks give you correctness that eventually consistent stores make you build by hand.
- Moderate-scale everything: up to a few TB and thousands of writes per second, which covers most of the systems you'll be asked to design once you do the math.
- Mixed workloads: one system that handles transactions, flexible JSON attributes, geo queries, basic search and vector similarity until one of them needs a dedicated system.
Knowing Its Limitations
- Writes don't scale out. One primary takes every write. Past what one big machine can do, you shard, and Postgres doesn't do that for you.
- Connections are heavyweight. You need a pooler with many app servers or serverless clients.
- MVCC needs maintenance. Update-heavy workloads cause bloat, long transactions block cleanup, and autovacuum must keep up.
- Failover is external. Use a managed service or Patroni, and expect some seconds of write unavailability during failover.
- Not built for some access patterns. Massive append-only time series, petabyte analytics, high-cardinality counters and global multi-region writes are better served by Cassandra, a columnar warehouse, Redis or a distributed SQL database respectively.
Questions You Might Get
- "Why Postgres and not DynamoDB or Cassandra?" Talk about the access patterns: if you need joins, ad-hoc queries, multi-row transactions or constraints, Postgres. If the access pattern is a known key lookup at massive scale with simple consistency needs, a key-value or wide-column store. Then give the throughput numbers that make your choice safe.
- "Two users try to book the last seat at the same time. What happens?" A conditional
UPDATE ... WHERE status = 'available'orSELECT ... FOR UPDATEmakes one of them win and the other see zero rows updated or wait, then find the seat taken. - "How do you scale reads?" Cache first, then read replicas, and explain how you handle replication lag for read-your-writes.
- "The primary dies. What happens?" The HA tooling promotes a standby, clients reconnect through the updated endpoint, and with asynchronous replication the last moments of commits may be lost; with synchronous replication to a same-region standby, none are.
- "How would you add a column to a 2 TB table without downtime?" Adding a nullable column, or one with a constant default (Postgres 11+), is a fast metadata change. Backfill computed values in small batches, then add constraints with
NOT VALIDand validate them separately. Create indexes withCREATE INDEX CONCURRENTLY.
Summary
Postgres is a single-primary relational database that gives you SQL, constraints and real ACID transactions. Commits are durable once a sequential WAL append reaches disk. MVCC keeps multiple row versions so readers and writers don't block each other, at the cost of vacuum work. Indexes go well beyond B-trees, with GIN, GiST, BRIN and pgvector covering JSON, search, geo and vectors.
It scales reads with caching and replicas and manages large tables with partitioning, but write scaling past one machine means sharding, through application logic, Citus or a distributed SQL database. In an interview, Postgres is the right default whenever correctness and relationships matter. Back the choice with numbers, know where the single-primary ceiling is, and have a plan for when you reach it.