Roadmap Hub

Architecture Library · PostgreSQL 18

PostgreSQL Architecture

A clear guide to how PostgreSQL handles requests, stores data, and protects changes. Technical terms are explained as they appear.

Explanation view

The guide starts with plain-language explanations. Choose Technical for implementation details, or Both to see the two side by side.

System map

PostgreSQL at a glance

PostgreSQL has two sides: programs that ask for data (clients) and a server that handles those requests. The server gives each connection a worker process called a backend. These workers share memory and get help from background processes that manage data files and the change log.

Conceptual PostgreSQL 18 server architecture Clients connect to the postmaster, which accepts connection requests and starts a backend process. The backend handles session startup and authentication, processes queries, and uses shared memory. Background processes maintain buffers and WAL, which are written to database files and WAL segments. CLIENTS CONNECTION HANDLING SERVER INSTANCE SHARED MEMORY STORAGE Application client: opens a PostgreSQL protocol connection and sends SQL or prepared statements. FastAPIapplication client Command-line and graphical clients such as psql and pgAdmin also connect through the PostgreSQL protocol. psql · pgAdminother clients The postmaster listens for connections, performs startup and connection setup, and starts a backend process for an accepted client. Postmasterlisten · acceptstart backend A backend handles one client connection at a time: it processes the protocol, runs SQL, and returns results. Backend processone connected clientquery · transaction Background processes perform distinct maintenance and I/O tasks; they are not client query workers. Background processeswriter · checkpointerWAL · autovacuum · archive Shared buffers cache table and index pages in shared memory. Backends can read and modify shared pages. Shared Bufferscached data pages WAL buffers hold generated WAL records in shared memory before WAL writer or commit processing writes them to WAL files. WAL Bufferschange records PostgreSQL shared memory also holds locks, transaction status, and other coordination structures. Other shared statelocks · transaction data Relation files contain table heap pages, indexes, and auxiliary storage such as TOAST relations. Relation filesheap · TOASTindexes WAL segment files hold the sequential log records used for crash recovery and, depending on configuration, archiving and replication. WAL segmentsdurability · recovery connection spawn shared access page writes WAL writes flush dirty pages
A simplified map of the main parts. The exact work and timing depend on the server settings and workload.

Select a diagram component to highlight it and jump to its explanation. On narrow screens, scroll the diagram horizontally.

Choose a component in the diagram to see where it is covered in this guide.

Plain English

Think of PostgreSQL as a workshop. Each connected customer has a worker. Workers use shared workspaces, while other workers save changes and clean up old data.

Technical

The server uses a process-per-connection model. Backends execute client commands and coordinate through shared memory and synchronization primitives. Buffer and WAL I/O are distinct: WAL is flushed for commit durability; table and index pages can be written later.

01 · Connections

Client-server architecture

A client is any program that connects to PostgreSQL, such as a website, a command-line tool, or a database app. A driver (a library that lets the program talk to PostgreSQL) sends and receives messages. The program and database can be written in different languages.

The postmaster is PostgreSQL's main server process. It listens for new connections and starts a backend process for each one. The backend checks the connection details and password, then handles all queries for that connection. The postmaster does not handle each query itself.

PostgreSQL connection flow A client connects over a Unix socket or TCP, the postmaster accepts the connection and starts a backend, the backend performs session startup and authentication, then client and backend exchange protocol messages. Applicationdriver · protocol Postmasterlisten · start backend Backend processone per connection SQL & resultsfrontend/backend protocol socket / TCP startup + auth query · response
An application can connect on the same machine or over a network. TLS can encrypt a network connection when enabled.

Plain English

The postmaster is like a front desk. It starts a worker for each new connection; that worker then handles the conversation.

Technical

PostgreSQL uses a process-per-user connection model. The postmaster accepts the connection and starts a backend; the backend performs the protocol startup and authentication flow using access configuration such as pg_hba.conf. Connection poolers can reduce the number of server backends required by an application.

FastAPI example

# A driver manages a PostgreSQL protocol connection.
async with pool.connection() as conn:
    row = await conn.execute(
        "SELECT id, username FROM users WHERE id = %s",
        (10,),
    )

The driver sends the query to the backend, which checks and runs it. Applications often reuse connections through a connection pool instead of opening a new one for every request. Database permissions should give each application only the access it needs.

02 · Execution model

PostgreSQL processes and core components

