Processes and Shared Memory

Topics Covered

One Process per Connection

The postmaster

Backends and their lifetime

Why processes and not threads

The cost of many connections

When a backend crashes

Reading pg_stat_activity

Process names on the host

Signals and session control

Timeouts that protect the server

Shared Buffers and the Page Cache

Buffer descriptors, pins and locks

Clock sweep eviction

Double buffering with the operating system

Sizing shared_buffers

Ring buffers for big scans

Dirty pages and who writes them

Huge pages and memory mapping

Warming the cache after a restart

Private Memory and work_mem

What work_mem limits

Why the total can explode

Spilling to temporary files

Setting work_mem sensibly

Maintenance memory

Other private memory

Reading memory use in EXPLAIN

Memory and parallel query together

A worked budget

Background Processes

Checkpointer and background writer

WAL writer and WAL senders

Autovacuum launcher and workers

Statistics and logging

Parallel workers and background worker slots

Processes you will see on a replica

Logical replication and extension workers

Reading backend_type in practice

Startup, shutdown and the control file

When a helper falls behind

The Life of a Query

Parse, analyze and rewrite

Planning and the plan cache

Execution and the pull model

Commit and visibility

Where to look when a query is slow

Extended query protocol

Planning cost in partitioned schemas

Transactions around the query

Following one query with tools

PostgreSQL is built from ordinary operating system processes that cooperate through a region of shared memory. There are no green threads inside the server and no single process that handles every client. When you connect, the server starts a new process dedicated to your session, and that process parses, plans and executes every statement you send until you disconnect. This design dates back to the Berkeley POSTGRES project of the late 1980s, and it explains a surprising number of the operational facts that engineers run into later: why connections are expensive, why a few thousand idle clients can hurt a large server, why connection poolers are nearly universal and why a crash in one session forces every other session to reconnect.

The postmaster

The first process to start is the postmaster, the parent of everything else. It reads the configuration, allocates shared memory, opens the listening sockets and starts the auxiliary processes described later in this lesson. After that, its main job is to wait. When a client connects, the postmaster accepts the socket and calls fork to create a child process, called a backend, which inherits the shared memory mapping and the open socket. The postmaster then goes back to listening. It deliberately does very little else, because it is the one process that must never crash: if any child dies unexpectedly, the postmaster is the process that notices and decides what happens next.

Backends and their lifetime

A backend first performs authentication, using the rules in the host based access file, and then loads enough of the system catalogs to know about the database it connected to. From then on it is a single threaded program running one statement at a time on behalf of one client. It keeps private memory for caches of catalog entries, prepared statements and query plans, plus whatever working memory the current query needs for sorts and hashes. When the client disconnects, the backend exits and the operating system reclaims its private memory. You can see every backend, what it is doing and what it is waiting for in the pg_stat_activity view, one row per process.

The postmaster accepts each connection and forks a dedicated backend. Backends never share a client, but they all map the same shared memory.

Why processes and not threads

Processes give strong isolation for free. A bug that corrupts private memory in one backend cannot scribble over another backend private memory, because the operating system keeps their address spaces apart. Extensions written in C, which Postgres loads into the backend, benefit from the same protection. The model also made the code simpler in an era when thread libraries were immature and varied between Unix systems. The cost is overhead: forking a process, building its catalog caches and running authentication takes on the order of a few milliseconds, and each backend carries several megabytes of private memory even when idle. Threads would make connections cheaper, and the community has discussed a move to a threaded model for years, but the process model remains in every released version.

The cost of many connections

Because each connection is a process, the number of connections is a capacity decision, not a free parameter. The max_connections setting sizes several shared memory structures, including the array of process slots and the lock tables, so raising it costs memory even if the connections are never used. More importantly, every active backend competes for the same CPU cores, the same lock manager partitions and the same snapshot computations. Taking a snapshot requires scanning the array of running transactions, so its cost grows with the number of connections. Newer releases made snapshots much cheaper, but the rule of thumb still holds: a few hundred busy backends on a large server is reasonable, while thousands of mostly idle ones waste memory and add contention. The lesson on connection pooling returns to this in detail.

