Skip to content

PostgreSQL in Practice

Intermediate 63 min read Part 15 of 18

PostgreSQL in practice: MVCC and WAL, index types, JSONB, extensions, replication, partitioning, connection pooling, and when Postgres is enough.

Summary#

PostgreSQL ("Postgres") is an open-source relational database. It combines strict ACID transactions with an unusually rich feature set: many index types, JSONB documents, full-text search, geospatial queries through PostGIS, and vector search through pgvector. Extensions add almost anything else. One well-tuned primary on modern hardware handles thousands to tens of thousands of writes per second, with read replicas and connection pooling multiplying read capacity. Partitioning keeps huge tables manageable. In system design, Postgres is the sensible default for most products until a specific limit is hit: write throughput beyond one machine, a truly global active-active footprint, or search and analytics workloads a specialised engine does better. Knowing exactly where those limits sit is what interviewers probe.

Why It Exists#

Postgres descends from the POSTGRES research project at UC Berkeley, led by Michael Stonebraker from 1986. "The Design of POSTGRES" (Stonebraker and Rowe, SIGMOD 1986) set out goals that still define it: user-defined types, extensibility, and rules, on top of a relational core. The project added SQL in the mid-1990s, and became PostgreSQL in 1996. Stonebraker received the 2014 Turing Award, partly for this line of work.

Three properties explain why it became the default relational database for many new systems:

  1. Correctness first. Real transactions, serializable isolation, constraints (foreign keys, unique, check, exclusion), and a crash-safe write-ahead log. Data is not silently truncated or coerced.
  2. Extensibility. Types, operators, index methods, functions in many languages, foreign data wrappers, and whole extensions (PostGIS, TimescaleDB, Citus, pgvector) plug into the server. One database can serve relational, document, geospatial, time-series, search and vector workloads.
  3. A liberal licence and a vendor-neutral community. The PostgreSQL licence is permissive, BSD-like, and no single company owns the project. Every major cloud offers managed Postgres (Amazon RDS and Aurora, Google Cloud SQL and AlloyDB, Azure Database for PostgreSQL), and several companies build Postgres-compatible systems.

Postgres has topped Stack Overflow's developer survey as the most used or most admired database for several recent years. Companies from Instagram and Reddit to Notion and Figma have run core products on it. Commentators have described Postgres as "eating the database world": instead of adding a separate document store, search engine, queue and vector database, many teams now start with Postgres plus extensions, and split out a specialised system only when a measured limit demands it.

What problem does it solve in a design? It gives you a single, strongly consistent source of truth for data with relationships. Users, orders, payments, inventory, permissions: data that needs joins, constraints and multi-row atomic changes.

How It Works#

Architecture and data model#

Postgres uses a process-per-connection model. A supervisor process (the postmaster) listens on port 5432 and forks one backend process per client connection. Backends share a large memory area:

  • shared buffers, the page cache for table and index pages, typically sized to about 25% of RAM, with the OS page cache holding much of the rest;
  • WAL buffers;
  • lock tables.

Background processes do the housekeeping:

  • the WAL writer flushes the write-ahead log;
  • the checkpointer periodically writes dirty pages to data files;
  • the background writer smooths those writes;
  • the autovacuum launcher and workers reclaim dead row versions;
  • WAL senders stream the log to replicas;
  • the stats collector functions (in shared memory since PostgreSQL 15) track activity.

On disk, each table is a heap: a file (split into 1 GB segments) of 8 KB pages, holding rows ("tuples") in no particular order. Each index is a separate file of 8 KB pages, pointing to tuples by TID, a (page, slot) pair. Large values are moved out of line into a TOAST table, and compressed (more on this under JSONB). The WAL lives in its own directory as a sequence of 16 MB segment files.

Let's use a growing social platform as the running example. Users create posts, comment on posts, follow each other, like posts and comments, and exchange direct messages. The requirements map neatly onto what Postgres does well:

  • Atomic multi-step operations. Creating a DM thread inserts the thread, its participants and the first message together, or not at all.
  • Referential integrity. A comment must reference an existing post. A follow must reference two existing users. Foreign keys enforce this in the database, not in hopeful application code.
  • Mixed consistency. Like counts can lag by a few seconds, while a DM thread cannot be half-created.
  • Efficient reads by access pattern. "Recent posts by user X" needs an index on (user_id, created_at).
  • Search over posts and users.
  • Growth: more rows, more queries, and eventually more machines.

Direct messages form a separate cluster of tables, written together in one transaction:

A few modelling choices are already Postgres-specific:

  • bigint identity keys, since int overflows at about 2.1 billion;
  • timestamptz for all times;
  • a jsonb column for loosely structured user settings;
  • a generated tsvector column for full-text search;
  • composite primary keys on follows and likes, so the uniqueness rule ("you can like a post once") is enforced by the index itself.

The general modelling discipline lives in Data Modeling. Here we focus on what Postgres does with it.

MVCC and the write-ahead log#

Two mechanisms explain most of Postgres's behaviour, both good and bad: multi-version concurrency control (MVCC) and the write-ahead log (WAL).

MVCC: readers never block writers. Postgres never overwrites a row in place. An UPDATE writes a new tuple version, and marks the old one as expired. A DELETE only marks a tuple as expired. Each tuple header carries:

  • xmin: the ID of the transaction that created this version;
  • xmax: the ID of the transaction that deleted or replaced it, or zero if it's still live.

When a transaction (or, under Read Committed, each statement) starts, it takes a snapshot: the set of transactions that had committed at that moment. A tuple is visible if its xmin committed before the snapshot, and its xmax is empty or not yet committed in that snapshot. So a long analytical SELECT sees a consistent picture, while writers keep changing rows, and neither waits for the other. Writers do block other writers on the same row, using row-level locks recorded in the tuple header. The isolation-level theory is in ACID and Isolation Levels. Postgres's specific choices are covered under transactions, below.

The price of MVCC is dead tuples. Old versions stay in the heap until no running snapshot can need them. VACUUM (run automatically by autovacuum) removes them, records free space in the free space map, and updates the visibility map, a bit per page meaning "all tuples here are visible to everyone", which enables index-only scans. If vacuum falls behind (because of long-running transactions, an abandoned replication slot, or autovacuum settings too timid for a busy table), tables and indexes bloat. Scans touch more pages, caches hold less useful data, and performance degrades slowly.

WAL: durability and replication from one log. Before any change to a data page reaches disk, a WAL record describing it is appended to the log. On COMMIT, Postgres flushes the WAL up to the commit record with fsync. That single sequential write makes the transaction durable. The modified data pages can be written later, lazily, by the checkpointer. After a crash, recovery starts from the last checkpoint, and replays WAL forward, redoing every change. The same WAL stream is what streaming replication ships to replicas, what point-in-time recovery archives, and what logical decoding turns into row-level change events for Change Data Capture. The general idea of a log-first storage engine is in Storage Engines.

MVCC and WAL, in depth: HOT updates, wraparound, checkpoints and commit settings#

Heap-only tuple (HOT) updates. Because an update creates a new tuple at a new TID, every index on the table would normally need a new entry pointing to it. That's index write amplification. Postgres avoids this with HOT updates (since 8.3). If no indexed column changed, and the new version fits on the same page, the old tuple simply points to the new one, and no index is touched. To keep HOT updates possible, leave free space on pages with a fillfactor below 100 (for example, 80–90 on heavily updated tables), and avoid indexing frequently updated columns such as like_count or last_seen_at. Monitor this with n_tup_hot_upd versus n_tup_upd in pg_stat_user_tables. A low HOT ratio on a hot table is a red flag.

Transaction ID wraparound. Transaction IDs are 32-bit counters compared with modular arithmetic: about 2 billion IDs are "in the past", and 2 billion are "in the future". A tuple whose xmin is older than about 2 billion transactions would suddenly appear to be in the future, and vanish. To prevent this, vacuum freezes old tuples, marking them as visible to everyone forever. Autovacuum triggers aggressive anti-wraparound vacuums as a table's oldest unfrozen ID approaches autovacuum_freeze_max_age (200 million by default). If freezing still can't keep up, Postgres eventually refuses new transactions to protect data, which is a full write outage until a manual vacuum completes. Busy systems have suffered exactly this. Sentry published a detailed account of a wraparound outage in 2015, and Mailchimp's Mandrill had a long outage in 2019 attributed to wraparound. The lesson: monitor age(datfrozenxid), never let long transactions or stale replication slots block vacuum, and tune autovacuum for large, hot tables. A rate of 10,000 write transactions per second consumes 200 million IDs in about 5.5 hours, so freezing is a continuous background job for busy databases, not a rare event. (Postgres 14 added a failsafe that makes vacuum skip non-essential work when wraparound is near.)

Checkpoints and full-page writes. A checkpoint flushes all dirty pages, so recovery need only replay WAL written after it. Frequent checkpoints shorten recovery, but cause write bursts. They also increase WAL volume, because of full-page writes: the first time a page is modified after a checkpoint, the whole 8 KB page image goes into WAL, to protect against torn pages (a partial page write during a crash). Typical tuning is a checkpoint_timeout of 15 minutes or more, and a max_wal_size large enough that checkpoints are time-driven rather than size-driven, with checkpoint_completion_target around 0.9 to spread the I/O. A sudden spike in WAL volume right after each checkpoint is the full-page-write signature.

Commit durability is tunable per transaction. synchronous_commit controls what COMMIT waits for:

SettingCOMMIT waits forRisk on crash
offnothing; WAL flushed within about 3× wal_writer_delay (default 200 ms)Lose the last fraction of a second of commits, but no corruption
locallocal WAL flush onlyDurable locally; a replica may lag
remote_writestandby received WAL and wrote it to its OSStandby OS crash could lose it
on (default)local flush plus, if synchronous standbys are configured, standby flushDurable on both
remote_applystandby has replayed the changeRead-your-writes on that standby

You can set synchronous_commit = off for just the transactions that tolerate a tiny loss, such as analytics events and like counters, while payments keep the default. That's per-transaction durability, which few databases offer so cleanly.

