Core Concepts

PostgreSQL

Store related records, enforce data rules, and query them with SQL.

Free~18 min

PostgreSQL stores related records that an application needs to query and update. SQL can filter orders by status or join them with customers. The database can enforce rules such as requiring every order to reference an existing customer.

Use it when related writes must succeed together, when concurrent requests can violate a data rule, or when we need several ways to query the same records.

What PostgreSQL is good at

A constraint is a rule PostgreSQL checks when data changes. A UNIQUE constraint on a checkout request ID can enforce one order per request even when a client retries. A foreign key checks that orders.customer_id points to an existing customer. Add NOT NULL to require a customer on every order. A transaction can change an order's status and record that change in its history as a single unit. PostgreSQL constraints

An application can fetch an order by ID, list a customer's recent orders, and report orders by status from the same table. A key-value store is a candidate when the workload mostly looks up a value by a known key. Keep large files such as invoice PDFs in object storage, with their keys and searchable metadata in PostgreSQL. A Redis cache can hold a copy of a value the application can recreate.


What survives a crash after commit?

Order 817 belongs to customer 42 and starts with status pending. To record its payment, update the order and add a paid event in the same transaction.

BEGIN;
 
WITH paid_order AS (
  UPDATE orders
  SET status = 'paid'
  WHERE id = 817 AND status = 'pending'
  RETURNING id
)
INSERT INTO order_events (order_id, event_type, occurred_at)
SELECT id, 'paid', TIMESTAMPTZ '2026-02-14 10:20:00+00'
FROM paid_order;
 
COMMIT;

RETURNING id gives the insert the ID of the updated order. If the update matches zero rows, paid_order is empty and the insert adds no event. If the insert fails, the transaction rolls back both changes. PostgreSQL data changes in WITH

PostgreSQL changes the order's page, a block of table data it holds in memory. At commit that changed page may still be waiting to reach disk. PostgreSQL also records the changes and the commit in a sequential write-ahead log, or WAL. With a locally durable commit, PostgreSQL flushes WAL through the commit record before returning success. To flush here means to make the log bytes durable on storage. PostgreSQL write-ahead logging

In the timeline below, PostgreSQL acknowledges the commit, then crashes before the changed orders page reaches disk. When it restarts on the same storage, it replays the durable WAL to redo the missing page changes.

After restart, read the order from the recovered database.

SELECT status FROM orders WHERE id = 817;

Result after recovery

status
------
paid

The same ordering applies whenever PostgreSQL flushes a changed page. The WAL that describes the change must already be durable. This lets PostgreSQL write changed table and index pages separately from commit and lets one WAL flush cover several concurrent commits. A physical backup plus archived WAL can also recover the database to a chosen point in time.


What can a reader see during an update?

Run two versions of the same experiment. Both start with order 817 at pending. One connection, transaction A, reads it twice. Between those reads, a second connection runs the payment transaction above as transaction B and commits.

In transaction A, choose the default isolation level for the first run.

BEGIN ISOLATION LEVEL READ COMMITTED;

For the second run, start with a fresh copy of the pending order and begin A with this setting.

BEGIN ISOLATION LEVEL REPEATABLE READ;

Run the same query before and after B commits

Run this query in transaction A before transaction B updates the order.

SELECT status FROM orders WHERE id = 817;

First read at either isolation level

status
------
pending

Once B marks the order paid and commits, run that same query again in the still-open transaction A.

SELECT status FROM orders WHERE id = 817;

Second read at READ COMMITTED

status
------
paid

Second read at REPEATABLE READ

status
------
pending

We can now commit A with COMMIT. A snapshot determines which row versions a query can see. READ COMMITTED takes a fresh snapshot at the start of each SELECT. REPEATABLE READ uses the snapshot from A's first SELECT for both reads.

PostgreSQL can give each reader the right version because B's update creates a new row version and leaves the old one available. This is multiversion concurrency control (MVCC). An ordinary read can use an older version while a write is still in progress. A second writer trying to update the same row may have to wait. PostgreSQL transaction isolation