When a backend crashes

If a backend exits normally, nothing special happens. If it dies from a signal, such as a segmentation fault in an extension or the kernel out of memory killer, the postmaster cannot know whether that process left shared memory in a corrupted state, for example halfway through modifying a buffer or holding a spinlock. It therefore takes the conservative path: it signals every other backend to exit immediately, reinitializes shared memory and runs crash recovery by replaying the write ahead log from the last checkpoint. Every client sees its connection drop, and the server is unavailable for the seconds or minutes recovery takes. This is why the kernel out of memory killer is so dangerous for Postgres, and why production servers usually disable memory overcommit so that allocations fail cleanly instead.

A backend killed by a signal may have left shared memory half updated. The postmaster ends every session, replays WAL and only then reopens.

Reading pg_stat_activity

The single most useful view for understanding a running server is pg_stat_activity. Each row is one process, and the columns tell you the database and user, the client address, when the session started, when the current transaction started, when the current statement started, the text of the statement and the state, such as active, idle or idle in transaction. Two more columns, wait_event_type and wait_event, say what an active process is waiting on: a lock, an input or output operation, a lightweight lock inside shared memory or a client. When a server is slow, grouping this view by state and wait event is usually the fastest way to learn whether the problem is CPU, disk, locks or the application. Sessions in the idle in transaction state deserve special attention, because they hold snapshots and locks open while doing nothing, and later lessons show how that blocks vacuum and DDL.

Process names on the host

On a Linux host, each Postgres process rewrites its own command line so that tools such as ps and top show what it is. A backend appears with the user, database, client address and current activity, and auxiliary processes appear with names such as checkpointer, background writer, walwriter and autovacuum launcher. This makes it possible to correlate operating system metrics, like CPU or memory per process, with database activity. It also means that a stuck process can be investigated with standard tools such as strace or perf, which is a common technique when a backend spins on CPU without making progress.

Signals and session control

Because sessions are processes, controlling them uses ordinary signals sent through SQL functions. The pg_cancel_backend function sends an interrupt that cancels the running statement but leaves the session connected, which is the polite way to stop a runaway query. The pg_terminate_backend function asks the backend to exit entirely, rolling back any open transaction and closing the connection. Both are safe, because the backend handles the signal at a well defined point and cleans up its locks and buffers on the way out. Killing a backend from the shell with signal 9 is not safe, for exactly the reason described above: the postmaster will treat it as a crash and restart every session. Operators who learn this distinction once rarely forget it.

Timeouts that protect the server

Several settings exist to stop one session from harming the rest. The statement_timeout setting cancels any statement that runs longer than a limit, and is often set per role so that web requests get a short limit while reporting jobs get a long one. The lock_timeout setting cancels a statement that waits too long for a lock, which matters most for schema changes. The idle_in_transaction_session_timeout setting terminates sessions that open a transaction and then sit idle, a common symptom of application bugs that leak transactions. And idle_session_timeout ends sessions that stay idle outside a transaction. Setting these deliberately is cheap insurance, because a single forgotten session can hold locks and snapshots that affect the whole database for hours.

Connections are processes

Each client connection is a forked backend process with its own private memory, sharing one region of shared memory with every other backend. Connections are therefore expensive to create and to keep idle, and any backend crash makes the postmaster restart every session and replay WAL.

Postgres stores tables and indexes in files divided into 8 kilobyte pages, and it never reads or writes a row directly from disk. Every access goes through the shared buffer pool, an array of page sized slots in shared memory sized by the shared_buffers setting. A backend that needs a page first looks it up in a hash table that maps a page identity, made of the relation, fork and block number, to a buffer slot. If the page is there, the backend pins the buffer, takes a content lock for reading or writing and uses it in place. If not, it must find a slot to evict, possibly write the old contents out and then read the requested page in. Understanding this cache, and how it interacts with the operating system page cache below it, is the basis of nearly all memory tuning in Postgres.

Buffer descriptors, pins and locks