Group commit. One fsync can make many concurrent transactions durable at once, because their commit records are adjacent in the WAL. On NVMe with power-loss protection, a flush takes tens to hundreds of microseconds. With group commit, a single primary can sustain thousands to tens of thousands of commits per second, the canonical range in Numbers to Know. Settings such as commit_delay trade a little latency for larger groups.

Index types: B-tree, Hash, GIN, GiST, SP-GiST and BRIN#

Without an index, finding "all posts by user 7" means a sequential scan, reading every page of the heap. An index is a separate structure that leads straight to the matching tuples. The general theory is in Database Indexing. Postgres's distinctive strength is that it ships six index access methods, and lets extensions add more.

B-tree (the default). A balanced tree of 8 KB pages, holding sorted keys. Use it for:

  • equality: WHERE email = 'a@b.com';
  • ranges: WHERE created_at > now() - interval '7 days';
  • prefix LIKE 'abc%', given the right operator class or the C collation;
  • sorting: ORDER BY created_at DESC LIMIT 20, which can read the index in order and stop early;
  • uniqueness: primary keys and UNIQUE constraints automatically create B-trees.

CREATE TABLE users (id bigint PRIMARY KEY, email text UNIQUE) produces two B-trees without being asked. B-trees are the right answer for more than 90% of indexes.

Hash. Equality only, with no ordering. Hash indexes have been crash-safe and WAL-logged since Postgres 10. They're occasionally smaller and faster than a B-tree for long keys used only in = lookups (say, a long URL or token). In practice they're rarely needed, because a B-tree handles equality nearly as well, and also supports ranges and sorting.

GIN (Generalised Inverted Index). Maps each element inside a value to the rows containing it. That's an inverted index, the same idea that powers search engines. Use it for:

  • full-text search over tsvector columns;
  • JSONB containment (settings @> '{"theme":"dark"}') and key existence;
  • arrays (tags @> ARRAY['postgres']);
  • trigram similarity via pg_trgm, for LIKE '%term%' and fuzzy matching.

GIN lookups are fast, but writes are expensive, because one row may add dozens of index entries. GIN mitigates this with a pending list (fastupdate), which buffers new entries and merges them in bulk. That makes inserts cheaper, but searches must also scan the pending list until it's flushed.

GiST (Generalised Search Tree). A framework for balanced trees over data that can be described by "bounding" predicates rather than total order. It powers:

  • geometry and geography in PostGIS (an R-tree-like structure);
  • range types (tsrange, int4range), with overlap queries;
  • nearest-neighbour ordering (ORDER BY location <-> point LIMIT 10);
  • exclusion constraints. "No two bookings for the same room may have overlapping time ranges" is a single declarative constraint: EXCLUDE USING gist (room_id WITH =, during WITH &&). It's a beautiful tool for booking systems (Ticket Booking).

SP-GiST (space-partitioned GiST). For non-balanced, space-partitioning structures: quadtrees, k-d trees and radix tries. Useful for points with uneven distribution, IP ranges, and text prefixes. Compare with the geospatial structures in Geospatial Indexing.

BRIN (Block Range INdex). Instead of indexing every row, BRIN stores a summary per range of pages (128 pages, about 1 MB, by default), such as the min and max of created_at in that range. A query for last Tuesday skips every block range whose min–max doesn't overlap. BRIN indexes are tiny: kilobytes or megabytes for a terabyte table, versus gigabytes for a B-tree. But they only work well when the column's values are physically correlated with insertion order: append-only events, logs, time-series. For randomly ordered values, BRIN prunes nothing.

Index features that matter as much as type.

  • Multi-column (composite) indexes: (user_id, created_at) serves "posts by user, newest first". Column order matters: the index helps queries that constrain the leading column(s). It can't efficiently serve WHERE created_at > X alone. (Postgres 18 added B-tree skip scan, which helps some queries that omit a low-cardinality leading column, but don't design around it.)
  • Partial indexes: CREATE INDEX ... ON orders (created_at) WHERE status = 'pending' indexes only the 1% of rows you query, so it's small, hot in cache, and cheap to maintain.
  • Expression indexes: ON users (lower(email)), so case-insensitive lookups use an index.
  • Covering indexes and index-only scans: CREATE INDEX ... ON posts (user_id, created_at) INCLUDE (title) (since Postgres 11) lets the query be answered from the index alone, if the visibility map says those heap pages are all-visible. That's another reason vacuum matters.
  • Building without downtime: a plain CREATE INDEX blocks writes to the table for the duration. CREATE INDEX CONCURRENTLY builds without blocking writes (slower, and it must be retried if it fails). Always use it on live production tables.

Indexes are not free. Each index:

  • slows every insert, and every non-HOT update;
  • consumes disk and cache, sometimes nearly as much as the table;
  • may never be used, if the planner judges a sequential scan cheaper (for example, when a query returns 30% of the table).

"Index every column" is a classic interview mistake. Index for your known query patterns, and check pg_stat_user_indexes.idx_scan periodically to drop unused indexes.

Indexes, in depth: B-tree maths, planner statistics and query optimisation#

Why B-trees are shallow. An 8 KB page holds a few hundred index entries for bigint keys, depending on key size and fill. With a fanout of about 300:

  • 3 levels index 300³, about 27 million rows;
  • 4 levels index about 8 billion.

The root and inner levels are tiny, and stay cached in shared buffers, so a point lookup typically costs one or two page reads from storage (leaf, plus heap page). With everything cached, it costs microseconds of CPU. That's why "an indexed read takes about 1–5 ms end to end" is mostly network and protocol overhead, not the tree. Recent versions shrank B-trees further:

  • Postgres 13 added deduplication (one key, many TIDs), which is great for low-cardinality columns;
  • Postgres 14 added bottom-up deletion, which removes version churn from the index before a page split.

Random UUIDv4 primary keys scatter inserts across all leaf pages, increasing page splits, WAL (more full-page writes) and cache misses. Time-ordered keys (bigint identities, or UUIDv7, which has a built-in uuidv7() function in Postgres 18) insert at the right edge, and stay cache-friendly (Unique ID Generation).

How the planner chooses. Postgres has a cost-based optimiser. ANALYZE (run by autovacuum) samples each column to build statistics:

  • the number of distinct values;
  • the most common values and their frequencies;
  • histograms;
  • the correlation between value order and physical order.

From these, it estimates the selectivity of each predicate, and picks among the plans available:

  • a sequential scan;
  • an index scan (walk the index, fetch each heap tuple: good for a few rows);
  • a bitmap index scan plus bitmap heap scan (collect matching TIDs, sort by page, read each heap page once: good for thousands of rows, and for combining several indexes with AND and OR);
  • an index-only scan.

For joins, it chooses among nested loop, hash join and merge join, and decides the join order. Bad plans usually come from bad estimates:

  • correlated columns (city and zip code) multiply selectivities wrongly. Fix this with CREATE STATISTICS (extended statistics);
  • stale statistics after bulk loads. Run ANALYZE;
  • functions over columns that have no expression index.

Query optimisation essentials (what you need in practice, and in interviews):

  1. Find the expensive queries first. The pg_stat_statements extension aggregates total time, calls, mean time and rows per normalised query. Sort by total time. The top 10 queries usually account for most of the load.
  2. Read EXPLAIN (ANALYZE, BUFFERS). Compare estimated with actual rows (a big mismatch means bad statistics), look for sequential scans on large tables in OLTP paths, check buffer reads (shared hit vs read), and look for sorts spilling to disk (raise work_mem for that query, or add an index that provides the order).
  3. Fix access patterns, not just indexes:
    • avoid N+1 query loops from ORMs; batch with WHERE id = ANY($1) or joins;
    • avoid SELECT * when you need three columns;
    • use keyset pagination (WHERE (created_at, id) < ($1, $2) ORDER BY created_at DESC, id DESC LIMIT 20) instead of OFFSET 100000, which must read and discard 100,000 rows.
  4. Keep transactions short. Long transactions hold snapshots that block vacuum, and hold locks that block writers.
  5. Set timeouts: statement_timeout for user-facing queries, idle_in_transaction_session_timeout to kill forgotten sessions, and lock_timeout for migrations, so a schema change doesn't queue behind a long query and block everything behind it.

JSONB: documents inside a relational database#

Postgres has two JSON types:

  • json stores the text as given, and re-parses it on every access;
  • jsonb (since 9.4, 2014) stores a decomposed binary form: keys sorted and de-duplicated, values typed. It's slightly slower to write, much faster to query, and indexable. Use jsonb unless you must preserve exact formatting or key order.

Operators and functions:

  • -> and ->> extract a field (as JSON or as text);
  • #> extracts by path;
  • @> tests containment ("does this document contain this sub-document?");
  • ? tests key existence;
  • jsonb_set and || modify;
  • SQL/JSON path expressions (jsonb_path_query, since Postgres 12) give a richer query language;
  • Postgres 16 and 17 added more SQL-standard JSON functions (JSON_TABLE arrived in 17).

Indexing options:

  • A GIN index with the default jsonb_ops indexes every key and value, and supports @>, ?, ?| and ?&.
  • A GIN index with jsonb_path_ops indexes only hashed paths to values, so it's smaller and faster for @> containment, but doesn't support key-existence operators.
  • Expression B-tree indexes on a single field (CREATE INDEX ON events ((payload->>'user_id'))) are best when you query one known field by equality or range.

When JSONB fits.

  • Attributes that vary by row: product attributes across categories, per-tenant custom fields, user settings, feature flags.
  • Payloads you store and return mostly whole: webhook bodies, audit events, API responses.
  • Fast-evolving schemas early in a product, alongside relational columns for the core fields.

The winning pattern is hybrid: relational columns for identity, foreign keys and anything you filter, join or aggregate on often, and JSONB for the long tail. That gives you most of a document database's flexibility without giving up transactions and joins (SQL vs NoSQL).