PostgreSQL uses separate operating-system processes to do its work. A backend serves one client connection, while background processes handle specific tasks such as saving data or cleaning up old rows.

PostgreSQL server process relationships The postmaster starts client backends and background processes. Backends and background workers coordinate through shared memory. Specialized processes write data pages, flush WAL, vacuum tables, archive completed WAL, and transfer WAL for replication. Postmastersupervisor · listener Backendsclient SQL sessions Shared memorybuffers · locks · state Writer · checkpointerdata-page I/O WAL writer · archiverlog flush · archive Autovacuumlauncher · workers spawn start services WALtable pages
The arrows show each process's main job, not every internal message or file operation.

Process roles

ProcessEveryday comparisonMain job
PostmasterA service desk assigning a worker to each customer.Listens for new connections and starts the server processes that handle them.
BackendA worker helping one customer.Handles one client connection, runs its SQL, and returns results.
Background writerA filing assistant clearing papers from shared desks.Writes some changed pages from memory to database files.
CheckpointerA supervisor marking a recovery point.Writes pages needed for a checkpoint so recovery has a known starting point.
WAL writerA clerk saving the change log.Writes change records from memory to log files. A backend can also do this when needed.
Autovacuum launcher / workersA coordinator sending out cleanup crews.Finds tables that need cleanup or updated statistics and starts workers to maintain them.
ArchiverA courier taking finished log files to storage.Copies completed change-log files to an archive when configured.
WAL sender / receiverWorkers sending and receiving a change log.Sends change records from a primary server to a standby.

Each process has a separate job. The background writer and checkpointer save table and index pages. The WAL writer saves change records. Autovacuum cleans tables, and the archiver copies finished log files when archiving is enabled.

Background process details

Background writer

Non-technical

A filing assistant moves some frequently used papers from shared desks into their proper cabinets gradually, so customer-facing workers have less filing to do themselves.

Technical

The background writer scans buffer-pool state and writes selected dirty shared-buffer pages. It smooths relation-page I/O, but checkpoint and backend writes still occur; WAL must be flushed before a dirty page can be written.

Why it exists: to reduce bursts of writes performed by backends when they need clean buffers. It is not the mechanism that makes a transaction commit durable.

Checkpointer

Non-technical

A supervisor creates a reliable bookmark in the journal and makes sure the pages needed for that recovery point are safely filed.

Technical

The checkpointer writes dirty buffers needed for a checkpoint, ensures WAL through the checkpoint record is durable, and updates checkpoint state. The interval and write pacing affect recovery time and I/O.

How it interacts: it coordinates relation-page writes with WAL ordering and shared buffers. A checkpoint bounds crash-recovery work; it is not issued for every COMMIT.

WAL writer

Non-technical

A ledger clerk periodically copies the latest change notes from a shared tray into the durable journal.

Technical

The WAL writer flushes WAL buffers to WAL segment files on a schedule. Backends can also perform WAL writes and flushes, including when a transaction must wait for synchronous commit durability.

Why it exists: to move WAL out of shared memory efficiently and reduce the amount of work that a backend must do when commit records are generated.

Autovacuum launcher and workers

Non-technical

A coordinator sends cleanup crews to tables that have accumulated stale row versions or need refreshed statistics.

Technical

The launcher starts workers based on per-table vacuum/analyze thresholds and available worker slots. Workers perform VACUUM and ANALYZE; anti-wraparound vacuuming can take priority to protect transaction-ID correctness.

How they interact: workers read and update table/index structures and share buffer and lock resources with application workloads. Long-running transactions and replication horizons can constrain how much dead-tuple cleanup is safe.

Archiver

Non-technical

A courier takes a completed, sealed journal volume to a separate archive location.

Technical

When WAL archiving is enabled, the archiver invokes the configured archive command or archive library for completed WAL segments. Archive retention and backup consistency are managed as part of the backup/recovery design.

Important boundary: archiving does not itself make a base backup and does not replace the active WAL segment files needed by the running server.

WAL sender and receiver

Non-technical

One office sends a numbered stream of journal entries; the receiving office checks the stream and applies it to its own files.

Technical

A walsender serves WAL to a replication connection on the primary; a walreceiver on the standby receives it, writes it locally, and coordinates replay. Replication slots can retain WAL required by a consumer.

Why they exist: to transport physical WAL for streaming replication and standby recovery. They are separate from logical decoding and application backend execution.

Ten components to keep distinct

These are the ten main parts of the system, not ten separate processes. Open a row to see what each part does and how it works.