Both tracks in the diagram use the same writer commit between the two reads. The only difference is when A takes its snapshot.

Old snapshots delay cleanup

The old pending version must stay available while A's repeatable-read snapshot can see it. Once no active snapshot needs it, vacuum can reclaim its space for reuse. A long-running transaction can hold an old snapshot open so more obsolete row versions pile up in tables and indexes. Vacuum also freezes old row versions so PostgreSQL can safely reuse its finite range of transaction IDs. PostgreSQL routine vacuuming

A consistent snapshot is useful when several reads must agree. If correctness also depends on what concurrent transactions read and write together, PostgreSQL's SERIALIZABLE isolation level can abort a transaction when the combined result cannot match any serial execution. The application needs to retry the whole transaction after a serialization failure. Isolation Levels and MVCC


How does an index change the order lookup?

To show customer 42 their 20 most recent orders, we filter by customer, sort newest first, and use the order ID to break ties.

SELECT id, status
FROM orders
WHERE customer_id = 42
ORDER BY created_at DESC, id DESC
LIMIT 20;

Result on the primary after payment (first row)

id  | status
----+-------
817 | paid

For a large table with no useful index, PostgreSQL may read the table, keep matching rows, and sort them. The following B-tree index keeps entries for each customer together in the order the query needs.

CREATE INDEX orders_customer_recent_idx
ON orders (customer_id, created_at DESC, id DESC);

An index scan can seek to customer 42 and follow matching entries in order until it has enough visible rows. Each entry points into the table's main storage area, called the heap. The regular index scan visits the heap to get status and check whether the row version is visible to the query. PostgreSQL indexes and sorting

When can the query skip fetching the table row?

An index with INCLUDE (status) would carry the extra value the query returns. That makes an index-only scan possible. The visibility map tracks which table pages have only row versions visible to all active and future transactions. The payment update clears that flag for the affected page. An index-only scan still fetches the row from that page to check visibility until vacuum can mark it all-visible again. Once the flag is set, the scan can return the values directly from the index. PostgreSQL index-only scans · Visibility map

Follow order 817 from the index to the heap. In the covering-index path, the visibility check determines whether the heap visit is needed.

Every index takes space and adds work to writes that need new entries. A heap-only tuple (HOT) update can skip new B-tree entries if the indexed columns stay the same and the new row version fits on the same heap page. Including status in this index makes that optimization unavailable for the payment update. Evaluate the extra column against the read workload. PostgreSQL heap-only updates

Use EXPLAIN (ANALYZE, BUFFERS) on the read with representative data to see what PostgreSQL chose and how often it found a page in memory or had to read one. An index-only plan can report heap fetches. When a query returns most of a table, scanning the table once may cost less than following index pointers. PostgreSQL EXPLAIN


Replication follows the WAL

To survive loss of a database server, we can keep a copy on another server. The primary accepts writes. A physical standby starts from a copy of the primary's data files and keeps it current by replaying the WAL the primary sends. A hot standby can serve read-only queries while replay runs. In the default asynchronous configuration, the primary can acknowledge the payment before the standby has the change.

A standby read can lag behind a durable write

Suppose the standby has saved the payment WAL to its own disk and has yet to apply the change to its copy of the table. Run a fresh query on that standby.

SELECT status FROM orders WHERE id = 817;

Standby result before replay

status
------
pending

Result when we run the same query after replay

status
------
paid

Failover can preserve only the WAL that is available

Consider a separate run with the same payment. The primary acknowledges the commit, then its storage is lost before the only standby gets that WAL. With no other copy of the missing WAL, we promote the standby. Promotion makes it the new primary so it can accept writes.

SELECT status FROM orders WHERE id = 817;

Result from the promoted standby

status
------
pending

The diagram compares the two outcomes. In the first, WAL is present and replay can catch up. In the second, recovery has no copy of the payment WAL, so the acknowledged update is absent.

Choose what commit success waits for

With synchronous replication, we choose which and how many standbys must acknowledge the write before the primary returns commit success. With synchronous standbys configured, synchronous_commit = on waits for the required standbys to flush the commit WAL to durable storage. remote_apply also waits for them to replay it so fresh queries on those standbys can see it. Waiting for standby acknowledgments adds a network round trip. Commits can stall if the required standbys are unavailable. PostgreSQL synchronous commit settings