Each buffer slot has a descriptor holding the page identity, a usage count, a pin count, a dirty flag and a lightweight lock that protects the page contents. A pin says that some backend is using the buffer and that it must not be evicted. The content lock, taken in shared mode for reads and exclusive mode for writes, keeps one backend from seeing a page halfway through another backend modification. These locks are short lived and protect memory, not rows: row level locking is handled separately through the tuple headers and the lock manager. When a page in the buffer pool is modified, it is marked dirty, and it stays dirty until a checkpoint, the background writer or an evicting backend writes it back to the file.

Clock sweep eviction

When no free buffer is available, Postgres chooses a victim with an algorithm called clock sweep. Imagine the buffers arranged in a circle with a hand pointing at one of them. Each buffer has a usage count that is incremented, up to a maximum of five, every time a backend pins it. To find a victim, the hand advances around the circle. If the buffer under the hand is pinned, the hand skips it. If its usage count is above zero, the hand decrements it and moves on. The first unpinned buffer with a usage count of zero becomes the victim. Frequently used pages keep getting their counts refreshed and survive many sweeps, while pages touched once fall to zero after a single pass and are evicted. This approximates least recently used eviction at much lower cost, since a hit only increments a counter instead of moving an entry in a list.

The clock hand decrements usage counts as it passes. Hot pages keep high counts and survive, and the first buffer at zero is reused.

Double buffering with the operating system

Postgres uses buffered file input and output, not direct input and output. When it reads a page that is not in shared buffers, the kernel first looks in its own page cache, and only goes to the disk if the page is not there either. When Postgres writes a dirty page, the write lands in the kernel page cache and is flushed to the device later, or immediately when Postgres calls fsync. The result is two caches stacked on top of each other, and a page can be present in both at the same time. This double buffering is why the classic advice is to give shared_buffers about a quarter of RAM, not most of it: the kernel cache does useful work too, and a page cached in both places wastes memory. Recent releases have added experimental support for direct and asynchronous input and output, but on most production systems today the kernel cache remains a large part of the read path.

Sizing shared_buffers

A larger buffer pool reduces the number of reads that have to cross into the kernel and lowers the cost of hot pages, but it has costs. Changing it requires a restart. Very large pools make checkpoints write more dirty data at once. And the clock sweep has to walk more buffers to find victims under pressure. The usual starting point is 25 percent of RAM on a dedicated server, with the effective_cache_size setting, which only informs the planner, set to the combined size of shared buffers and the expected kernel cache, often 50 to 75 percent of RAM. From there, the pg_buffercache extension shows which relations occupy the pool and how much of it is dirty, and the hit ratios in pg_stat_database and pg_statio views show whether reads are mostly served from memory. A hit ratio below about 99 percent on an online workload is usually worth investigating.

A miss in shared buffers is not always a disk read. The kernel page cache below often has the page, and only a miss in both reaches the device.

Ring buffers for big scans

A single sequential scan of a large table would, without protection, push every hot page out of the buffer pool. Postgres guards against this with buffer access strategies. Large sequential scans, VACUUM and bulk writes such as COPY use a small private ring of buffers, 256 kilobytes for reads and somewhat more for vacuum and bulk writes, and recycle those same few buffers over and over instead of claiming fresh ones from the pool. The scan still goes through shared buffers, so concurrent readers can share pages, but it cannot evict the working set of the rest of the system. This is why a large analytic query on an online database can be slower than expected even if the table fits in memory: its pages are not being kept, because Postgres assumes a full scan is a one time event.

Dirty pages and who writes them

A dirty buffer must be written before its slot can be reused. Three actors do that writing. The checkpointer periodically writes every dirty buffer so that crash recovery has a bounded starting point. The background writer runs continuously, writing dirty buffers that the clock hand is about to reach, so that backends usually find clean victims. And when both fall behind, a backend that needs a slot writes the dirty victim itself, which adds latency to the query. The pg_stat_bgwriter and, in newer releases, pg_stat_checkpointer and pg_stat_io views count how many buffers each actor wrote. A large share of writes by backends is a sign that the background writer is tuned too conservatively or that the write load exceeds what the storage can absorb.