When it doesn't.

  • Everything in one JSONB blob. You lose type checking, foreign keys, constraints and column statistics (the planner guesses selectivity for JSON expressions, which often produces bad plans).
  • Frequently updated large documents. Updating one key rewrites the entire value, and with MVCC, a whole new tuple. Large documents also live in TOAST (below), so each update rewrites the TOASTed chunks too.
  • Deeply relational data shoved into nested arrays, such as comments inside a post document. You can't index or join them efficiently, and the document grows without bound.

JSONB, in depth: TOAST, generated columns and validation#

TOAST (The Oversized-Attribute Storage Technique). A tuple must fit in a page. When a row exceeds about 2 KB (TOAST_TUPLE_THRESHOLD), Postgres first compresses large values (pglz, or lz4 since Postgres 14, which is usually faster), and then, if needed, moves them out of line into a TOAST table, in about 2 KB chunks. Consequences:

  • reading a 50 KB JSONB value means fetching and decompressing many chunks;
  • extracting one key still de-TOASTs the whole value;
  • updating one key writes a new full value.

So keep frequently read hot fields in normal columns, and keep JSONB documents modest, ideally a few KB. A common optimisation is to split hot and cold: orders(id, status, total, ...) plus order_details(order_id, payload jsonb).

Generated columns bridge both worlds: ALTER TABLE events ADD COLUMN user_id bigint GENERATED ALWAYS AS ((payload->>'user_id')::bigint) STORED extracts a field into a real, typed, indexable column with statistics. (Postgres 18 adds virtual generated columns, computed on read, which became the default kind.)

Validation. CHECK constraints can enforce shape: CHECK (jsonb_typeof(settings->'notifications') = 'object'). Extensions such as pg_jsonschema validate against JSON Schema. Validation at the database boundary prevents "schemaless" from becoming "every row has a different, slightly broken shape".

Numbers. A GIN jsonb_path_ops index on a 100-million-row events table is typically a sizeable fraction of the table size. Expect insert throughput to drop noticeably, compared with no GIN index, because each insert adds many entries. Pending-list flushes can cause latency spikes during heavy write bursts. If you only ever filter by two fields, two expression B-trees (or two generated columns) are smaller and cheaper than a GIN index over everything.

Extensions: full-text search, PostGIS, pgvector and friends#

An extension is a packaged bundle of types, functions, operators and index methods, installed with CREATE EXTENSION. This is how Postgres grows without forking. Managed services support a curated list. Check that your provider offers the extensions you plan to use.

Full-text search (built in). Postgres turns text into a tsvector: a sorted list of normalised lexemes, with positions. The normalisation:

  • lower-cases words;
  • removes stop words ("the", "a");
  • stems words ("running", "runs" and "ran" may all become "run", depending on the dictionary).

Queries are tsquery expressions with AND, OR, NOT, phrase (<-> adjacency) and prefix matching. A GIN index over the tsvector makes WHERE search_doc @@ websearch_to_tsquery('english', 'taylor swift tour') fast. ts_rank and ts_rank_cd score matches by frequency and proximity, and setweight lets the title outweigh the body.

ALTER TABLE posts ADD COLUMN search_doc tsvector
  GENERATED ALWAYS AS (
    setweight(to_tsvector('english', coalesce(title, '')), 'A') ||
    setweight(to_tsvector('english', coalesce(body, '')), 'B')
  ) STORED;
 
CREATE INDEX CONCURRENTLY posts_search_idx ON posts USING gin (search_doc);
 
SELECT id, title, ts_rank(search_doc, q) AS rank
FROM posts, websearch_to_tsquery('english', 'postgres replication') AS q
WHERE search_doc @@ q
ORDER BY rank DESC
LIMIT 20;

For substring and fuzzy matching ("Taylr" for "Taylor", or ILIKE '%swift%'), the pg_trgm extension indexes three-character grams with GIN or GiST, and provides a similarity() score. That's how a ticketing system can search event names without a full table scan. Postgres full-text search is a great solution for moderate search needs inside one database: product catalogues, event names, internal tools, tens of millions of documents.

When to graduate to Elasticsearch:

  • you need BM25 relevance with field boosting and rich analysers for many languages, synonyms, typo tolerance, faceted aggregations at scale, and "search as you type" over hundreds of millions of documents;
  • search traffic is heavy enough that it should not compete with transactional queries.

Postgres's built-in ranking is not BM25. It lacks corpus-wide statistics such as inverse document frequency. Extensions such as ParadeDB's pg_search add BM25-style ranking inside Postgres. The usual architecture keeps Postgres as the source of truth, and streams changes into the search engine through CDC (Post Search).

PostGIS (geospatial). PostGIS adds:

  • geometry (planar coordinates) and geography (on the spheroid, metres) types;
  • hundreds of spatial functions (ST_DWithin, ST_Contains, ST_Intersects, ST_Distance);
  • GiST-backed R-tree-style indexes;
  • coordinate reference system transforms.

"Find restaurants within 2 km, nearest first" becomes:

WHERE ST_DWithin(location, ST_MakePoint(lon, lat)::geography, 2000)
ORDER BY location <-> ST_MakePoint(lon, lat)::geography
LIMIT 20

That's an index-assisted radius filter, plus KNN ordering. PostGIS is the reference open-source GIS database, used for mapping, logistics and real-estate search. Compared with geohash prefixes in a key-value store, or Redis GEOSEARCH, PostGIS offers exact polygon operations, such as delivery zones, and joins with business data. Its limit is write and read throughput on one primary: for millions of driver location updates per second, an in-memory store is the better fit (Proximity Service, Ride Hailing).

pgvector (vector similarity). pgvector adds:

  • a vector(n) type, plus halfvec (16-bit floats), bit (binary) and sparsevec variants;
  • distance operators: <-> (L2), <=> (cosine distance), <#> (negative inner product);
  • two approximate nearest neighbour (ANN) index types: HNSW (a hierarchical navigable small-world graph, with better recall and latency, but slower builds and more memory) and IVFFlat (inverted lists around k-means centroids, with faster builds and less memory, but needing training data and lower recall at equal speed).

Embeddings live next to the rows they describe, so one SQL query can filter by tenant, permissions and recency, and rank by similarity, with transactional consistency and no sync pipeline. For retrieval-augmented generation (RAG) and recommendations at the scale of up to tens of millions of vectors, this is often the simplest correct design. The details of ANN indexes are in Vector Databases.

Other extensions worth knowing.

ExtensionWhat it addsFits when
pg_stat_statementsPer-query execution statisticsAlways: the first tool for performance work
TimescaleDBHypertables (automatic time partitioning), compression, continuous aggregatesMetrics, IoT and event data that should live in SQL (Time-Series Databases)
CitusDistributed tables sharded across worker nodes, with a coordinatorMulti-tenant SaaS or real-time analytics outgrowing one node
pg_partmanAutomated creation and retention of time or ID partitionsLarge time-partitioned tables
pg_cronCron-style job scheduling inside the databasePeriodic maintenance, rollups, cleanup
postgres_fdwQuery tables in other Postgres servers as if localOccasional cross-database reporting or migrations
pgcryptoHashing and encryption functionsColumn-level crypto when the app can't do it
pg_trgmTrigram similarity, and indexed LIKE '%x%'Fuzzy name and substring search
hstore, ltree, citextKey–value pairs, hierarchical label paths, case-insensitive textTags, category trees, emails

Extensions, in depth: pgvector at scale and the "just use Postgres" debate#

HNSW parameters in pgvector.

  • m is the number of graph neighbours per node (default 16). Higher values give better recall, but a bigger index.
  • ef_construction is the candidate list size during build (default 64). Higher values give a better graph, but slower builds.
  • hnsw.ef_search is the candidate list at query time (default 40). Higher values give better recall, but slower queries.

For 1 million 768-dimension float vectors, the raw data alone is 1M × 768 × 4 bytes, about 3 GB. The HNSW graph adds more, and the whole index should fit in memory for good latency. Quantising to halfvec halves the memory, typically with little recall loss. With binary quantisation (bit), you shortlist with a cheap binary index, then re-rank exactly. Expect single-digit to tens of milliseconds per query at 95%+ recall on adequately sized hardware. Exact numbers depend heavily on dimensions, ef_search and filters, so benchmark your own data.

The filtering problem. ANN indexes return the top k nearest neighbours first, and then Postgres applies WHERE tenant_id = 42. If tenant 42 owns 0.1% of the vectors, the top 40 candidates may contain none of them, and the query returns too few rows. Fixes:

  • pgvector 0.8 added iterative index scans, which keep scanning until enough rows pass the filter;
  • partial indexes or partitions per large tenant;
  • raise ef_search for selective filters;
  • or pre-filter with a B-tree, and compute exact distances when the filtered set is small (say, under 10,000 rows).

Dedicated vector databases implement filter-aware graph traversal natively. That's one reason to move once filters are complex and data is large.

When to leave Postgres for vectors.

  • Hundreds of millions to billions of vectors.
  • Very high query rates that would crowd out transactional work.
  • Index builds that take hours and must happen often.
  • Needing features like hybrid sparse-dense search with tuned fusion, multi-tenancy with thousands of separate indexes, or tiered storage of vectors on disk.

At that point, Milvus, Pinecone, Weaviate, Qdrant, or Elasticsearch and OpenSearch kNN make sense. Keep Postgres as the source of truth for metadata.

"Just use Postgres" as a design principle. The argument for consolidation:

  • one system to operate, secure, back up and monitor;
  • transactional consistency across data types (no dual writes, as in Change Data Capture);
  • one query language;
  • fewer network hops.

Postgres can credibly act as:

  • a job queue, via SELECT ... FOR UPDATE SKIP LOCKED, with tools such as Graphile Worker, Oban (Elixir), river (Go) and pgmq;
  • pub/sub for low volumes, via LISTEN/NOTIFY;
  • a cache, via unlogged tables, though that's rarely wise compared with Redis;
  • a time-series store (TimescaleDB);
  • a search engine (full-text plus pg_trgm);
  • a vector store (pgvector).