Client applications
Definition
A program that speaks PostgreSQL's frontend/backend protocol.
Purpose
Submit commands and consume rows, status, and errors.
Mechanism
Driver encodes protocol messages over a socket, optionally using TLS.
Role
Owns application behavior and connection policy; server-side execution belongs to the backend.
Real-world analogy
A customer communicating an order to a service desk.
Technical explanation
Clients include FastAPI services, psql, pgAdmin, and language drivers such as libpq-based tools, JDBC, or psycopg.
Postmaster (main server process)
Definition
The supervising PostgreSQL server process.
Purpose
Start and supervise an instance and accept connection requests.
Mechanism
Listens on configured sockets and starts a backend process; the backend performs session startup and authentication.
Role
Connection admission and process lifecycle, not ordinary query execution.
Real-world analogy
A receptionist who assigns a dedicated staff member to a visitor.
Technical explanation
The postmaster supervises the process-per-connection server model and starts auxiliary server processes.
Backend processes
Definition
A server process assigned to one client connection.
Purpose
Parse commands, run transactions, and return results to that client.
Mechanism
Receives protocol messages, uses private memory and shared server structures, and issues storage I/O as needed.
Role
Session-scoped query and transaction execution.
Real-world analogy
A dedicated clerk handling one customer's session.
Technical explanation
Each backend has process-local state and accesses shared memory under PostgreSQL's synchronization rules; a pooler can multiplex application sessions onto fewer server connections.
Shared memory
Definition
Memory mapped for use by multiple server processes.
Purpose
Share buffers and coordinate concurrent work.
Mechanism
Processes use PostgreSQL synchronization primitives, including locks and semaphores, to protect shared state.
Role
Coordinates backends and auxiliary processes.
Real-world analogy
A shared noticeboard and workbench in a workshop.
Technical explanation
Contains shared buffers, WAL buffers, lock and transaction state, and other structures; it is distinct from each process's private memory.
Shared buffers
Definition
The shared cache of relation pages maintained by PostgreSQL.
Purpose
Cache table and index blocks and provide a place to modify pages in memory.
Mechanism
A page is read into a buffer on a miss; modified buffers become dirty and are written later.
Role
Bridge backend page access and relation-file I/O.
Real-world analogy
Frequently used folders kept on a communal desk rather than fetched from an archive each time.
Technical explanation
Configured with shared_buffers; PostgreSQL's buffer manager coordinates pinning, locking, replacement, and dirty-page handling. The operating-system page cache may also cache file data.
WAL buffers
Definition
A shared-memory staging area for write-ahead log records.
Purpose
Collect records before they are written to WAL segment files.
Mechanism
Backends generate WAL records as they change data; records are flushed in the required order.
Role
Support redo-based recovery and transaction durability.
Real-world analogy
A numbered dispatch ledger that is copied to secure storage before the filing cabinet is updated.
Technical explanation
WAL buffers are distinct from shared buffers. A commit normally waits for the relevant WAL to reach durable storage according to synchronous_commit and the platform's sync guarantees.
Background processes
Definition
Server processes with system-level maintenance or replication responsibilities.
Purpose
Handle checkpointing, writing, vacuum, archiving, and WAL transport.
Mechanism
Coordinate through shared memory and perform specific scheduled or continuous duties.
Role
Maintain the database without assigning all work to client backends.
Real-world analogy
Specialist staff responsible for filing, cleaning, and transporting records.
Technical explanation
The background writer, checkpointer, WAL writer, autovacuum launcher/workers, and archiver have different responsibilities; process availability depends on configuration and workload.
Data files
Definition
Persistent relation files holding tables, indexes, and related structures.
Purpose
Store the database's durable page contents.
Mechanism
Relation pages are read into shared buffers and dirty pages are written to storage through PostgreSQL and the operating system.
Role
Long-term home for heap tuples and index entries.
Real-world analogy
The filing cabinets where the records ultimately live.
Technical explanation
Relation data is organized in pages and files under the cluster data directory; large relations span multiple segment files. WAL is required to recover data files after a crash.
WAL files
Definition
Sequential segment files containing WAL records.
Purpose
Support crash recovery, archiving, and replication.
Mechanism
Records are appended in log sequence order and replayed from a checkpoint after a crash.
Role
Make changes recoverable and committed transactions durable.
Real-world analogy
A time-ordered journal used to reconstruct the filing cabinets after a failure.
Technical explanation
WAL records describe changes; they are not a replacement for heap or index files. PostgreSQL redoes required changes during crash recovery.
Index files
Definition
Persistent relation files containing index access-method structures.
Purpose
Provide alternative ways to locate rows or evaluate supported operators.
Mechanism
The planner may choose an index scan; the executor follows index entries and fetches heap tuples when needed.
Role
Accelerate suitable lookups while adding storage and write-maintenance cost.
Real-world analogy
An index in a book points toward relevant pages but does not contain the whole story.
Technical explanation
Index entries can become dead or require maintenance under MVCC. Index-only scans can avoid some heap visits only when visibility-map and query conditions permit.