Huge pages and memory mapping

On Linux, shared memory for a large buffer pool is mapped with ordinary 4 kilobyte pages unless configured otherwise. With tens of gigabytes of shared buffers and hundreds of backends, each process needs page table entries covering the whole region, and the page tables themselves can consume gigabytes of memory. Enabling huge pages, 2 megabytes each, shrinks those page tables by a factor of about 500 and reduces pressure on the processor translation lookaside buffer, which improves performance measurably for large pools. The huge_pages setting can be set to try or on, and the operating system must reserve enough huge pages in advance. Transparent huge pages, the automatic variant, is a different feature and is usually disabled for database hosts because its background compaction can cause latency spikes.

Warming the cache after a restart

After a restart, shared buffers start empty, and the first queries after a failover or maintenance window run against a cold cache. For large working sets this can mean minutes of elevated latency while pages are read back in. The pg_prewarm extension addresses this in two ways. It can load a named relation into the buffer pool on demand, and its autoprewarm worker can periodically record which pages are in the pool and reload them automatically at startup. The kernel cache may also be warm after a quick restart of Postgres alone, but not after a host reboot or a failover to a replica that served different queries. Planning for a cold cache is part of planning a failover.

Read the hit ratio and who writes

Shared buffers hold 8 kilobyte pages in shared memory, evicted by clock sweep with usage counts, above a kernel page cache that also caches the same files. Start at about a quarter of RAM, check hit ratios in pg_statio views, and watch pg_stat_io for backends doing their own writes.

Shared buffers get most of the attention, but a large share of the memory a Postgres server uses at peak is private to backends. Every sort, hash join, hash aggregate, bitmap and materialization in a query plan needs working memory, and each of them is allowed to use up to the work_mem setting before spilling to temporary files on disk. Because the limit applies per operation and not per query or per connection, the total can be far larger than the setting suggests. Getting this right is one of the most consequential tuning decisions for an analytic workload and one of the most common causes of out of memory crashes on a busy online system.

What work_mem limits

The work_mem setting, 4 megabytes by default, caps the memory one plan node can use for its in memory data structure. A sort node keeps tuples in memory until the limit and then switches to an external merge sort that writes sorted runs to temporary files. A hash join builds its hash table on the inner input and, if the table would exceed the limit, splits the input into batches that are written to disk and processed one at a time. A hash aggregate builds groups in memory and, since version 13, spills groups to disk instead of growing without bound. Hash based nodes may use work_mem multiplied by the hash_mem_multiplier setting, which defaults to 2, because hashing benefits more from memory than sorting does.

Why the total can explode

A single query can contain several sort and hash nodes, and every one of them gets its own work_mem allowance. With parallel query, every worker process gets its own allowance too. Multiply that by the number of concurrent queries and the worst case becomes enormous. A server with 500 connections, work_mem at 64 megabytes and queries containing three hash nodes each could theoretically ask for nearly 200 gigabytes. In practice most queries use far less than their limit, which is why the setting can be raised safely for many workloads, but the arithmetic explains why a sudden burst of complex reporting queries can push a server into the out of memory killer even when the configuration looked conservative.

work_mem caps each sort or hash node, not the query. Several nodes per query and many concurrent queries multiply the real total.

Spilling to temporary files

When a node exceeds its allowance, it writes temporary files under the database directory, in the pgsql_tmp folder of the default or configured temporary tablespace. Spilling is not an error, and a sort that spills is often only a few times slower than one that fits, since it writes and reads sequentially. Hash joins that split into many batches can be worse, because skewed keys may produce a batch that still does not fit. EXPLAIN ANALYZE reports whether a sort used memory or disk and how many batches a hash used, and the log_temp_files setting logs every temporary file above a size threshold. The temp_file_limit setting caps how much temporary space one session can use, which protects the disk from a runaway query that would otherwise fill it.

A sort holds tuples in memory up to work_mem. Past that, it writes sorted runs to temporary files and merges them at the end.

Setting work_mem sensibly