The counter-argument is resource contention and blast radius. A runaway search query, a queue table with heavy churn and bloat, or a vector index rebuild competes for the same CPU, memory, I/O and connections as checkout. The pragmatic rule: start consolidated, measure, and split out the workload whose load profile differs most from your OLTP core. Use separate replicas for search-like reads first. Move to a dedicated system when it needs independent scaling or different durability. This is frugal architecture applied to data (Cloud Architecture Essentials).

Replication: streaming and logical#

Replication concepts (leader–follower, synchronous vs asynchronous, lag, failover) are covered in Replication. Postgres offers two concrete mechanisms.

Streaming (physical) replication. The primary's WAL sender streams WAL records to each standby. The standby's startup process replays them, producing a byte-for-byte identical copy of the whole cluster: every database, table, index and catalogue. Properties:

  • Hot standby: standbys serve read-only queries while replaying. That's how read replicas scale reads.
  • Asynchronous by default. The primary commits without waiting, so a standby may lag (usually milliseconds within a region; seconds or more under load, or across regions).
  • Synchronous when synchronous_standby_names is set. The primary waits for one or more standbys to confirm each commit (FIRST 1 (s1, s2) for priority order, or quorum ANY 1 (s1, s2, s3) since Postgres 10). That gives an RPO of zero for those standbys, at the cost of an extra round trip per commit, about 1–2 ms across AZs.
  • Replication slots make the primary keep WAL until each consumer has received it, so a disconnected replica can catch up. But an abandoned slot makes WAL accumulate until the primary's disk fills. Since Postgres 13, max_slot_wal_keep_size caps this.
  • Cascading replication: standbys can feed other standbys, which reduces load on the primary.
  • Physical replication requires the same major version and architecture on both sides. It replicates everything, and you can't choose tables.

Logical replication. Logical decoding turns WAL into a stream of row-level changes (insert, update, delete, with values), through an output plugin such as the built-in pgoutput. A publication on the source lists tables, optionally with row filters and column lists (Postgres 15). A subscription on the target applies the changes. Properties:

  • Works across major versions, so it's the standard path for near-zero-downtime major upgrades (replicate to the new version, cut over).
  • Can replicate a subset of tables, merge many sources into one (consolidation), or fan out to many targets.
  • The target is a normal writable database, with its own indexes.
  • Limitations: DDL (schema changes) is not replicated, sequence values are not replicated (resynchronise them at cutover), and tables generally need a primary key or replica identity for updates and deletes. Large transactions may be streamed before commit (since Postgres 14), but very write-heavy sources can still lag.
  • Logical decoding is also what Debezium and other CDC tools consume, to stream Postgres changes into Kafka, search indexes, caches and warehouses (Change Data Capture, Kafka).

Replication, in depth: high availability, failover and read-your-writes on replicas#

Postgres has no built-in automatic failover. The server provides the mechanisms: promote a standby with pg_promote(), and use pg_rewind to resynchronise an old primary. Deciding when to fail over is left to external tooling:

  • Patroni is the most common open-source choice. Each node runs an agent. A distributed consensus store (etcd, Consul or ZooKeeper) holds a leader key with a TTL. The primary keeps renewing the key. If it fails to, the standbys race to acquire it, and the most up-to-date healthy standby is promoted. The old primary demotes itself when it can't renew the key, which is how split brain is prevented (Leader Election and Coordination).
  • Others include pg_auto_failover, repmgr, and on Kubernetes, CloudNativePG and other operators.
  • Managed services such as RDS Multi-AZ keep a synchronous standby in another AZ and fail over automatically, typically in about one to two minutes, including DNS changes. Newer Multi-AZ cluster deployments with two readable standbys fail over faster.

Applications must handle failover. Connections drop, in-flight transactions fail, and the DNS name or proxy now points to the new primary. Use connection retries with backoff, idempotent writes (Idempotency), and short DNS TTLs, or a proxy (PgBouncer, HAProxy, RDS Proxy) that routes to the current primary.

Choosing synchronous or asynchronous. Asynchronous standbys risk losing the last few hundred milliseconds of commits on failover (RPO above zero). Synchronous standbys give RPO zero, but every commit waits for the standby. And if the only synchronous standby fails, writes stall until it returns or is removed from the list. That's why production setups use quorum (ANY 1 of 2+ standbys), or let the HA tool demote the setting automatically, choosing availability over strict RPO. That choice should be explicit (CAP and PACELC).

Read replicas and stale reads. Routing reads to replicas multiplies read capacity, but a user who just posted may not see the post if their next read hits a replica that's 200 ms behind. Patterns:

  1. Read your own writes from the primary for a short window after a write (sticky routing, say for 5 seconds).
  2. Track LSNs. After a write, record pg_current_wal_lsn(). Before reading from a replica, check that pg_last_wal_replay_lsn() is at least that value, or wait briefly.
  3. Use synchronous_commit = remote_apply for the rare writes that must be visible on a specific standby immediately.
  4. Route by consistency need. GoPuff-style availability checks tolerate slight staleness and read from replicas, while orders and inventory decrements go to the primary in a transaction.

Replica query conflicts. A long query on a hot standby may need row versions that the primary has already vacuumed away. When that WAL arrives, the standby must either delay replay (raising lag) or cancel the query. That's the error "canceling statement due to conflict with recovery". The settings max_standby_streaming_delay and hot_standby_feedback trade replica freshness, query safety and primary bloat (feedback stops the primary vacuuming rows the standby still needs). Use a dedicated replica, with relaxed settings, for analytics.

Aurora and other cloud-native variants. Amazon Aurora PostgreSQL keeps the Postgres query layer, but replaces local storage with a distributed, log-structured storage service. Each write is replicated as six copies across three AZs, with a 4-of-6 write quorum and a 3-of-6 read quorum, as described in "Amazon Aurora: Design Considerations for High Throughput Cloud-Native Relational Databases" (Verbitski et al., SIGMOD 2017). Replicas share the storage volume, so replica lag is typically tens of milliseconds, and adding a replica doesn't copy data. Similar ideas, separating compute from storage, appear in Google AlloyDB and Neon. Neon's design adds branching and scale to zero. These change the replication and failover story, but not the single-writer model, MVCC, or how you design queries.

Backups and point-in-time recovery (PITR). Replicas are not backups: a DROP TABLE replicates instantly. Take periodic base backups (with pg_basebackup, pgBackRest, Barman or WAL-G), and continuously archive WAL to object storage. To recover to "14:32:05, just before the bad migration", restore the base backup, then replay archived WAL up to that timestamp. Postgres 17 added incremental base backups. Test restores regularly. In January 2017, GitLab accidentally deleted the data directory on its primary during an incident, and found that several backup mechanisms were not working. It restored from a staging snapshot about six hours old. The lesson is to test restores, not just backups (Disaster Recovery).

Write performance, scaling limits and partitioning#

Where write throughput comes from, and where it stops. Every write in Postgres goes to one primary. The primary must:

  • append WAL, and flush it on commit;
  • update the heap (a new tuple version);
  • update every affected index;
  • later, vacuum the dead version and checkpoint the dirty pages.

On a modern server with NVMe storage, a single primary commonly sustains about 5,000–20,000 write transactions per second for typical OLTP transactions touching a few rows and indexes. Simple inserts, batched, can push considerably higher. Heavily indexed rows, large rows, or contended rows push lower. Reads scale further: one primary can serve tens of thousands of cached point lookups per second, and each replica adds similar capacity.