Non-technical

Each component solves one kind of problem: clients request, backends work, shared memory coordinates, background processes maintain, and files preserve state.

Technical

Do not treat “server,” “backend,” “shared memory,” and “disk” as interchangeable. Process boundaries, private versus shared state, and WAL versus relation files explain both concurrency and durability behavior.

03 · SQL execution

Query processing pipeline

When you send SQL, PostgreSQL processes it in five steps: check the writing, check that names and data types are valid, apply rules, choose how to find the data, and run the query.

PostgreSQL query-processing stages PostgreSQL checks the SQL, looks up table and column names, applies rules, chooses a way to find the data, then runs the query. Parsersyntax → parse tree Analyzernames · types · semantics Rewriterrules · views Planner / Optimizercosted execution plan Executorrows · data changes SQL textcatalog lookuprewritten treeplan nodesstorage access
This shows the usual order. The chosen plan may include steps such as scanning a table, joining tables, filtering rows, or sorting results.

Walkthrough: SELECT * FROM users WHERE id = 10;

  1. Parser: checks that the SQL is written correctly.
  2. Analyzer: checks that users and id exist and that the query uses them correctly.
  3. Rewriter: applies database rules. For example, it expands a view (a saved query) into the query that defines it.
  4. Planner / optimizer: chooses how to find the rows. It may read the whole table or use an index (a lookup structure), based on the table's size and available information.
  5. Executor: follows that plan, checks which row versions this query can see, and returns the matching rows.
EXPLAIN SELECT * FROM users WHERE id = 10;
EXPLAIN (ANALYZE, BUFFERS) SELECT * FROM users WHERE id = 10;

EXPLAIN shows how PostgreSQL plans to run a query without running it. EXPLAIN ANALYZE runs the query and reports what happened. Be careful with commands that change data: ANALYZE really does run them.

Plain English

PostgreSQL checks the query, confirms the names are valid, picks a way to find the data, then runs it.

Technical

The parser produces a parse tree; parse analysis resolves names and types; the rewrite system transforms query trees; the optimizer compares paths and constructs a plan tree; executor nodes evaluate it using the storage system.

04 · Working set

Memory architecture

PostgreSQL uses both shared and private memory. Shared memory is available to server processes. Each backend also has its own memory for tasks such as sorting query results. Some memory settings apply separately to every connection or task, so their total use can add up.

Shared and process-local PostgreSQL memory Shared memory holds cached data pages and change records used by multiple processes. Each backend also has private memory for query tasks and maintenance work. SHARED MEMORY · INSTANCE-WIDE BACKEND-LOCAL · PRIVATE Shared bufferscached heap and index pages WAL buffersrecords awaiting WAL writes Locks · transaction state · other shared structurescoordination among backends and server processes work_memsort / hash operation budget maintenance_work_memmaintenance operation budget separate regions
Conceptual scope, not a scale drawing. Work memory is a limit per eligible operation, not a single per-server allocation.
Memory areaScopeTypical use
Shared memoryShared by PostgreSQL processesBuffers, locks, transaction and coordination state
shared_buffersSharedPostgreSQL's cache for relation pages
wal_buffersSharedStaging generated WAL records
work_memBackend operationSorts and hash operations; multiple operations and sessions can consume it concurrently
maintenance_work_memMaintenance operationOperations such as VACUUM and index creation; worker concurrency matters
Backend-local memoryPrivate to a server processExecutor state, session state, and operation-specific allocations

When a backend needs a relation page, PostgreSQL checks shared buffers. A cache hit avoids a PostgreSQL data-file read; on a miss, the block is read into a buffer, often with help from the operating system's own page cache. A write dirties a buffer rather than forcing an immediate relation-file write.