A practical approach starts from the memory left after shared buffers and the operating system, divides it by the expected number of concurrently active queries and by a small factor for nodes per query, and uses the result as the default. Online workloads with simple queries can often use 16 to 64 megabytes. Analytic sessions can be given much more for a single transaction with SET LOCAL, which avoids raising the global value for everyone. Because the setting can be changed per role, per database and per session, the default should be safe for the busiest case, and larger values should be granted where they are known to help.

Maintenance memory

Operations that are not part of normal queries have their own setting. The maintenance_work_mem setting limits memory for CREATE INDEX, VACUUM, ALTER TABLE ADD FOREIGN KEY and similar commands, and defaults to 64 megabytes. Because few of these run at once, it can safely be much larger, often 1 to 2 gigabytes on a big server. For vacuum it matters a great deal: vacuum collects the identifiers of dead tuples in memory, and when that memory fills it must scan every index of the table before continuing, so a small value can make vacuum of a large table scan its indexes many times. Autovacuum workers use autovacuum_work_mem if it is set, and fall back to maintenance_work_mem otherwise, and each worker gets its own allowance.

Other private memory

Backends also keep catalog caches, relation caches and plan caches, which grow with the number of tables a session touches. Applications that use thousands of partitions or tables per session can see each backend grow to hundreds of megabytes, which adds up across many connections. Prepared statements keep their plans in memory too. Long lived connections in a pool therefore accumulate memory over time, which is one reason poolers often recycle server connections after a fixed lifetime. The pg_backend_memory_contexts view, available in recent releases, shows how a backend memory is divided among contexts and is the tool of choice for diagnosing a session that keeps growing.

Reading memory use in EXPLAIN

The clearest evidence of how a query uses working memory comes from EXPLAIN ANALYZE. A sort node reports its sort method, such as quicksort for an in memory sort, top N heapsort when a LIMIT lets it keep only the best rows, or external merge with the amount of disk used. A hash node reports the number of buckets, the number of batches and the peak memory, and a batch count above one means the hash table spilled. A hash aggregate reports its peak memory and any disk usage. Adding the BUFFERS option shows temporary blocks read and written by each node. Running a slow query once with these options before and after raising work_mem for the session gives a direct answer to whether memory is the bottleneck, instead of guessing from server wide settings.

Memory and parallel query together

Parallel query interacts with memory in ways that surprise people. Each parallel worker builds its own copy of a hash table for a parallel hash join only when the plan uses a non shared hash, while a parallel hash join shares one table across workers in dynamic shared memory, sized from work_mem times the number of participants. A parallel sort has each worker sort its share in its own memory before the leader merges them. In both cases the per query total is larger than the serial plan would use, which is the price of finishing sooner. When memory is tight, lowering max_parallel_workers_per_gather is often a better lever than lowering work_mem, because it reduces the multiplier without making every individual sort spill.

A worked budget

Consider a server with 256 gigabytes of RAM, 64 gigabytes of shared buffers and a peak of 120 active queries, most of them online lookups and a few reports. Reserving 32 gigabytes for the operating system and kernel cache headroom leaves about 160 gigabytes for private memory. Allowing an average of two memory hungry nodes per active query at 64 megabytes each, with hash nodes doubled, gives a worst case of about 120 times 192 megabytes, roughly 23 gigabytes, well inside the budget. A reporting role can then be given 1 gigabyte per node with a concurrency cap of five sessions through the pool, adding at most a few tens of gigabytes. Writing the budget down like this turns a vague fear of the out of memory killer into a checked plan.

work_mem multiplies

work_mem limits each sort or hash node, hash nodes get a multiplier on top, and every parallel worker and every concurrent query gets its own allowance. Budget it from nodes per query times concurrency, raise it per session where needed, and give maintenance_work_mem a generous separate value.

A running Postgres server is more than its backends. A set of auxiliary processes, started by the postmaster, perform work that no single session should be responsible for: writing dirty pages, flushing the write ahead log, running checkpoints, launching vacuum workers, archiving WAL files, streaming changes to replicas and collecting statistics. Each has a name you can see in pg_stat_activity, where the backend_type column distinguishes them from client backends. Knowing what each one does makes it much easier to read server metrics and to understand which settings tune which behavior.