For an immediate confirmation read, use the primary. Send reads that can tolerate older data to a hot standby. A failover plan also needs a way to detect failure, select and promote a standby, block the old primary from accepting writes, and route clients to the new one. PostgreSQL standby servers


When does partitioning reduce work?

The paid event for order 817 lives in order_events. Suppose that history has grown across years and most queries include a date range. We can present one logical table to the application while storing each month's rows in a separate child table. This is range partitioning.

To read the February history for order 817, filter on the same occurred_at column we use to define the monthly ranges.

SELECT event_type, occurred_at
FROM order_events
WHERE order_id = 817
  AND occurred_at >= TIMESTAMPTZ '2026-02-01 00:00:00+00'
  AND occurred_at <  TIMESTAMPTZ '2026-03-01 00:00:00+00';

Result (timestamps displayed in UTC)

event_type | occurred_at
-----------+-----------------------
paid       | 2026-02-14 10:20:00+00

PostgreSQL can infer from the range that January and March contain no matching rows. Skipping those tables is partition pruning. It still has to look for order 817 within February. The figure also shows a separate maintenance operation. We can detach January from the parent table in one operation. January's data remains in an ordinary table for archiving or removal later. PostgreSQL declarative partitioning

An indexed table is the simpler starting point when most queries would visit every partition and retention work is manageable. Partitioning pays off when date filters skip substantial work or when we regularly retire whole ranges of history.

Know which resource is limiting growth

If application instances exhaust the database's connections, a connection pool lets many requests share a bounded number of sessions. If a slow query reads too much data, check its plan and indexes. Monthly partitions in a single PostgreSQL cluster still share its resources. Once the workload outgrows one cluster's write or storage capacity, sharding distributes data across database servers. Choose a shard key that keeps common queries and related writes together to limit cross-server coordination.


How to use in a system design

For a checkout service, choose PostgreSQL because marking an order paid and recording its payment event must succeed together. Both writes can happen in one transaction. A required customer ID and a foreign key keep every order tied to a real customer. A key-value store is easier to justify when the prompt is about a single lookup and those relationships and rules are outside the workload. Use object storage for invoice files and keep their searchable metadata with the order.

Put checkout writes and the immediate confirmation read on the primary. A dashboard that can tolerate briefly stale order counts can read from a standby. Ask how much acknowledged data the business can afford to lose if the primary fails. If acknowledged payments must survive loss of the primary, wait for a durable copy on a standby that can be promoted, and account for commits waiting when that standby is unavailable.

Start with an index for the customer order list. Use query plans and the cost of retiring old history to decide when order_events needs partitions. If storage or writes still exceed what the cluster can handle, estimate how many requests would need to cross a shard boundary before choosing a shard key.

See also

  • Database Indexes - follow a point lookup and a backward scan.
  • ACID Transactions - choose what must commit together.
  • Isolation Levels and MVCC - see which row versions overlapping transactions can read.
  • Write-Ahead Log - the durability mechanism behind commit, recovery, and physical replication.
  • Data Replication - the general leader, follower, lag, and failover tradeoffs.
  • Database Sharding - the scale-out step after one PostgreSQL cluster is the boundary.
  • SQL vs NoSQL - chooses a data model from access patterns and invariants.
  • B-Trees vs LSM-Trees - compares PostgreSQL's common index structure with write-optimized storage engines.
  • MySQL (forthcoming) - another relational database with different storage and replication internals.

Used in

  • ChatGPT - enforces one active turn per conversation and saves pending work, replies, and usage.
  • URL Shortener - enforces unique short codes and preserves durable mappings.
  • Group Chat with Threads - stores relational conversation metadata and transactional message state.
  • Online Chess - persists completed games and transactional rating updates after live play ends.
  • Collaborative Coding Interview Platform - stores sessions, permissions, and durable run metadata.

Done reading? Mark it so it sticks in your dashboard.

Discussion