Memory settings have workload-dependent consequences. For example, a query may have several sorts or hash operations, and many backends run concurrently. Setting work_mem high can therefore allow aggregate use far beyond the value shown for one operation.

Non-technical

Shared memory is the workshop's common benches. Each worker also has a personal work area. A larger personal allowance can help one task but, multiplied across many tasks and workers, can crowd the room.

Technical

shared_buffers is an instance-wide buffer pool; work_mem is applied per eligible plan operation, per backend; maintenance_work_mem applies to maintenance work. The operating-system cache is separate from PostgreSQL shared buffers.

05 · Persistent data

Storage architecture

A PostgreSQL installation stores its data in a database cluster (the data directory for one server instance). It can contain several databases. Each database can have schemas, which group tables and other objects. Tables and indexes are saved in files made up of small blocks called pages.

PostgreSQL logical and physical storage hierarchy One server's data directory contains databases. Databases contain schemas and tables. Tables are stored in pages; large values may use extra storage. Indexes and the change log are stored separately from table data. Database clusterone PostgreSQL instance Databasecatalog namespace Schemanamed objects Heap relationtable tuple versions Index relationaccess method data TOAST relationlarge values, if needed Pagestuples · line pointers table pages
The change log (WAL) is separate from table files. PostgreSQL keeps it in the pg_wal directory.

From a row to a disk page

  • A table's main storage is called the heap. It is a set of pages, each holding parts of the table's rows.
  • When a row changes, PostgreSQL usually stores a new version. It keeps the old version while an active query may still need it.
  • An index is a separate structure that helps PostgreSQL find rows faster. PostgreSQL can also read the table from start to finish when that is faster.
  • Very large values may be stored separately using TOAST. This is only needed for some values.
  • PostgreSQL keeps extra information about free space and row visibility to help with cleanup and some index lookups.

In a standard PostgreSQL build, each page is 8 KiB. Large tables can use more than one file. PostgreSQL maps names such as database, schema, and table to these files. Applications should use SQL and backup tools, not edit the files directly.

Plain English

Think of a database cluster as a filing room. It holds databases, each with named groups of tables. Tables are split into pages, and indexes help find rows without reading every page.

Technical

A cluster's data directory contains per-database relation files and cluster-wide state. Heap pages store tuple versions; indexes and TOAST relations are separate relation storage. WAL lives separately and supports recovery of relation pages.

06 · Durability

Write-ahead logging (WAL)

WAL (write-ahead log) is PostgreSQL's change log. It helps restore data after a crash and can send changes to another server. PostgreSQL saves a change in this log before it writes the changed table page. That way, the log can restore a change if the server stops unexpectedly.

WAL durability and data-page write flow A backend modifies a shared buffer and generates WAL records. WAL records pass through WAL buffers and are flushed to WAL segments before the commit acknowledgement. Dirty relation pages can be written later by background writer or checkpointer. WAL supports redo after a crash. Backendchange tuple / page Dirty shared bufferdata page in memory WAL buffersordered change records WAL segmentsflush before page write COMMIT may returnafter required WAL flush Relation filesdata page written later later page write durability point*
*Commit behavior depends on settings such as synchronous_commit, the transaction's durability mode, and storage guarantees. In standard synchronous local commit, the required WAL is flushed before success is reported.

What WAL does and does not do

  • When a tuple or index is changed, PostgreSQL generates WAL records and marks affected shared buffers dirty.
  • For a standard durable commit, PostgreSQL ensures WAL through the transaction's commit record is flushed before acknowledging COMMIT. Group commit can amortize a flush across transactions.
  • The changed heap and index pages do not need to reach their final relation files before COMMIT returns. A crash can be recovered by redoing changes from WAL after the last checkpoint.
  • WAL is not a second copy of the complete database and does not replace relation files. It is a change log whose records can be replayed.
  • Archiving WAL plus a valid base backup supports point-in-time recovery. Streaming replication can transport WAL to a standby.
BEGIN;
INSERT INTO users (username) VALUES ('Sami');
COMMIT;

Plain English

PostgreSQL writes each change in a log before saving the changed table page. If the server stops, it can use the log to finish saving the change when it starts again.

Technical

WAL records are generated in memory and written in LSN order. WAL-before-data ordering plus redo recovery allows commit to be durable without synchronously flushing every changed relation page. This guarantee depends on configured sync behavior and honest storage flush semantics.

07 · Concurrency

MVCC and transaction architecture