Checkpointer and background writer

The checkpointer performs checkpoints: it writes every dirty buffer to its data file, fsyncs the files and records a checkpoint location in the WAL, so that crash recovery can start from that point. Checkpoints are triggered by time, through checkpoint_timeout, or by the amount of WAL generated, through max_wal_size, and the checkpointer spreads the writes across a fraction of the interval set by checkpoint_completion_target to avoid a burst. The background writer is a separate process that wakes up every few hundred milliseconds and writes a limited number of dirty buffers that the clock sweep is likely to reach soon. Its goal is not durability but latency: backends that find clean victims do not have to write pages themselves. The next lesson but one covers checkpoints in depth.

WAL writer and WAL senders

Every change is recorded in the write ahead log before the data page is written. Backends insert WAL records into shared WAL buffers, and a committing backend usually flushes the WAL up to its commit record itself. The WAL writer process flushes WAL buffers periodically in the background, which matters mostly for asynchronous commits, where backends do not wait for the flush. When replicas are connected, each one has a WAL sender process on the primary that reads WAL and streams it over the replication connection. On the replica, a WAL receiver process writes the incoming stream to disk and a startup process replays it. The archiver process, if archiving is enabled, copies completed WAL segment files to an archive location for backups and point in time recovery.

Backends change pages and log the change. Helper processes flush WAL, clean and write pages, mark checkpoints and stream WAL to replicas.

Autovacuum launcher and workers

The autovacuum launcher wakes up every autovacuum_naptime, one minute by default, and decides which databases need attention. For each one it starts an autovacuum worker, up to autovacuum_max_workers at once, three by default. A worker checks the statistics for every table in its database, and vacuums or analyzes the tables whose dead tuple counts or modification counts have crossed their thresholds. Workers throttle themselves with a cost based delay so that their reads and writes do not saturate the storage. Because autovacuum is the main defense against table bloat and transaction ID wraparound, its processes are among the most important on the server, and two later lessons are devoted to tuning them.

Statistics and logging

Postgres tracks how many tuples each table has inserted, updated and deleted, how many sequential and index scans it has had and when it was last vacuumed. Through version 14, a separate statistics collector process received these counters over a socket and wrote them to files. Since version 15 they live in shared memory, which removed a source of delay and lost updates. A separate logging collector process, when enabled, captures the server log output and writes it to log files with rotation. These processes are rarely the cause of problems, but they explain where the pg_stat views get their numbers and why those numbers can lag slightly behind reality.

Parallel workers and background worker slots

Queries that scan large tables can use parallel workers, which are separate processes started for the duration of one query. The leader backend divides the work, workers each scan part of the table and send tuples back through shared memory queues, and the leader combines the results. The max_worker_processes setting caps all background workers, including parallel query workers, logical replication workers and those started by extensions, while max_parallel_workers caps the parallel query share and max_parallel_workers_per_gather caps the workers for one query. When the pool of workers is exhausted, queries simply run with fewer workers than planned, which EXPLAIN ANALYZE reports as workers planned versus launched.

Processes you will see on a replica

A standby server runs a different set of auxiliary processes. The startup process replays WAL continuously, applying each record to data pages exactly as crash recovery would, which is why recovery speed and replica lag are closely related. The WAL receiver connects to the primary, receives the WAL stream and writes it to local WAL files. The checkpointer and background writer still run, performing restartpoints, the standby equivalent of checkpoints, so that a crash of the standby does not force it to replay everything from the beginning. Client backends on a hot standby can run read only queries while replay continues, and conflicts between those queries and replay are a topic of the replication lesson.

Logical replication and extension workers

The logical replication launcher starts apply workers for each subscription on a subscriber and table synchronization workers during the initial copy. On a publisher, logical replication uses WAL senders with logical decoding, which read the WAL and reconstruct row changes. Extensions can register their own background workers too: pg_cron runs scheduled jobs from a worker, pg_prewarm uses one for autoprewarm, and several monitoring and partition management extensions add their own. All of them draw from max_worker_processes, so a server with many extensions and parallel query enabled can run out of slots, and the symptom is often silent, such as a scheduled job that never started or a query that ran without its planned workers.