The practical ceilings, roughly in the order teams hit them:

  1. Connection count (process per connection; see below). The issue is often hundreds of idle connections, not throughput.
  2. Hot rows. Many transactions updating the same row (a global counter, a popular item's stock) serialise on its row lock. Throughput on that row is bounded by lock hold time: about 1,000 or more updates per second if each transaction is about 1 ms, and much less with network round trips inside the transaction.
  3. Write amplification: index count, full-page writes, and non-HOT updates. A table with 8 indexes does roughly 9 writes per insert.
  4. Vacuum throughput on large, heavily updated tables. Bloat and wraparound pressure grow with update volume.
  5. WAL volume and replication bandwidth. Hundreds of MB per second of WAL stress replicas and cross-region links.
  6. Single-machine size. Storage of tens of terabytes per instance works, but backups, restores, rebuilds and major-version upgrades take hours to days. The pain is operational before it's a hard limit.

Write optimisations, in roughly increasing effort.

  • Batch: multi-row INSERT ... VALUES (...), (...), or COPY, which is often 10× or more faster than row-by-row inserts in separate transactions, because it amortises round trips, parsing and commits.
  • Fewer, leaner indexes; partial indexes; drop unused ones.
  • Keep HOT updates possible: fillfactor, and avoid indexing churny columns.
  • Relaxed durability where acceptable: synchronous_commit = off per transaction. Unlogged tables skip WAL entirely, so they're fast, but they're truncated on crash and not replicated. They suit scratch and staging data only.
  • Move contention out of the row: sharded counters, append-only "like events" aggregated asynchronously, or keep hot counters in Redis and flush them periodically.
  • Buffer writes through a queue (Message Queues), so bursts are smoothed, and writes can be batched by consumers (Scaling Writes).
  • Partition large tables (below), then shard across machines when one primary is no longer enough.
  • Scale up first. Moving to a larger instance with more cores, more RAM and faster NVMe often buys 2–4× with no code change (Vertical vs Horizontal Scaling).

Declarative partitioning (single node). Since Postgres 10, a table can be declared PARTITION BY RANGE, LIST or HASH, with child tables holding the rows. Benefits:

  • Partition pruning. A query with WHERE created_at >= '2026-11-01' only touches matching partitions, both at planning time and at execution time.
  • Cheap retention. Dropping a month of data is DETACH PARTITION plus DROP TABLE, which takes milliseconds. Compare that with a DELETE of 500 million rows, which creates massive bloat and WAL.
  • Smaller indexes per partition, which fit in memory. Vacuum works partition by partition.
  • Hot and cold separation. Old partitions can live on cheaper tablespaces, or be archived.

Constraints and costs:

  • a primary key or unique constraint must include the partition key;
  • queries that can't prune (no partition key in WHERE) scan all partitions;
  • thousands of partitions inflate planning time and memory (keep it to hundreds to low thousands, sized so each partition is perhaps tens of GB);
  • partition creation must be automated (pg_partman, or a scheduled job).

Common schemes:

  • range by time for events, logs, messages and orders;
  • list by region or tenant tier (the GoPuff-style design partitions inventory by a region ID derived from the zip-code prefix, so a nearby-availability query touches one or two partitions);
  • hash by ID to spread a hot table evenly.

Sharding (multiple nodes). When one primary can't handle the writes or the data, split the data across multiple Postgres clusters. The strategies (key choice, resharding, cross-shard queries) are in Partitioning and Sharding. The Postgres-specific options:

  • Application-level sharding: the app maps a shard key (user, tenant or workspace) to a cluster. Many logical shards (schemas or databases) are mapped onto fewer physical clusters, so you can rebalance by moving logical shards. Instagram described this approach in 2012: thousands of logical shards as Postgres schemas, mapped onto far fewer servers, with 64-bit IDs generated in PL/pgSQL embedding time, shard ID and a sequence (Unique ID Generation). Notion's 2021 engineering post described sharding its block data into 480 logical shards across 32 physical databases.
  • Citus, an extension (open source, and offered as a managed Azure service): a coordinator distributes tables by a distribution column across workers. It co-locates related tables on the same shard key, so joins stay local. It replicates small reference tables to every node, and parallelises analytical queries.
  • Proxy-based sharding: a routing layer in front of many Postgres clusters. Figma wrote in 2024 about scaling Postgres roughly 100× since 2020. First came vertical partitioning (moving groups of tables to their own databases), then horizontal sharding via an in-house query proxy, with sharding introduced logically before physically, to de-risk the migration.
  • Postgres-compatible distributed SQL: CockroachDB, YugabyteDB, Spanner's PostgreSQL interface, and Aurora's sharded "Limitless" option. They offer automatic sharding and multi-region consistency, but different performance characteristics, and incomplete compatibility for some features and extensions (Multi-Region Data).

Scaling, in depth: lessons from Uber, Figma, Notion and OpenAI#

The 2016 Uber critique. Uber's engineering blog post "Why Uber Engineering Switched from Postgres to MySQL" (2016) is a useful list of Postgres's architectural trade-offs:

  • write amplification, because every update writes a new tuple and, without HOT, new entries in every index;
  • physical replication shipping all of that amplified WAL across data centres;
  • replica MVCC conflicts;
  • major-version upgrades that were hard, because physical replication couldn't cross versions.

Their workload, a schemaless key-value layer with heavy updates over many indexes, made those costs dominant. Several of the points have since been mitigated:

  • logical replication enables cross-version upgrades;
  • HOT, B-tree deduplication and bottom-up deletion reduce index churn;
  • pg_upgrade --link performs in-place upgrades in minutes.

The broader lesson stands: Postgres's MVCC design is update-unfriendly compared with an undo-log design such as MySQL InnoDB's, which updates rows in place, and keeps old versions in an undo log. So update-heavy, wide-index workloads need care. The InnoDB undo design has its own costs, such as long purge lag.

Vertical before horizontal. Figma's journey shows that a large Postgres deployment can go a long way by:

  1. scaling instances up;
  2. adding replicas and PgBouncer;
  3. splitting groups of tables into separate databases by domain (vertical partitioning), each with its own primary.

Horizontal sharding only came when individual tables became too big and too write-heavy for one instance. Its sharding design emphasised colocation: tables sharing a shard key live on the same shard, so most queries and transactions stay single-shard. It also kept rollback possible at each step. Notion similarly chose workspace ID as the shard key, so that a workspace's blocks live together, and migrated with double writes plus backfill, then verification, then cutover (Data Migration).

One primary can go very far. OpenAI wrote in early 2026 about running ChatGPT's main Postgres workload on a single primary on Azure, with many read replicas (on the order of 50, across regions). They used aggressive query optimisation, connection pooling, caching, rate limiting and workload isolation, moving write-heavy, shardable workloads to other systems instead of sharding Postgres itself. Whatever the exact numbers, the pattern is instructive: read-heavy products can scale a single-writer Postgres to enormous traffic if writes are controlled, and reads are offloaded.

Choosing the shard key. It's the same rules as anywhere (Partitioning and Sharding):

  • high cardinality;
  • present in almost every query;
  • keeps transactional units together (tenant, workspace, user);
  • avoids hot shards (a celebrity user needs special handling).

Postgres-specific advice: keep global, small, rarely changing tables (plans, countries, feature flags) as reference tables replicated everywhere, and accept that cross-shard joins become application code or analytics-pipeline work.

Connection pooling#

Why Postgres needs a pooler. Each connection is a separate OS process. An idle backend uses a few MB of memory, and an active one can use far more: work_mem is allocated per sort or hash operation, so one complex query can use several multiples of it. Snapshot computation and lock-table work also grow with the number of connections. Throughput typically peaks when active connections are around a small multiple of CPU cores, then falls as context switching and contention rise. A widely quoted starting heuristic, from the HikariCP and PostgreSQL wiki discussions, is: connections ≈ (cores × 2) + effective spindle count. So a 32-core server might run best with about 50–100 active connections. Meanwhile, 200 app pods with a pool of 20 each want 4,000 connections. Serverless functions, which open connections per invocation, are worse: a traffic spike becomes a connection storm that exhausts max_connections, and every new connection pays a fork plus authentication, typically a few milliseconds.

PgBouncer is a lightweight, single-threaded, event-driven pooler that multiplexes many client connections onto few server connections. It has three modes:

ModeServer connection is held forWorks withBreaks
SessionThe client's whole sessionEverythingLittle multiplexing; mainly caps total connections
TransactionOne transactionMost web apps; the usual choiceSession state: SET, session advisory locks, LISTEN, temp tables, and (before PgBouncer 1.21) named prepared statements
StatementOne statementAutocommit-only workloadsMulti-statement transactions

In transaction mode, 4,000 client connections can share about 100 server connections, because most clients are idle between transactions. PgBouncer 1.21 (2023) added support for protocol-level prepared statements in transaction mode, removing a long-standing ORM incompatibility. Alternatives include PgCat and Odyssey (multi-threaded, with features such as load balancing across replicas and sharding support), Supavisor, and managed proxies such as Amazon RDS Proxy, which also hides failover from clients. Many frameworks also pool in-process (HikariCP, the node-postgres pool, SQLAlchemy). Use both: a small app-side pool per instance, plus a server-side pooler in front of the database.

Connection pooling, in depth: sizing, timeouts and the failure modes#

Sizing by Little's law. Pool connections needed is roughly throughput × the time each transaction holds a connection. At 5,000 transactions per second, each holding a connection for 4 ms (including network round trips inside the transaction), you need about 20 busy connections on average. Size the server pool at 2–3× that (40–60) for bursts, not at 1,000. If transactions hold connections for 100 ms because the app calls an external API mid-transaction, you need 500 connections for the same throughput. The fix is to never do slow I/O inside a transaction, not to add connections (Latency, Throughput and Performance).

Timeouts and queueing. When all server connections are busy, PgBouncer queues clients. Set query_wait_timeout so clients fail fast rather than piling up, and set app-side acquisition timeouts. Database-side, idle_in_transaction_session_timeout kills sessions that opened a transaction and wandered off. In transaction pooling mode, those sessions pin a server connection and hold back vacuum.

Failure modes.

  1. Pool exhaustion cascades. A slow query plan or lock wait makes transactions hold connections longer, the pool saturates, requests time out, and retries add load. That's a classic retry storm (Resilience Patterns). Use statement timeouts, circuit breakers, and load shedding at the app.
  2. PgBouncer as a single point of failure. Run several instances behind a load balancer, or one per app host. PgBouncer is single-threaded, so one instance tops out at tens of thousands of queries per second. Use so_reuseport with multiple processes, or a multi-threaded pooler, for more.
  3. Session state leaking across clients in transaction mode, such as a SET search_path intended for one tenant. Use SET LOCAL inside transactions.
  4. Failover handling. After promotion, the pooler must reconnect to the new primary. Point it at a DNS name, or HA endpoint, that moves, or integrate with Patroni callbacks.

Transactions, locking and consistency in practice#

This section covers the Postgres-specific behaviour behind the theory in ACID and Isolation Levels and Concurrency Control and Locking.

  • Default isolation is Read Committed. Each statement sees data committed before it began. Two statements in the same transaction can see different data.
  • Repeatable Read is snapshot isolation. The whole transaction sees one snapshot. If it tries to update a row that another transaction changed after the snapshot, it fails with a serialization error, rather than overwriting. That prevents lost updates. Write skew is still possible.
  • Serializable uses Serializable Snapshot Isolation (SSI). Postgres tracks read and write dependencies between concurrent transactions, and aborts one when a dangerous cycle forms. That gives true serializability without blocking reads. The design is described in "Serializable Snapshot Isolation in PostgreSQL" (Ports and Grittner, VLDB 2012), building on Cahill, Röhm and Fekete (SIGMOD 2008). The cost: some false-positive aborts. Applications must retry on SQLSTATE 40001.
  • Explicit row locks. SELECT ... FOR UPDATE locks the selected rows until commit (there's also FOR NO KEY UPDATE, FOR SHARE, and NOWAIT). SKIP LOCKED skips rows other transactions have locked. That turns a table into a correct multi-consumer work queue, where each worker grabs different jobs without blocking (Long-Running Tasks).
  • Advisory locks. pg_advisory_xact_lock(key) gives application-defined locks, useful for "only one cron worker runs this job" without a separate lock service (Distributed Locking).
  • Optimistic concurrency with a version column: UPDATE ... SET qty = qty - 1, version = version + 1 WHERE id = $1 AND version = $2. Check the affected row count, and retry on zero.
  • Constraints as concurrency control. A UNIQUE index makes duplicate inserts fail atomically, which gives idempotency keys for free (Idempotency). A CHECK (stock >= 0) constraint makes oversells impossible. Exclusion constraints prevent overlapping bookings.

The running example. Creating a DM thread is one transaction:

  1. insert the thread;
  2. insert the participants;
  3. insert the first message.

Foreign keys guarantee participants are real users. If any step fails, nothing persists. Like counts, by contrast, don't need to be transactional with the like itself at large scale: insert into likes (the primary key prevents double-likes), and update an approximate counter asynchronously.

Don't hold locks across user think time. The Ticketmaster lesson applies: holding a SELECT FOR UPDATE row lock while a user spends five minutes on the payment page strains connections, invites lock pile-ups and deadlocks, and leaves locks in limbo when clients crash. lock_timeout turns waits into errors, not graceful queues. Postgres also has no row-level TTL. Instead, store a reservation row with an expires_at and check it in the booking transaction, with a cleanup job, or hold the short-lived reservation in Redis with a key TTL, and do the final atomic booking in Postgres (Dealing with Contention). For inventory-style checkouts, a single Postgres transaction at SERIALIZABLE (or with FOR UPDATE on the stock rows) that decrements stock and creates the order is the simple, correct design, as long as it stays within one database.

When Postgres is enough#

A rough sizing guide, assuming a well-indexed schema, a pooler and modern hardware:

SignalPostgres alone is comfortableStart planning beyond one primary
WritesUp to about 5,000–20,000 transactions per second, sustainedSustained tens of thousands per second, or rapid growth toward it
ReadsUp to about 100,000+ simple queries per second with replicas and cachingMillions per second of key–value reads (cache or KV store)
Data sizeUp to single-digit to low tens of TB per clusterHundreds of TB of hot OLTP data
Latency1–5 ms indexed reads in-regionSingle-digit ms writes worldwide (multi-region active-active)
Query shapeJoins, transactions, constraints, ad-hoc queriesKnown key-based access only, at massive scale
Search and analyticsModerate full-text search, dashboards on replicasRelevance-tuned search at scale; OLAP over billions of rows

Translated into users: a product with 10 million daily active users, each doing 20 writes a day, generates 200 million writes a day, about 2,300 per second on average, and perhaps 7,000–12,000 at peak. That's well within one primary. The same users' 500 reads a day each come to about 58,000 reads per second on average, served by a handful of replicas plus a cache. That's why "Postgres with replicas and Redis" is a defensible answer for most interview prompts until the numbers say otherwise (Back-of-the-Envelope Estimation).

When to Use It#

Use PostgreSQL as the default primary database when:

  • Data is relational, with integrity rules: users, accounts, orders, payments, inventory, permissions, bookings. Foreign keys, unique constraints and multi-row transactions are worth a lot.
  • You need strong consistency for core flows: money movement, stock decrements, seat booking, idempotency keys.
  • Query patterns are varied, or not fully known yet. SQL, joins and ad-hoc queries let the product evolve without re-modelling everything around access patterns, as a key–value store would require.
  • Scale is "big but not planet-scale". Up to roughly 5,000–20,000 writes per second, read-heavy traffic served by replicas and caches, and single-digit to tens of TB of hot data.
  • You want one store for several needs: relational plus JSONB documents, moderate full-text search, geospatial queries through PostGIS, vectors through pgvector, a job queue with SKIP LOCKED, or time-series data through TimescaleDB.
  • Portability matters. The same engine runs on every cloud, on Kubernetes and on-premises, with many compatible managed and distributed options.

Pick something else instead when:

  • Write throughput exceeds what one primary can do, and the access pattern is simple key-based. Pick Cassandra or ScyllaDB for very high write volume and wide partitions (messages, events, time-ordered feeds), or DynamoDB for managed, predictable single-digit-ms key–value access at any scale.
  • You need multi-region active-active writes with strong consistency: Spanner, CockroachDB or YugabyteDB.
  • You need relevance-ranked search at scale (BM25, facets, typo tolerance, hundreds of millions of documents): Elasticsearch or OpenSearch, fed from Postgres by CDC.
  • You need analytics over billions of rows (OLAP): ClickHouse, BigQuery, Snowflake or Druid, fed by CDC or batch exports. Postgres row storage is slow for scanning a few columns of huge tables (Data Pipelines and Analytics).
  • You need sub-millisecond caching, counters, leaderboards, rate limiting or ephemeral TTL data: Redis.
  • You need a durable event log, replay, and fan-out to many consumers: Kafka. A Postgres outbox table plus CDC can feed it.
  • You need very large vector collections with heavy filtered ANN queries: a dedicated vector database.
  • You need high-cardinality metrics at millions of samples per second: a time-series database such as Prometheus TSDB, VictoriaMetrics or InfluxDB (Time-Series Databases).

When NOT to Use It#

  • As a message broker at high volume. Queue tables with heavy insert-delete churn bloat and stress vacuum. LISTEN/NOTIFY doesn't persist messages for offline listeners. A Postgres queue is fine for thousands of jobs per second, but not for hundreds of thousands of events per second with replay.
  • As a cache for hot keys. A network round trip, plus planning, plus MVCC overhead, is roughly an order of magnitude slower than Redis for simple gets, and a cache stampede would hit your source of truth.
  • For huge, append-only, write-heavy workloads with simple access, such as IoT telemetry at 1 million rows per second, or chat messages for hundreds of millions of users. WAL, index maintenance and vacuum costs grow with every row. Wide-column or log-structured stores fit better (Storage Engines).
  • For blobs. Store images and videos in Object Storage, and keep metadata and keys in Postgres. Multi-MB bytea values bloat TOAST, backups and replication.
  • When a team will run it without basic operations discipline: no monitoring of vacuum, replication slots, disk and wraparound. Then pick a managed service, at minimum.

How to Implement It#

  1. Choose deployment. Managed (RDS or Aurora, Cloud SQL or AlloyDB, Azure Flexible Server, Neon, Supabase, Crunchy Bridge) for most teams. Self-host with Patroni, or a Kubernetes operator such as CloudNativePG, only with in-house expertise (Cloud Architecture Essentials).
  2. Design the schema from access patterns.
    • Use bigint identities or UUIDv7 keys, and timestamptz.
    • Add constraints (NOT NULL, UNIQUE, CHECK, foreign keys).
    • Use JSONB only for the variable long tail.
    • Plan partitioning for any table expected to exceed about 100 GB, or with time-based retention.
  3. Index deliberately. Composite B-trees matching WHERE plus ORDER BY, partial indexes for hot subsets, GIN for search and JSONB, BRIN for append-only time columns. Always CREATE INDEX CONCURRENTLY in production.
  4. Put a pooler in front (PgBouncer in transaction mode, or a managed proxy). Size the server pool from Little's law. Set statement_timeout, idle_in_transaction_session_timeout and lock_timeout.
  5. Set up HA and backups.
    • A synchronous or semi-synchronous standby in another AZ.
    • Automated failover.
    • Continuous WAL archiving plus base backups with pgBackRest or WAL-G (or provider PITR).
    • A cross-region backup copy.
    • Restore tests, at least quarterly (Disaster Recovery).
  6. Scale reads: replicas for tolerant reads, with read-your-writes routing for users who just wrote. Add a cache (Caching Strategies).
  7. Monitor:
    • pg_stat_statements top queries;
    • replication lag and slot WAL retention;
    • age(datfrozenxid);
    • dead tuples and autovacuum activity;
    • bloat estimates;
    • connection counts;
    • cache hit ratio (aim above 99% for OLTP);
    • checkpoint frequency;
    • disk free space (Observability).
  8. Run safe migrations.
    • Expand and contract.
    • Add nullable columns, or columns with constant defaults (instant since Postgres 11).
    • Backfill in batches.
    • Add constraints as NOT VALID, then VALIDATE.
    • Set lock_timeout on DDL (CI/CD and Deployment).
  9. Plan upgrades. Use pg_upgrade --link, or logical replication to a new major version, with a rehearsed cutover.
  10. Plan the next scale step before you need it: partitioning, then vertical splits, then a shard key, then tooling.

A compact schema for the running example, showing partitioning, the key index types and a SKIP LOCKED job queue:

CREATE TABLE posts (
  id         bigint GENERATED ALWAYS AS IDENTITY,
  user_id    bigint NOT NULL REFERENCES users(id),
  body       text   NOT NULL,
  meta       jsonb  NOT NULL DEFAULT '{}',
  search_doc tsvector GENERATED ALWAYS AS (to_tsvector('english', body)) STORED,
  created_at timestamptz NOT NULL DEFAULT now(),
  PRIMARY KEY (id, created_at)              -- must include partition key
) PARTITION BY RANGE (created_at);
 
CREATE TABLE posts_2026_12 PARTITION OF posts
  FOR VALUES FROM ('2026-12-01') TO ('2027-01-01');
 
CREATE INDEX ON posts (user_id, created_at DESC);          -- profile feed
CREATE INDEX ON posts USING gin (search_doc);               -- full-text
CREATE INDEX ON posts USING gin (meta jsonb_path_ops);      -- JSONB @>
CREATE INDEX ON posts USING brin (created_at);              -- time scans
 
CREATE TABLE jobs (
  id       bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  kind     text NOT NULL,
  payload  jsonb NOT NULL,
  run_at   timestamptz NOT NULL DEFAULT now(),
  attempts int NOT NULL DEFAULT 0
);
CREATE INDEX ON jobs (run_at) WHERE attempts < 5;
 
-- Worker: claim up to 10 due jobs without blocking other workers
WITH next AS (
  SELECT id FROM jobs
  WHERE run_at <= now() AND attempts < 5
  ORDER BY run_at
  LIMIT 10
  FOR UPDATE SKIP LOCKED
)
UPDATE jobs j SET attempts = attempts + 1, run_at = now() + interval '5 minutes'
FROM next WHERE j.id = next.id
RETURNING j.id, j.kind, j.payload;

The worker deletes each job after success. If the worker crashes, the job reappears after five minutes, a visibility timeout like a message queue's. A BRIN index on a partitioned table is cheap per partition, while the (user_id, created_at DESC) index serves the profile query with an early-terminating index scan.

TechnologyFits when
Amazon RDS for PostgreSQLStandard managed Postgres on AWS with Multi-AZ standby and familiar operations
Amazon Aurora PostgreSQLFaster failover, shared-storage replicas with low lag, storage auto-growth, global database
Google Cloud SQL, AlloyDBManaged Postgres on GCP; AlloyDB for higher performance and analytical acceleration
Azure Database for PostgreSQL (Flexible Server)Managed Postgres on Azure; Citus-based option for distributed tables
Neon, Supabase, Crunchy BridgeDeveloper-friendly managed Postgres; Neon branching and scale-to-zero; Supabase app platform
Patroni with etcd, CloudNativePGSelf-managed HA on VMs or Kubernetes with automated failover
PgBouncer, PgCat, Odyssey, RDS ProxyConnection pooling and multiplexing, proxy-level failover
pgBackRest, WAL-G, BarmanBase backups, WAL archiving, PITR to object storage
CitusSharded Postgres for multi-tenant SaaS and real-time analytics
DebeziumCDC from logical decoding into Kafka for search, cache and warehouse sync
CockroachDB, YugabyteDBPostgres-wire-compatible distributed SQL with multi-region consistency

Trade-offs#

OptionProsConsPick when
Single primary plus replicasSimple, strongly consistent writes, full SQLWrite ceiling of one node; replica lagMost products; read-heavy workloads
Synchronous standbyRPO zero on failoverExtra commit latency; write stall if standby down (without quorum)Payments, orders, anything that can't lose commits
Asynchronous replicasNo write latency cost; cheap read scalingStale reads; possible data loss on failoverRead scaling, DR copies
Declarative partitioningPruning, instant retention, smaller indexesPK must include partition key; non-pruned queries fan outBig time-series and event tables; per-region data
Application or proxy shardingNear-linear write scalingCross-shard joins and transactions are hard; resharding workWrites or data beyond one primary, with a clear shard key
CitusSharding with SQL, co-located joinsDistribution-column design required; some features limitedMulti-tenant SaaS; real-time analytics
Distributed SQL (CockroachDB, Yugabyte, Spanner)Automatic sharding, multi-region strong consistencyHigher latency per write; partial compatibility; costGlobal active-active with strong consistency
JSONB columnsSchema flexibility, indexableWeak statistics; full-value rewrites; no FK insideVariable attributes alongside relational core
Postgres full-text searchNo extra system; transactionalNo BM25 by default; limited at large scaleModerate search inside one product
Postgres as queue (SKIP LOCKED)Transactional enqueue with business dataBloat under churn; limited throughputBackground jobs up to thousands per second

Common Pitfalls#

  • No connection pooler, with hundreds of pods or serverless functions each holding connections, so max_connections is exhausted, or memory blows up.
  • Long-running or idle-in-transaction sessions that block vacuum, cause bloat, hold locks, and eventually raise wraparound risk.
  • Abandoned replication slots that make the primary retain WAL until the disk fills.
  • Indexing everything, or indexing churny columns, which kills HOT updates and multiplies write cost.
  • OFFSET pagination on large tables. Use keyset pagination.
  • Plain CREATE INDEX or blocking DDL on a hot table, which locks out writes. Use CONCURRENTLY, NOT VALID plus VALIDATE, and lock_timeout.
  • Random UUIDv4 primary keys on huge insert-heavy tables, causing index bloat and cache misses. Prefer bigint or UUIDv7.
  • Reading from replicas right after a write, so users don't see their own changes. Use read-your-writes routing.
  • Treating replicas as backups. Deletes replicate instantly. Use PITR and test restores.
  • Mass DELETE for retention, which bloats tables and floods WAL. Drop partitions instead.
  • Huge JSONB documents updated frequently, which rewrite the whole TOASTed value every time.
  • Holding row locks during user interaction or external API calls, which causes pool exhaustion and lock pile-ups.
  • Not retrying serialization failures (40001) and deadlocks (40P01) under Repeatable Read or Serializable.
  • Ignoring autovacuum tuning on very large tables. Defaults trigger on 20% dead rows, which for a 1-billion-row table means 200 million dead tuples before cleanup. Lower the per-table scale factor.

Real-World Examples#

  • Instagram ran its early backend on PostgreSQL, and in 2012 described sharding with thousands of logical shards, mapped as schemas onto fewer servers, plus database-generated 64-bit IDs.

  • Notion (2021) sharded its Postgres block storage by workspace ID into 480 logical shards across 32 physical databases, migrating with double writes and backfill, and later expanded the physical fleet.

  • Figma (2023–2024) scaled Postgres about 100× since 2020 through vertical partitioning, then horizontal sharding behind an in-house proxy.

  • Uber (2016) moved part of its storage stack from Postgres to MySQL, citing write amplification, replication and upgrade issues for its update-heavy workload. That's a well-known critique of MVCC trade-offs.

  • OpenAI (2026) described serving ChatGPT's core metadata from a single Azure Postgres primary, with dozens of read replicas, offloading write-heavy workloads elsewhere.

  • GitLab (2017) lost about six hours of production database changes after accidental data deletion and failing backups, a lasting lesson in restore testing.

  • Reddit and many SaaS companies use Postgres as a core store. Supabase and Neon build developer platforms on it.

  • Zerodha, a large Indian stockbroker run by a small team, keeps hundreds of billions of rows in self-hosted Postgres, sharding reports by financial year and using Postgres itself as a hot cache for report results; see Zerodha's engineering lessons.

Case studies that use this pattern#

  • Ticket Booking: ACID booking transactions, FOR UPDATE vs reservations, full-text search on events, exclusion constraints.
  • Payment System: double-entry ledgers, idempotency keys via unique constraints, serializable transfers.
  • Food Delivery: orders and inventory in one transactional store, read replicas and region partitioning.
  • URL Shortener: a single primary plus cache, ID generation, and when Postgres is enough.
  • Online Auction: bid consistency with row locks or optimistic concurrency.
  • Job Scheduler: SKIP LOCKED queues and partitioned execution history.
  • Proximity Service: PostGIS radius search vs geohash indexes.

In the Interview#

Deep Dive: Vacuum, bloat and freezing as an operational disciplineShow

What autovacuum actually decides. For each table, autovacuum starts a vacuum when dead tuples exceed autovacuum_vacuum_threshold + autovacuum_vacuum_scale_factor × reltuples. The defaults are 50, plus 20% of the rows. Since Postgres 13, it also vacuums after enough inserts, so append-only tables get their visibility map set, and get frozen. For a 10,000-row table, 20% is 2,000 dead rows: fine. For a 2-billion-row table, it's 400 million dead rows before cleanup, by which time the table and its indexes have bloated badly, and the vacuum itself takes hours. So for large tables, set per-table parameters: ALTER TABLE events SET (autovacuum_vacuum_scale_factor = 0.01), or a fixed threshold.

Vacuum is throttled by design. The cost-based delay (autovacuum_vacuum_cost_limit and autovacuum_vacuum_cost_delay) stops vacuum saturating I/O. Since Postgres 12, the default delay has been 2 ms. On fast NVMe storage, the defaults are often too gentle for busy databases. Raise the cost limit (for example, to 1,000–2,000), and allow more workers (autovacuum_max_workers) if many big tables churn. The worker count is shared, so more workers each get a smaller slice of the cost budget, unless you raise the limit too.

What blocks vacuum from removing dead rows. Vacuum can only remove a tuple version that's older than the oldest snapshot still in use anywhere. Three things hold back that horizon:

  1. Long-running transactions, including idle-in-transaction sessions. Find them with SELECT pid, now() - xact_start, state, query FROM pg_stat_activity ORDER BY xact_start.
  2. Replication slots whose consumer is behind: SELECT slot_name, active, restart_lsn FROM pg_replication_slots. Check the xmin and catalog_xmin columns too.
  3. Standbys with hot_standby_feedback running long queries.

A single forgotten BEGIN in a psql session left open over a weekend can bloat every hot table in the database. That's why idle_in_transaction_session_timeout (minutes, not hours) is a default worth setting.

Measuring and fixing bloat. Estimate it with the pgstattuple extension (exact, but it scans the table), or with catalogue-based estimate queries (cheap, approximate). Remedies:

  • VACUUM makes space reusable, but rarely shrinks files.
  • VACUUM FULL rewrites the table compactly, but takes an ACCESS EXCLUSIVE lock for the duration, which is unusable on a hot table.
  • pg_repack (or pg_squeeze) rebuilds the table online, with only brief locks.
  • REINDEX CONCURRENTLY (since Postgres 12) rebuilds bloated indexes without blocking writes.

A worked example. A sessions table has 50 million rows of about 300 bytes. Each row is updated every 5 minutes, which is about 167,000 updates per second at full concurrency. That's an extreme case, but let's scale it down: say 10% of sessions are active, so about 17,000 updates per second.

  • With HOT updates (no index on the updated last_seen column, and fillfactor 80), most updates reuse space on the same page, and pruning reclaims it opportunistically, even between vacuums. The table stays near 15–20 GB.
  • Without HOT (an index on last_seen), each update adds an index entry and a new tuple on another page. That's 17,000 × 300 bytes, about 5 MB per second of new heap versions, about 18 GB per hour, plus index growth. Autovacuum must keep pace, or the table doubles in hours.

The fix is design, not tuning: drop the index on last_seen (or make it a partial index), use fillfactor, or move this ephemeral, high-churn state to Redis with TTLs.

Freezing at scale. Anti-wraparound vacuums must read every page not yet marked all-frozen in the visibility map. On multi-terabyte tables, that can take many hours, and they can't be cancelled by normal means once they're urgent. Strategies:

  • partition big tables, so old partitions get frozen once and stay frozen;
  • run scheduled VACUUM (FREEZE) during quiet hours;
  • monitor age(relfrozenxid) per table, and alert well before autovacuum_freeze_max_age.

Postgres 16 and later versions improved freezing efficiency, by freezing pages opportunistically when they're already being written.

Why not undo logs? InnoDB and Oracle update in place, and keep old versions in an undo log, so the main table doesn't bloat. But long transactions make the undo log grow, and old snapshots read back through version chains instead. Postgres projects have explored undo-based storage. EnterpriseDB's "zheap" effort stalled. OrioleDB builds an alternative engine on the table access method API added in Postgres 12. Today's practical answer remains: design for HOT, keep transactions short, and tune vacuum (Storage Engines).

Deep Dive: Serializable Snapshot Isolation and choosing an isolation levelShow

The anomaly snapshot isolation allows. Under Repeatable Read (snapshot isolation), each transaction sees a consistent snapshot, and the first committer wins on a write-write conflict. But two transactions that read overlapping data and write different rows can both commit, and together break an invariant. That's write skew.

The classic example has two on-call doctors, Alice and Bob, with the rule "at least one must be on call":

  1. Both open a transaction.
  2. Both run SELECT count(*) FROM oncall WHERE on_call and see 2.
  3. Alice updates her own row to off-call, and so does Bob.
  4. Snapshot isolation sees no conflict, because they wrote different rows.
  5. Both commit. Nobody is on call.

The same pattern breaks "username must be unique across two tables", "don't overbook total seats across rows", or "account balances across two accounts must sum to at least zero". See Concurrency Control and Locking.

How SSI detects it. Postgres's Serializable level adds SIREAD locks. These are not real locks, and block nothing. They record what each serializable transaction read: tuples, pages, or whole relations, escalating to coarser granularity when there are too many. When transaction T2 writes something that T1 read, while both are concurrent, that's a read-write antidependency, T1 → T2.

The theory, from Fekete et al. ("Making Snapshot Isolation Serializable", ACM TODS 2005), and made practical by Cahill, Röhm and Fekete (SIGMOD 2008), shows that every serialisation anomaly under snapshot isolation contains a "dangerous structure": two consecutive rw-antidependencies, T1 → T2 → T3, where T2 is the pivot (T1 and T3 may be the same transaction), and T3 commits first. Postgres tracks these edges, and aborts a transaction when the structure appears, raising SQLSTATE 40001 ("could not serialize access"). In the doctors example, each transaction read the row the other wrote, which forms the cycle, so one of the two commits fails, and its retry sees only one doctor on call.

Costs and false positives. Tracking is conservative. Coarse-grained SIREAD locks (page or relation level) and imprecise commit-order information cause some aborts that weren't strictly necessary. Ports and Grittner (VLDB 2012) report that Postgres's implementation performed within a modest overhead of snapshot isolation on their benchmarks, while read-only workloads benefit from optimisations:

  • a transaction declared READ ONLY DEFERRABLE waits for a safe snapshot, then runs with no SIREAD tracking, and can never be aborted. That's ideal for long reports and backups (pg_dump --serializable-deferrable).
  • Read-only transactions can also be committed early in the conflict analysis.

Practical advice:

  • keep serializable transactions short;
  • make sure queries use indexes (sequential scans take relation-level SIREAD locks, which inflate conflicts);
  • always wrap them in a retry loop.
// Retry a unit of work on serialization failure or deadlock, with jittered backoff
async function withSerializableRetry<T>(pool: Pool, work: (c: Client) => Promise<T>, max = 5): Promise<T> {
  for (let attempt = 1; ; attempt++) {
    const c = await pool.connect();
    try {
      await c.query("BEGIN ISOLATION LEVEL SERIALIZABLE");
      const result = await work(c);
      await c.query("COMMIT");
      return result;
    } catch (err: any) {
      await c.query("ROLLBACK").catch(() => {});
      const retryable = err.code === "40001" || err.code === "40P01";
      if (!retryable || attempt >= max) throw err;
      await sleep(Math.random() * 10 * 2 ** attempt);   // full jitter, ms
    } finally {
      c.release();
    }
  }
}

The work function must be idempotent with respect to side effects. Don't send an email or call a payment API inside it. Do that after commit, or through an outbox (Pattern: Multi-Step Processes).

Choosing a level per operation.

OperationLevel and techniqueWhy
Simple CRUD, single-row updatesRead Committed (default)Each statement atomic; row locks prevent lost updates for UPDATE ... SET x = x + 1
Read-modify-write on one row in app codeRead Committed plus SELECT ... FOR UPDATE, or a version columnPrevents lost updates explicitly
Consistent multi-query reportRepeatable Read, READ ONLYOne snapshot, no blocking
Invariants spanning rows or tables (on-call, seat totals, balance sums)Serializable plus retry, or explicit locks on a guard rowPrevents write skew
Hot contended counterRead Committed, single-statement atomic update, or move to Redis or sharded countersMinimise lock hold time
Uniqueness across concurrent insertsUnique constraint (any level)Index enforces atomically

Locks behind the levels. Even reads take a lightweight ACCESS SHARE lock on the table, which conflicts only with ACCESS EXCLUSIVE (most ALTER TABLE forms, DROP, VACUUM FULL). That's the root of the infamous lock queue problem. A migration's ALTER TABLE waits behind one long-running SELECT, and every subsequent query on that table queues behind the waiting ALTER. The application stalls, even though the ALTER itself would take milliseconds. Always run DDL with SET lock_timeout = '3s', and retry.

Deep Dive: Tuning, upgrades and zero-downtime operationsShow

Memory and I/O settings that matter most.

  • shared_buffers: about 25% of RAM is the common starting point. Postgres relies on the OS page cache for the rest, which is "double buffering", so bigger isn't always better.
  • effective_cache_size: about 50–75% of RAM. It's a planner hint, not an allocation, telling the planner how likely index pages are to be cached.
  • work_mem: memory per sort or hash node, per query, per connection. 64 MB × 4 nodes × 200 active connections is about 51 GB in the worst case. Keep the global value modest (4–64 MB), and raise it per session for heavy reports.
  • maintenance_work_mem: for vacuum and index builds. 1–2 GB speeds up CREATE INDEX substantially.
  • random_page_cost: the default 4.0 assumes spinning disks. Set it to about 1.1 on SSD, so the planner uses indexes appropriately.
  • Huge pages reduce TLB overhead for large shared_buffers.
  • I/O: Postgres 18 introduced an asynchronous I/O subsystem (including io_uring on Linux), which improves sequential scans and vacuum on fast storage.
  • WAL: put it on fast, low-latency storage. Enable wal_compression (lz4 or zstd, since Postgres 15) to shrink full-page images.

Major-version upgrades. Minor versions (17.1 to 17.2) are binary-compatible. Restart and done. Major versions change the on-disk catalogue format. Options:

  1. pg_dump and restore: simple, but takes hours for large databases. Only for small ones.
  2. pg_upgrade --link: rewrites the catalogues and hard-links the data files. The downtime is minutes, even for terabytes. But it's in place, so test a rollback plan: snapshots, or keep the old cluster's standby.
  3. Logical replication to a new-version cluster: near-zero downtime. Managed equivalents include Amazon RDS Blue/Green Deployments, which create a synchronised "green" copy and switch over.

The cutover window is seconds. The risks are tables without primary keys, which can't replicate updates and deletes, DDL changes during the migration, sequence resync, and extensions needing matching versions. Rehearse on a staging copy.

Zero-downtime schema changes. Postgres DDL is transactional (you can roll back a failed migration), but many forms take ACCESS EXCLUSIVE locks. Safe patterns:

  • Add a column: nullable, or with a constant default, is metadata-only since Postgres 11. Adding a volatile default rewrites the table.
  • Add NOT NULL: add CHECK (col IS NOT NULL) NOT VALID, then VALIDATE CONSTRAINT, which takes a weaker lock and scans while allowing writes. Since Postgres 12, SET NOT NULL can use the validated check to skip the scan.
  • Add a foreign key: NOT VALID, then VALIDATE.
  • Change a column type: usually a table rewrite. Add a new column, dual-write, backfill in batches of about 1,000–10,000 rows with pauses, switch reads, and drop the old column (expand and contract).
  • Rename: instant, but breaks running code. Use expand and contract with views or dual columns.
  • Indexes: CREATE INDEX CONCURRENTLY and DROP INDEX CONCURRENTLY. Check for an INVALID index after a failure.

Tools such as pgroll and reshape automate expand-and-contract migrations with views, and frameworks have "strong migrations" linters that block unsafe DDL in code review.

Failover drills. Practise promoting the standby in staging, and in production during low traffic. Measure the real RTO, including DNS, pooler reconnection and application retries. Verify that pg_rewind brings the old primary back as a standby. Many teams discover during the first drill that their application caches the primary's IP address, or that connection pools never refresh. Drills turn these into planned fixes, rather than incident findings (High Availability Design).

Key Takeaways#

  • Postgres is the default relational choice: ACID transactions, rich constraints, many index types, and an extension ecosystem (full-text search, PostGIS, pgvector, TimescaleDB, Citus) that covers many specialised needs in one system.
  • MVCC means readers don't block writers, but updates create new tuple versions. Vacuum, HOT updates and short transactions keep bloat and wraparound in check.
  • The WAL provides durability, crash recovery, replication, PITR and CDC. synchronous_commit tunes durability per transaction.
  • Match the index to the query: B-tree for equality, ranges and sorting; GIN for words, JSONB and arrays; GiST and SP-GiST for geometry and ranges; BRIN for huge append-only tables; HNSW for vectors. Every index costs write throughput.
  • JSONB is excellent for the variable long tail next to relational columns, and poor as a replacement for them.
  • Streaming replication gives HA and read scaling. Logical replication gives cross-version upgrades, selective sync and CDC. Use an external tool, such as Patroni or a managed service, for automatic failover, and handle replica staleness explicitly.
  • One primary handles about 5,000–20,000 writes per second. Beyond that: batch, partition, split vertically, then shard on a clear key (application, proxy or Citus), or move that workload to a specialised store.
  • Always pool connections. Size pools with Little's law, keep slow I/O out of transactions, and set timeouts.
  • Postgres is enough for most systems until concrete numbers (writes, data size, global latency, search or analytics scale) say otherwise. Say those numbers in the interview.