PostgreSQL uses multiversion concurrency control (MVCC) to handle readers and writers at the same time. When a row changes, PostgreSQL usually keeps the old version and creates a new one. A query sees the version that was current when that query began.

MVCC versions of a user row Transaction 40 creates a row version with xmin 40. Transaction 52 updates it, setting the old version's xmax to 52 and creating a new version with xmin 52. An older snapshot can continue to see the old version while a later snapshot sees the new version, subject to visibility rules. Tuple version Ausername = 'Sam' · xmin = 40xmax = 52 after update Tuple version Busername = 'Sami' · xmin = 52current version after commit UPDATE creates a version older snapshot may see Anewer snapshot may see B
Simplified visibility story: actual visibility depends on the transaction snapshot, commit status, command ID, and tuple metadata—not just comparing xmin and xmax numerically.

Tuple visibility and snapshots

  • xmin records the inserting transaction ID for a tuple version; xmax records a deleting or superseding transaction ID, with special states and meanings also possible.
  • A snapshot describes which transactions were in progress and which committed when a statement or transaction began. PostgreSQL uses transaction status and tuple metadata to determine visibility.
  • At Read Committed, each command gets a fresh snapshot. Repeatable Read uses a transaction-level snapshot. Serializable adds dependency tracking to detect executions that cannot be serialized safely.
  • MVCC reduces read/write blocking, but does not remove locks. Writes, DDL, explicit row locks, and conflicting operations can still wait or deadlock.
  • Obsolete tuple versions become dead tuples after no relevant snapshot can see them. VACUUM reclaims their space for reuse and maintains visibility information.
MechanismProtects / coordinatesTypical behavior
MVCC snapshotWhich tuple versions a statement can observeReaders commonly proceed without blocking writers
Row-level lockConflicting changes or explicit row-lock requestsCompeting writers can wait on the same row
Table-level lockOperations on a relation, including DDL and maintenanceModes conflict according to PostgreSQL's lock matrix
Advisory lockApplication-defined coordination keyMeaning is defined by the application, not automatically tied to a row

Plain English

Changing a row creates a new version instead of immediately replacing the old one. A query already in progress can finish reading the old version; a later query sees the new one.

Technical

MVCC visibility is snapshot-based. Tuple headers identify inserting and deleting/updating transactions; transaction status, snapshot boundaries, and command visibility determine which version is visible. Vacuum removes versions that are no longer potentially visible.

08 · Restart and consistency

Checkpoints and crash recovery

A checkpoint is a saved recovery point. PostgreSQL writes changed pages to disk and records the point in WAL. After a crash, the server can start recovery from there instead of checking the entire log. New changes can still be waiting to be saved after a checkpoint.

Checkpoint and crash recovery flow During normal operation, dirty buffers and WAL accumulate. A checkpoint writes required dirty pages and records a checkpoint location. After a crash, startup locates the last valid checkpoint and replays subsequent WAL records to redo changes. Dirty bufferschanged pages in memory Checkpointwrite pages · record LSN WAL after checkpointordered change records Startup recoveryredo WAL · open service checkpoint work WAL continues failure → replay data pages + checkpoint record are persisted uncommitted effects are not exposed as committed
Recovery uses WAL and transaction state to bring data files to a consistent state. Checkpoints reduce recovery work; WAL records remain essential between checkpoints.
  1. During normal operation, backends modify buffers and WAL records accumulate.
  2. The checkpointer writes dirty pages required for a checkpoint and records checkpoint information in WAL. The background writer can write pages earlier but does not replace checkpointing.
  3. After a crash, PostgreSQL locates the last valid checkpoint and replays relevant WAL forward to redo changes that may not yet be reflected in data files.
  4. Transaction state determines which transactions committed. Crash recovery is not equivalent to replaying arbitrary application SQL.

Non-technical

A checkpoint is a known, documented filing point. If the workshop loses power, staff start there and replay the later journal rather than reconstructing the entire history.

Technical

Checkpoint processing persists dirty buffers needed for the checkpoint and establishes an LSN for recovery. Startup redo replays WAL from the recovery start point; normal commit durability is obtained from WAL flush, not by synchronously checkpointing each transaction.

09 · Maintenance

Vacuum and autovacuum

Old row versions take up space after updates and deletes. VACUUM finds versions no active query needs and makes their space available for reuse. It usually keeps that space inside the table instead of returning it to the operating system.