Reading backend_type in practice

A useful habit when investigating a server is to group pg_stat_activity by backend_type and state before looking at anything else. A healthy primary shows a handful of auxiliary processes, a number of client backends mostly idle or briefly active, and perhaps a few autovacuum workers. Too many autovacuum workers stuck on the same large table, a WAL sender whose replica is far behind, or client backends piling up in a lock wait each point at a different problem. Since the view also shows the query start time and the transaction start time for each process, it quickly reveals the oldest open transaction, which is often the root cause of bloat and replication slot growth discussed in later lessons.

Startup, shutdown and the control file

The postmaster also manages startup and shutdown. At startup it reads the control file, a small file in the global directory that records the database system state, the last checkpoint location and key settings such as the page size. If the state shows a clean shutdown, the server starts immediately. Otherwise it runs crash recovery. Shutdown comes in three modes: smart waits for all clients to disconnect, fast disconnects them and performs a final checkpoint, and immediate exits without a checkpoint, so the next start runs recovery. Fast is the usual choice for planned restarts. Knowing which mode was used explains why some restarts take seconds and others take minutes.

When a helper falls behind

Each auxiliary process has a characteristic symptom when it cannot keep up. A checkpointer that cannot finish within its interval produces log warnings that checkpoints are occurring too frequently and causes spikes in write latency. A background writer that is too timid shows up as backends writing their own buffers. An archiver that keeps failing leaves WAL files piling up in the pg_wal directory until the disk fills. A WAL sender whose replica is slow shows growing lag in pg_stat_replication. And autovacuum workers that are all busy on large tables leave smaller tables waiting, visible as rising dead tuple counts. Monitoring each of these signals is far cheaper than discovering them during an outage.

Learn the backend types

The checkpointer and background writer write dirty pages, the WAL writer flushes the log, WAL senders stream it to replicas, the archiver copies segments, the autovacuum launcher starts workers, and parallel workers help one query. pg_stat_activity lists them all in backend_type.

With the processes and memory in place, it is worth following a single statement from the moment it reaches a backend to the moment its results leave. The stages are the same for every query: parse, analyze and rewrite, plan, execute, and for writes, commit. Each stage uses a different part of the architecture, and each has its own way of going wrong. Knowing where a query spends its time is the first step in making it faster, and Postgres exposes enough information at each stage to find out.

Parse, analyze and rewrite

The backend first parses the SQL text into a raw parse tree, checking only syntax. The analyzer then resolves names against the system catalogs, turning table and column names into object identifiers, checking types and permissions and producing a query tree. The rewriter applies rules, most importantly expanding views into their underlying queries and applying row level security policies. These stages are usually fast, a fraction of a millisecond, but they read the catalogs, so a session that touches many tables for the first time spends noticeable time filling its catalog caches. They also take light locks on every relation mentioned, which matters when DDL is waiting, as the lesson on lock queues explains.

Planning and the plan cache

The planner considers ways to execute the query tree, such as scan methods, join orders and join algorithms, estimates the cost of each with the statistics gathered by ANALYZE and picks the cheapest. For simple queries planning takes well under a millisecond, but for queries joining many tables or many partitions it can take longer than execution. Prepared statements let a session parse and analyze once, and after five executions the backend may switch to a generic plan that ignores the specific parameter values, if the generic plan is not estimated to be much worse. The plan_cache_mode setting can force custom or generic plans. Because plan caches are per backend, a connection pool that hands out different server connections may lose the benefit, which is one of the subtleties covered in the pooling lesson.

Every statement is parsed, analyzed and rewritten, planned and executed in its backend. Execution reads pages through shared buffers and streams rows out.

Execution and the pull model

The executor runs the plan as a tree of nodes, each producing tuples on demand for its parent. The top node asks its child for a row, which asks its own children, down to the scan nodes that read pages from shared buffers. This pull model means a query with a LIMIT can stop early, since the top node simply stops asking. Rows are sent to the client as they are produced, unless the plan needs to see all input first, as a sort or a hash aggregate does. Because the executor reads pages through shared buffers, it shares cached pages with every other backend, and it is where most of the time of a typical query is spent.