Autovacuum lifecycle

  1. The autovacuum launcher checks which tables need work and starts cleanup workers.
  2. A worker reclaims space from old row versions. It can also collect statistics that help PostgreSQL choose how to run queries.
  3. PostgreSQL cannot remove an old version while an active query may still need it. Long-running transactions can delay cleanup.
  4. VACUUM FULL rebuilds a table to make it smaller and return space to the operating system. It takes a stronger lock and needs extra disk space while it runs.

ANALYZE collects summary information about table data. PostgreSQL uses it to choose query plans. Autovacuum can run this task too.

Transaction ID safety: PostgreSQL uses transaction numbers to track changes. These numbers have a limit, so vacuum updates old rows before the numbers can wrap around and become confusing. This work protects correctness.

Non-technical

Old editions stay available while someone may still be reading them. Vacuum clears editions nobody can need, tidies the index, and keeps the numbering system from running out of safe identifiers.

Technical

VACUUM removes dead tuple versions eligible under the vacuum horizon, updates the visibility map, and supports XID freezing. Autovacuum workers use per-table thresholds and wraparound safeguards. VACUUM FULL rewrites and takes a stronger lock.

10 · Access paths

Index architecture

An index is a separate lookup structure that can help PostgreSQL find rows without reading the whole table. PostgreSQL decides whether using it is faster. For a small table or a search that matches many rows, reading the whole table may be quicker.

Planner choice between sequential and index scans The planner compares a sequential scan of the heap with an index scan that probes an index and fetches candidate heap tuples, choosing a plan based on estimated costs and statistics. Plannerestimate costs Sequential scanread heap pages Index scanprobe index → heap rows Heap relationvisible tuple versions candidate Acandidate B
An index often points PostgreSQL to the table page that holds a row. In some cases, PostgreSQL can answer directly from the index.
Access methodUseful shapeKey trade-off
B-treeEquality, ranges, and ordered retrievalGeneral-purpose default; requires maintenance and storage
HashEquality comparisonsDoes not provide ordered range access
GINValues with multiple components, such as arrays and some full-text workloadsCan be large and relatively costly to update
GiST / SP-GiSTOperator-class-defined searches, including spatial and nearest-neighbor use casesBehavior depends on the selected operator class
BRINSummaries of block ranges, especially when values correlate with physical orderCompact, but less precise and may return more candidate pages

Indexes can speed up searches, but they use extra storage and must be updated whenever data changes. Add indexes based on queries your application runs, then check their effect with EXPLAIN (ANALYZE, BUFFERS).

Non-technical

An index is like a book's index: it points to likely pages, but for a broad search it can be faster to scan the whole book. Every extra index also makes updates and storage more expensive.

Technical

Access methods implement operator-class-specific search semantics. The planner compares estimated sequential, index, bitmap, and other paths; the executor performs the selected scan and applies MVCC visibility checks.

11 · High availability

Replication architecture

Replication keeps another PostgreSQL server up to date. The main server (primary) sends its change log to a second server (standby), which applies those changes to its own data. This can support recovery or help serve read requests.

PostgreSQL primary and standby WAL replication Client writes go to a primary backend. The primary produces WAL, which a WAL sender streams to a standby WAL receiver. The standby replays WAL against its local data files and can serve read-only queries when configured. PRIMARY STANDBY Backendapplication writes WAL senderstream changes WAL receiverreceive WAL WAL replaystandby data files WAL streaming replication read-only queries may use standby replication slot may retain required WAL
Replication slots prevent removal of WAL still needed by a consumer, but a stalled consumer can cause WAL retention and disk pressure.
ModeWhat is sentCommon use
Physical streamingWAL for physical changes to the clusterStandby servers, failover, read scaling
WAL archivingCompleted WAL segment filesPoint-in-time recovery and delayed standby recovery
Logical replicationDecoded row changes for publications and subscriptionsSelective table replication, integrations, and some upgrade workflows

Logical replication is distinct from physical replication: it publishes logical changes for selected tables and replays them into subscriber tables. It does not automatically replicate all database objects or DDL. Plan schema changes and sequence state separately. Replication slots and synchronous replication settings have operational consequences for retention, latency, and availability.

Plain English

The primary sends its change log to a second server. The second server applies those changes to keep its copy up to date.

Technical

Physical streaming transports WAL from primary walsender to standby walreceiver and replays it. Logical replication decodes WAL into row-level changes selected by publications and applied by subscriptions; its scope and guarantees differ.

12 · Full system trace

A FastAPI write, end to end

Here is what happens when an application adds a user and saves the change:

BEGIN;
INSERT INTO users (username) VALUES ('Sami');
COMMIT;
FastAPI insert and PostgreSQL commit flow FastAPI sends an INSERT over a pooled connection to its PostgreSQL backend. The backend parses and executes it, modifies shared buffers and generates WAL. PostgreSQL flushes required WAL before acknowledging a durable commit; the changed relation page may be written later. The response returns to FastAPI. FastAPIparameterized INSERT Backendsession process Executorinsert · constraints Shared buffersdirty heap / index WAL flushcommit record durable* Data page writecan happen later COMMITresponse separate I/O path
*Assumes the normal synchronous local-commit durability behavior. Configuration can weaken or extend the commit wait; verify the deployed settings and storage guarantees.
  1. Connection: FastAPI gets a connection from its pool. PostgreSQL has a backend process ready to handle that connection.
  2. Check the request: The driver sends the query and its values. PostgreSQL checks the query and plans how to add the row.
  3. Add the row: PostgreSQL updates the table and any indexes it needs. It keeps these changes in shared memory first.
  4. Record the change: PostgreSQL adds details to WAL, its recovery log.
  5. Save the transaction: With the usual settings, PostgreSQL writes the required log records to durable storage before it confirms COMMIT. It does not have to write the table page at this point.
  6. Reply: PostgreSQL tells FastAPI that the save succeeded. It can write the changed table and index pages later. If the server crashes first, it uses WAL to restore the confirmed change.
Durability boundary: synchronous_commit = off can acknowledge a transaction before its WAL is flushed, so a recent acknowledged transaction can be lost after an operating-system crash. Synchronous replication settings may add a standby acknowledgement to the commit wait. Neither mode means the changed data page must be flushed at commit.

Plain English

FastAPI sends the request to PostgreSQL. PostgreSQL records the change in its log and confirms it. It can save the table page later, because the log can restore the change if the server stops.

Technical

The backend executes the INSERT, dirties heap/index buffers, and emits WAL. Under normal synchronous local commit, it flushes WAL through the commit record before acknowledging; relation pages can remain dirty until later background/checkpoint I/O. Recovery redoes logged changes.

13 · At a glance

Quick reference

Component comparison

ComponentMain responsibilityShared or persistent?
PostmasterSupervise the instance and start connection backendsOperating-system process
BackendServe one client session and execute its commandsProcess with private memory and shared-memory access
Shared buffersCache relation pages and hold dirty page changesShared memory
WAL buffersStage change records before WAL writesShared memory
WAL segmentsRecord ordered changes for redo and replicationPersistent log files
Heap / index filesStore tuples and access-method structuresPersistent relation files
CheckpointerEstablish a recovery checkpoint and write required dirty buffersBackground process
AutovacuumReclaim eligible dead tuples, refresh statistics, prevent XID wraparoundLauncher and worker processes

Terminology

Backend
A PostgreSQL worker process that handles one client connection.
Cluster
The data directory and databases managed by one PostgreSQL server instance.
Dirty page
A data page changed in memory but not yet saved to its database file.
LSN
A numbered position in PostgreSQL's change log.
Snapshot
The set of row changes a query is allowed to see.
Tuple
A stored row. PostgreSQL may keep more than one version of a row.
WAL
Write-ahead log: the record of changes PostgreSQL can use to recover data.
TOAST
A PostgreSQL feature for storing very large values separately from the main table data.

Key takeaways

  • A backend executes work for one client; the postmaster manages connection setup and process supervision.
  • Shared buffers, WAL buffers, and process-local memory have different scopes and purposes.
  • WAL is a recovery log, not a replacement for table and index files.
  • Durable COMMIT normally waits for WAL flush, not for each changed data page to reach its final file.
  • MVCC snapshots explain row visibility; vacuum reclaims obsolete versions when they are safe to remove.
  • The planner chooses a cost-based plan; verify behavior with representative measurements and explain output.

Non-technical

PostgreSQL coordinates workers around shared workspaces, uses a durable journal to recover changes, and keeps older record versions until readers no longer need them.

Technical

Process isolation, shared-memory coordination, WAL redo, snapshot visibility, and asynchronous relation-page writes are the core mechanisms connecting query execution to durability and concurrency.

This guide describes PostgreSQL 18 behavior at a conceptual level. Configuration, platform, extensions, workload, and build options can affect operational details. Consult the versioned PostgreSQL documentation for exact behavior.