Commit and visibility

For a write, the executor modifies tuples in shared buffers and inserts WAL records describing each change. At commit, the backend writes a commit record into the WAL and, with the default synchronous_commit setting, waits until the WAL is flushed to disk up to that record. Only then does it mark the transaction committed in the commit log and return success to the client. If synchronous replication is configured, it also waits for a standby to confirm. The modified data pages themselves are written later, by the background writer, the checkpointer or an evicting backend, because the WAL alone is enough to redo the change after a crash. Visibility to other sessions is governed by MVCC, the subject of the second section of the course.

A commit returns once its WAL record is on disk. The changed data page stays dirty in memory and is written much later.

Where to look when a query is slow

Each stage has a tool. Parse and plan time are reported by EXPLAIN ANALYZE as planning time, and very high values point to many joins, many partitions or cold catalog caches. Execution time per node is the main content of EXPLAIN ANALYZE output, covered in its own lesson. Waits on locks, input and output or the client appear in pg_stat_activity as wait events. Commit latency shows up as WAL sync waits and is governed by the storage and the synchronous_commit and replication settings. The pg_stat_statements extension aggregates all of this by query shape, showing total and mean time, rows and buffer hits and reads for every normalized statement, and is the first extension most teams install on a production server.

Extended query protocol

Clients can send statements in two ways. The simple query protocol sends the SQL text in one message and receives results. The extended protocol splits the work into parse, bind and execute messages, which lets the client send parameters separately from the SQL text, reuse a parsed statement many times and fetch results in batches. Most drivers use the extended protocol for parameterized queries, which avoids SQL injection by design because parameters are never interpreted as SQL. The extended protocol is also what makes prepared statements and generic plans possible, and its use of named statements per connection is why statement level poolers had trouble supporting it until recent PgBouncer releases added prepared statement tracking.

Planning cost in partitioned schemas

Planning time grows with the number of relations the planner must consider. A query against a table with thousands of partitions has to examine each one, at least to decide whether it can be pruned, and building the plan can take tens of milliseconds even when execution reads a single partition. Recent releases prune partitions earlier and more cheaply, including at execution time when a parameter value is known only then, but schema design still matters: a few hundred partitions is comfortable, while tens of thousands can make planning dominate for short queries. Prepared statements with generic plans help here, since a generic plan with runtime pruning is planned once and reused.

Transactions around the query

Every statement runs inside a transaction, either one the client opened explicitly or an implicit one that commits when the statement ends. A transaction takes a snapshot that decides which rows it sees, takes locks on the tables it touches and holds them until commit or rollback, and keeps its transaction ID visible to vacuum as long as it runs. Short transactions are therefore cheap for everyone, while long ones hold back cleanup and block conflicting DDL. Applications that wrap a web request in a transaction and then call slow external services inside it are a classic source of trouble, because the database sees a transaction that is open but idle for seconds at a time.

Following one query with tools

To make this concrete, a slow request can be followed through every layer. pg_stat_statements identifies the normalized query with the highest total time. EXPLAIN with the ANALYZE and BUFFERS options run in a session shows whether time goes to planning or execution, which node dominates and whether pages came from shared buffers or had to be read. pg_stat_activity during a slow run shows whether the backend is active on CPU, waiting on input and output or waiting on a lock. And the server log, with log_min_duration_statement and auto_explain configured, captures the plans of slow queries in production without anyone running them by hand. Each tool answers a different question, and together they cover every stage described in this lesson.

What good looks like at each level

A junior engineer knows Postgres keeps a cache of pages and that each connection costs resources. A mid level engineer explains the process per connection model, shared buffers with clock sweep over the kernel cache, work_mem per node and the main background processes. A senior engineer sizes memory from concurrency and plan shape, reads pg_stat_activity, pg_stat_io and pg_stat_statements to locate a bottleneck, and explains why a crash or the out of memory killer restarts every session.