PostgreSQL & Database Fundamentals
"The PostgreSQL server can handle multiple concurrent connections from clients. To achieve this it starts (“forks”) a new process for each connection." — PostgreSQL documentation, 1.2. Architectural Fundamentals
Summary: PostgreSQL is one supervisor process that forks a worker process per connection, shares one memory segment and one data directory, and describes itself in ordinary catalog tables. Focus: The process model, memory areas, data directory, catalogs, the cluster/database/schema/role hierarchy, configuration, extensions, psql, the wire protocol, driver anatomy in Go and Laravel, versions, and how it compares with MySQL, SQL Server and Oracle. Learning goal: Open a fresh cluster, name every process and directory you see, find any object in the catalogs, change a setting the right way (reload or restart), and know which chapter of this path explains each deeper question.
This is the entry page of the Databases path and the PostgreSQL deep dive. It is a complete reference for how a PostgreSQL server is put together from the outside: processes, memory, files, catalogs, naming, configuration, extensions, the client protocol and the two drivers this site uses (pgx for Go, the pgsql connector for Laravel). It does not re-teach the topics that have their own chapter (MVCC, WAL, indexes, planning, replication, partitioning); it names each one in one sentence and links to it. See the map of the other chapters.
Page map
| If you are looking for | Go to |
|---|---|
| Every process, every memory area, every directory in one table | Everything in one minute |
| Why one process per connection, and the restaurant analogy | Why it is built this way |
| Ingres, POSTGRES, Postgres95, PostgreSQL | Where it comes from |
| Postmaster, backends, background writer, checkpointer, WAL writer, autovacuum, archiver | Processes |
shared_buffers, work_mem, maintenance_work_mem, wal_buffers, effective_cache_size, huge pages | Memory |
PGDATA, base/, pg_wal/, pg_tblspc/, tablespaces, filenodes | Data directory |
pg_class, pg_attribute, pg_index, pg_namespace, pg_proc, pg_stat_*, information_schema | System catalogs |
Cluster, database, schema, role, search_path | Hierarchy and naming |
pg_stat_statements, pgcrypto, PostGIS, pgvector, TimescaleDB, Citus | Extensions |
\d, \x, \timing, \watch, \gexec | psql power use |
postgresql.conf, ALTER SYSTEM, pg_hba.conf, reload versus restart | Configuration |
| Simple versus extended protocol, prepared statements | The wire protocol |
pgx, database/sql, Laravel pgsql options | Connection anatomy: Go and Laravel |
| Major release cadence, 5-year support, PG 17, 18, 19 features | Versions |
| PostgreSQL against MySQL, SQL Server, Oracle, SQLite, MongoDB, CockroachDB, Redis | Positioning |
| Startup order, connection lifecycle, error codes | Mechanics |
| Too many connections, wrong schema, setting not applied | Solving the classic problems |
| Which tool for which situation | Choosing |
| Monolith to distributed data | In architecture |
| Every other chapter of the path | Map of the chapters |
| Hands-on tour of a fresh cluster | Lab |
| Wrong beliefs, cheat sheet, self-check, glossary | Misconceptions, Cheat sheet, Self-check, Glossary |
Everything in one minute
The processes. Each row is unpacked in Processes. Run SELECT pid, backend_type FROM pg_stat_activity to see them live.
Process (backend_type) | Job | If it stops |
|---|---|---|
| postmaster | First process; listens on port 5432, authenticates by pg_hba.conf, forks children, restarts after a crash | Nothing works; clients get connection refused |
| client backend | One per connection; parses, plans and executes your SQL | Only that session ends |
| checkpointer | Writes all dirty pages at a checkpoint, advances the recovery start point | Crash recovery gets longer, pg_wal grows |
| background writer | Trickles dirty buffers to disk so backends rarely write | Backends write more themselves; latency spikes |
| walwriter | Flushes wal_buffers to pg_wal between commits | Commits flush WAL themselves; slower |
| autovacuum launcher / worker | Starts workers that VACUUM and ANALYZE tables | Bloat, stale statistics, wraparound risk |
| archiver | Copies finished WAL segments (archive_command, archive_library) | Archive falls behind, pg_wal fills |
| logical replication launcher / worker | Starts apply workers for subscriptions | Logical subscribers stop applying |
| walsender / walreceiver | Streams WAL to a standby / receives it | Replica lag grows |
| startup | Replays WAL during crash or archive recovery, and on standbys | Server cannot finish starting |
| io worker (PG 18) | Executes asynchronous reads when io_method = worker | Falls back; reads stall |
| parallel worker | Helps one query scan or join in parallel | Query runs serially |
The memory areas. Unpacked in Memory.
| Area | Setting | Default | Change needs |
|---|---|---|---|
| Shared page cache | shared_buffers | 128MB | restart (postmaster) |
| Per sort or hash operation | work_mem | 4MB | per session SET |
| Hash tables multiplier | hash_mem_multiplier | 2.0 | per session SET |
| VACUUM, CREATE INDEX, ADD FOREIGN KEY | maintenance_work_mem | 64MB | per session SET |
| WAL not yet on disk | wal_buffers | -1 (1/32 of shared_buffers, 64kB to one WAL segment) | restart |
| Temporary tables | temp_buffers | 8MB | before first temp-table use in a session |
| Planner hint only | effective_cache_size | 4GB | per session SET; allocates nothing |
| Huge pages for the shared segment | huge_pages | try | restart |
| Connection slots | max_connections | 100 | restart |
The hierarchy and the catalogs. Unpacked in Hierarchy and Catalogs.
| Level | What it is | How to list it | Catalog |
|---|---|---|---|
| Cluster (instance) | One postmaster, one PGDATA, one port | SHOW data_directory | files under global/ |
| Role | User or group, shared by the cluster | \du | pg_authid, view pg_roles |
| Database | Isolated catalogs and files; a connection binds to one | \l | pg_database |
| Schema | Namespace inside a database | \dn | pg_namespace |
| Table, index, sequence, view | Relations | \d, \dt, \di | pg_class (relkind) |
| Column | Attribute of a relation | \d table | pg_attribute |
| Function, procedure | Routines | \df | pg_proc |
| Type | Base, composite, enum, domain | \dT | pg_type |
| Extension | Packaged set of objects | \dx | pg_extension |
| Tablespace | Directory for relation files | \db | pg_tablespace |
The three things to remember.
| Situation | Do this |
|---|---|
| Connection count grows with services and replicas | Budget max_connections across all pools, put PgBouncer in front (connection pooling) |
| A setting "did not apply" | Look at pg_settings.context and pending_restart: postmaster needs restart, sighup needs reload |
| An object "does not exist" | Check search_path and the current database before anything else |
Why it is built this way
PostgreSQL is an extensible, standards-heavy relational server whose design priorities are correctness, crash safety and extensibility. One of its oldest choices is a process per connection rather than a thread per connection. Processes isolate failures (a crashing backend cannot corrupt another's private memory) and keep the code simple, at the price of memory per connection and connection start-up cost. Everything that follows (shared memory, the postmaster, pooling) is the consequence of that choice.
| Process per connection (PostgreSQL) | Thread per connection or per task (MySQL, SQL Server, Oracle shared server) |
|---|---|
A bug or kill -9 in one backend is contained (the postmaster does restart all backends if shared memory may be damaged) | A bug can corrupt the whole process |
| Connection costs fork plus several MB of private memory | Cheaper per connection, more connections feasible |
| Shared state must live in an explicit shared memory segment | Shared state is just process memory |
| Pooling (PgBouncer) is close to mandatory above a few hundred clients | Built-in thread pools exist (MySQL Enterprise/Percona, SQL Server schedulers) |
| Each backend has its own catalog and plan caches | Caches can be shared across sessions |
The analogy we reuse: a restaurant. The postmaster is the host at the door: it seats parties and never cooks. Each party gets its own waiter (a backend) for the whole evening. The kitchen staff (checkpointer, background writer, WAL writer, autovacuum) work behind the scenes. The pantry on the counter is shared_buffers; the walk-in fridge is the operating-system cache; the cellar is PGDATA. The menu is the catalog, and the restaurant keeps its menu in the same notebooks it uses for recipes: PostgreSQL describes itself in ordinary tables.
Three common misunderstandings, up front
- “A database connection is cheap.” In PostgreSQL it is an operating-system process with private memory, and
max_connectionssizes shared memory at start. Thousands of idle connections are a cost, not a convenience. - “
shared_buffersshould be most of the RAM.” PostgreSQL also reads through the OS page cache. The documentation says more than about 40% of RAM is unlikely to help; 25% is “a reasonable starting value”. - “Database, schema and cluster are the same word.” A connection is bound to one database; a schema is a namespace inside it; a cluster is the whole server instance. Cross-database queries do not exist in one statement.
Where it comes from
PostgreSQL's own documentation tells the history in three steps. First, the Berkeley POSTGRES project:
"The POSTGRES project, led by Professor Michael Stonebraker, was sponsored by the Defense Advanced Research Projects Agency (DARPA), the Army Research Office (ARO), the National Science Foundation (NSF), and ESL, Inc. The implementation of POSTGRES began in 1986." — PostgreSQL documentation, 2.1. The Berkeley POSTGRES Project
Second, an SQL interpreter replaced the old query language:
"In 1994, Andrew Yu and Jolly Chen added an SQL language interpreter to POSTGRES. Under a new name, Postgres95 was subsequently released to the web to find its own way in the world as an open-source descendant of the original POSTGRES Berkeley code." — PostgreSQL documentation, 2.2. Postgres95
Third, the rename:
"By 1996, it became clear that the name “Postgres95” would not stand the test of time. We chose a new name, PostgreSQL, to reflect the relationship between the original POSTGRES and the more recent versions with SQL capability." — PostgreSQL documentation, 2.3. PostgreSQL
The project describes itself as having “more than 40 years of active development on the core platform”. About the first link of the chain, Ingres: POSTGRES was Stonebraker's follow-up to the earlier Ingres project at Berkeley (the name is usually explained as “post-Ingres”). That sentence comes from secondary sources and Stonebraker's own retellings, not from the documentation page above, so treat it as lore. The documentation also points to Joe Hellerstein's paper “Looking Back at Postgres” for another account.
| Era | Name | What changed |
|---|---|---|
| 1986 to 1994 | POSTGRES (Berkeley) | Extensible types, rules system, multiple storage managers; query language PostQUEL |
| 1994 to 1996 | Postgres95 | SQL replaced PostQUEL; code in ANSI C, about 25% smaller; libpq keeps the old name's echo |
| 1996 | PostgreSQL 6.0 | New name; version numbers resume the Berkeley sequence |
| Since PostgreSQL 10 | Two-part version numbers | Major version is the first number (10, 11, ... 19); minor releases are 18.7 |
| Yearly | A major release | Dump/restore or pg_upgrade needed between majors; supported 5 years |
The concept catalogue
Processes: postmaster and backends Must-know
In plain words: One boss process (the postmaster) listens for connections and starts a dedicated worker process (a backend) for each one. The boss also starts a small crew of long-running helpers.
Common misunderstanding: “PostgreSQL is multi-threaded, so a connection is a thread.” A session is an operating-system process (fork). Parallel query uses extra parallel worker processes, not threads.
Definition: The glossary defines the postmaster as “the very first process of an instance. It starts and manages the auxiliary processes and creates backend processes on demand”, and a backend as the “process of an instance which acts on behalf of a client session and handles its requests.”
postmaster (pid 1) client
1 listens on 5432 / unix socket connect()
2 accept() ------------------------> StartupMessage(user, database)
3 fork() -> backend (pid 4242)
4 backend reads pg_hba.conf rules (authentication method chosen)
5 backend: AuthenticationOk,
ParameterStatus x N, <- server_version, client_encoding...
BackendKeyData(pid, key), <- used later for cancel requests
ReadyForQuery
6 client sends Query / Parse / Bind ... backend runs it
7 Terminate or socket close -> backend exits; postmaster reaps itReal scenarios: 300 microservice replicas each with a pool of 10 open 3000 backends against max_connections = 100, so most fail with SQLSTATE 53300. An idle in transaction session holds a backend and a snapshot for hours. A runaway query is cancelled with pg_cancel_backend(pid) and an abandoned session killed with pg_terminate_backend(pid). A backend segfault makes the postmaster terminate all backends and run crash recovery (restart_after_crash, on by default).
| Aspect | PostgreSQL | MySQL (InnoDB) | SQL Server | Oracle |
|---|---|---|---|---|
| Unit of a session | OS process (backend) | Thread (thread_handling=one-thread-per-connection by default) | Task on a SQLOS scheduler (threads managed by the engine) | Dedicated server process, or shared server dispatchers |
| Connection cost | High (fork, private caches) | Medium | Low to medium | High (dedicated), lower (shared server) |
| Built-in pooling | None (use PgBouncer, pgcat, Odyssey, RDS Proxy) | Thread pool in Enterprise and Percona | Schedulers; client-side pools | Shared server, DRCP |
| Default port | 5432 | 3306 | 1433 | 1521 |
| Slot limit | max_connections (100) | max_connections (151) | Configured maximum user connections | processes / sessions |
Fix / how to use it:
-- See every process, including auxiliary ones.
SELECT pid, backend_type, state, application_name, wait_event_type, wait_event
FROM pg_stat_activity
ORDER BY backend_type, pid;
-- Connection budget.
SELECT current_setting('max_connections')::int AS max_conn,
current_setting('superuser_reserved_connections')::int AS superuser_reserved,
count(*) FILTER (WHERE backend_type = 'client backend') AS in_use
FROM pg_stat_activity;
-- Cancel the running statement, or end the session.
SELECT pg_cancel_backend(4242);
SELECT pg_terminate_backend(4242);Go: size the pool as a server budget, and label connections so they are visible.
// Command connect opens a pool through database/sql with the pgx stdlib
// driver and shows which session settings the server actually sees.
package main
import (
"context"
"database/sql"
"fmt"
"log"
"os"
"time"
_ "github.com/jackc/pgx/v5/stdlib" // registers the "pgx" driver
)
func main() {
// Parameters pgx does not know are sent to the server as runtime
// parameters, so search_path and application_name are set per session.
dsn := os.Getenv("DATABASE_URL")
if dsn == "" {
dsn = "postgres://app:secret@localhost:5432/appdb" +
"?sslmode=prefer&search_path=app,public&application_name=academy-api"
}
db, err := sql.Open("pgx", dsn)
if err != nil {
log.Fatal(err)
}
defer db.Close()
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
var buffers, path, app string
row := db.QueryRowContext(ctx, `SELECT current_setting('shared_buffers'),
current_setting('search_path'), current_setting('application_name')`)
if err := row.Scan(&buffers, &path, &app); err != nil {
log.Fatal(err)
}
fmt.Printf("shared_buffers=%s search_path=%s application_name=%s\n", buffers, path, app)
// SHOW is the psql-style way to read a single setting.
if err := db.QueryRowContext(ctx, "SHOW shared_buffers").Scan(&buffers); err != nil {
log.Fatal(err)
}
fmt.Println("SHOW shared_buffers:", buffers)
}Laravel: label the connection and read its backend.
<?php
declare(strict_types=1);
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
// Shows the backend that serves this connection and how the PDO layer
// talks to it. Laravel binds values as parameters, never into the SQL text.
class ProtocolDemo extends Command
{
protected $signature = 'db:protocol-demo';
protected $description = 'Show the backend behind the pgsql connection';
public function handle(): int
{
$row = DB::selectOne(
'select pg_backend_pid() as pid, current_database() as db, '
. 'current_setting(?) as app',
['application_name'],
);
$this->info("pid={$row->pid} database={$row->db} application_name={$row->app}");
// The server version string the driver negotiated.
$pdo = DB::connection()->getPdo();
$this->line('server: ' . $pdo->getAttribute(\PDO::ATTR_SERVER_VERSION));
// Listing the settings that a restart (not a reload) would change.
$pending = DB::select(
"select name, setting from pg_settings where context = 'postmaster' "
. 'and name in (?, ?, ?)',
['shared_buffers', 'max_connections', 'huge_pages'],
);
foreach ($pending as $p) {
$this->line("{$p->name} = {$p->setting} (restart to change)");
}
return self::SUCCESS;
}
}Auxiliary processes Must-know
In plain words: Besides the workers who serve you, the server runs a few permanent helpers that flush data to disk, clean up old row versions and ship WAL.
Common misunderstanding: “The statistics collector is a process I can see in ps.” It was removed in PostgreSQL 15: statistics are now kept in shared memory (the release notes say there is “no longer a separate statistics collector process”). Older books and blog posts still list it.
Definition: Each helper has one job.
| Process | Job (docs wording where quoted) | Key settings | Look at |
|---|---|---|---|
| checkpointer | “is responsible for executing checkpoints” | checkpoint_timeout (5min), max_wal_size, checkpoint_completion_target | pg_stat_checkpointer (PG 17), older pg_stat_bgwriter |
| background writer | “writes dirty data pages from shared memory to the file system” gently | bgwriter_delay, bgwriter_lru_maxpages | pg_stat_bgwriter |
| walwriter | “writes WAL records from shared memory to WAL files” | wal_writer_delay, wal_writer_flush_after | pg_stat_wal |
| autovacuum launcher | coordinates the workers that VACUUM and ANALYZE | autovacuum, autovacuum_max_workers, autovacuum_naptime | pg_stat_user_tables, pg_stat_progress_vacuum |
| archiver | copies completed WAL segments | archive_mode, archive_command, archive_library | pg_stat_archiver |
| logical replication launcher | starts apply workers for subscriptions | max_logical_replication_workers | pg_stat_subscription |
| walsender / walreceiver | streaming replication | max_wal_senders, primary_conninfo | pg_stat_replication, pg_stat_wal_receiver |
| startup | WAL replay during recovery | recovery_target_*, hot_standby | pg_stat_recovery_prefetch |
| WAL summarizer (PG 17) | records changed blocks for incremental backup | summarize_wal | pg_available_wal_summaries() |
| io worker (PG 18) | asynchronous I/O | io_method, io_workers | pg_aios, pg_stat_io |
time -> t0 t1 t2
backend UPDATE page 7 in shared_buffers (dirty), WAL record in wal_buffers
walwriter flush wal_buffers -> pg_wal (every wal_writer_delay)
backend COMMIT: flush WAL up to its LSN (synchronous_commit = on)
bgwriter write some dirty pages (LRU) -> data files
checkpointer write ALL dirty pages, fsync,
record checkpoint, recycle WALReal scenarios: pg_wal growing without bound because the archiver fails or a replication slot is stuck. A latency spike every 5 minutes that lines up with checkpoints. Autovacuum workers fighting a long-running transaction. A standby lagging because the walreceiver is blocked.
What each guarantees is the subject of durability and crash recovery, MVCC and VACUUM and replication and failover; here you only need to recognise them in ps and pg_stat_activity.
Fix / how to use it:
-- Checkpoint pressure: requested checkpoints should be rare.
SELECT num_timed, num_requested, write_time, sync_time, buffers_written
FROM pg_stat_checkpointer; -- PostgreSQL 17+; older: pg_stat_bgwriter
-- Is autovacuum keeping up?
SELECT relname, n_dead_tup, last_autovacuum
FROM pg_stat_user_tables ORDER BY n_dead_tup DESC LIMIT 10;// Go: the same query through database/sql (see catalog snippet above for the pattern).
// rows, err := db.QueryContext(ctx, "SELECT relname, n_dead_tup FROM pg_stat_user_tables ORDER BY 2 DESC LIMIT 10")// Laravel: DB::select('select relname, n_dead_tup from pg_stat_user_tables order by 2 desc limit 10');Memory areas Must-know
In plain words: PostgreSQL has one big shared pool (the page cache and a few control structures) that all processes use, and private memory that each query borrows for sorting and hashing.
Common misunderstanding: “work_mem is the memory a connection may use.” It is the base limit per sort or hash operation; one query can run several at once, hash nodes may use work_mem times hash_mem_multiplier, and parallel workers each get their own. The real worst case is many times the setting, times the number of sessions.
Definition:
| Area | Scope | Setting and default | Notes |
|---|---|---|---|
| Shared buffers | shared | shared_buffers, 128MB | PostgreSQL's page cache in 8kB pages; docs: start near 25% of RAM on a dedicated server of 1GB or more; above about 40% “unlikely” to help |
| WAL buffers | shared | wal_buffers, -1 | Auto size 1/32 of shared_buffers, at least 64kB, at most one WAL segment (16MB); flushed at every commit |
| Lock tables, proc array | shared | sized by max_connections, max_locks_per_transaction | Fixed at start |
| Cumulative statistics, SLRU caches | shared | track_counts, commit_timestamp_buffers, ... | pg_stat_* counters live here since PG 15 |
| Sort and hash memory | per operation | work_mem 4MB, hash_mem_multiplier 2.0 | Spills to temp files in base/pgsql_tmp when exceeded |
| Maintenance memory | per operation | maintenance_work_mem 64MB, autovacuum_work_mem -1 | VACUUM, CREATE INDEX, ALTER TABLE ADD FOREIGN KEY; autovacuum may use workers times this value |
| Temp table buffers | per session | temp_buffers 8MB | Only for temporary tables |
| Planner assumption | none | effective_cache_size 4GB | Allocates nothing; tells the planner how much cache a query may count on |
| Huge pages | OS | huge_pages = try, huge_page_size | Applies only to the main shared segment; see shared_memory_size_in_huge_pages |
| Plan, catalog, relation caches | per backend | plan_cache_mode, none for the rest | Rebuilt after invalidation |
time ->
1 Query: SELECT ... ORDER BY big_col (work_mem = 4MB)
2 backend sorts in memory until 4MB is reached
3 rows left over -> external merge sort -> temp files under base/pgsql_tmp
4 EXPLAIN (ANALYZE) shows "Sort Method: external merge Disk: 41296kB"
5 fix: SET work_mem = '64MB' for this session, or index the sort columnReal scenarios: an analytics endpoint spills 1 GB to disk per call; raising work_mem globally to 256MB then triggers the OOM killer under 200 connections. A database VM with 64GB sets shared_buffers = 16GB (25%) and leaves the rest to the kernel. A bulk index build is fast because the session raised maintenance_work_mem to 2GB for the duration.
| Product | Page cache | Per-query memory | Note |
|---|---|---|---|
| PostgreSQL | shared_buffers plus OS cache | work_mem per operation | Double caching; effective_cache_size is a hint |
| MySQL InnoDB | innodb_buffer_pool_size (often 50 to 75% of RAM; bypasses the OS cache with O_DIRECT) | sort_buffer_size, join_buffer_size per session | Opposite sizing philosophy |
| SQL Server | Buffer pool (max server memory) | Memory grants per query | Grants queue (RESOURCE_SEMAPHORE waits) |
| Oracle | SGA buffer cache | PGA (pga_aggregate_target) | Automatic memory management available |
| SQLite | OS cache plus cache_size | Per connection | Embedded; see SQLite |
Fix / how to use it:
SHOW shared_buffers; -- 128MB by default
SET work_mem = '64MB'; -- this session only
SET LOCAL work_mem = '256MB'; -- this transaction only
ALTER ROLE reporting SET work_mem = '128MB'; -- per role
ALTER DATABASE analytics SET maintenance_work_mem = '1GB';
-- Which settings need a restart?
SELECT name, setting, unit, context FROM pg_settings
WHERE name IN ('shared_buffers','wal_buffers','huge_pages','max_connections','work_mem');Go: read a setting back with SHOW and pg_settings.
// Command settings reads pg_settings to show where each parameter comes
// from and whether changing it needs a reload or a restart.
package main
import (
"context"
"database/sql"
"fmt"
"log"
"os"
"time"
_ "github.com/jackc/pgx/v5/stdlib"
)
const query = `
SELECT name, setting, COALESCE(unit, ''), context, source, pending_restart
FROM pg_settings
WHERE name IN ('shared_buffers', 'work_mem', 'maintenance_work_mem',
'wal_buffers', 'effective_cache_size', 'huge_pages',
'max_connections', 'search_path')
ORDER BY name`
func main() {
db, err := sql.Open("pgx", os.Getenv("DATABASE_URL"))
if err != nil {
log.Fatal(err)
}
defer db.Close()
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
rows, err := db.QueryContext(ctx, query)
if err != nil {
log.Fatal(err)
}
defer rows.Close()
fmt.Printf("%-22s %-12s %-10s %-18s %s\n", "name", "setting", "context", "source", "pending")
for rows.Next() {
var name, setting, unit, kind, source string
var pending bool
if err := rows.Scan(&name, &setting, &unit, &kind, &source, &pending); err != nil {
log.Fatal(err)
}
// context: postmaster = restart, sighup = reload, user = SET.
fmt.Printf("%-22s %-12s %-10s %-18s %t\n", name, setting+unit, kind, source, pending)
}
if err := rows.Err(); err != nil {
log.Fatal(err)
}
}Laravel: per-connection server_options and SET LOCAL inside a transaction.
use Illuminate\Support\Facades\DB;
DB::transaction(function () {
DB::statement("set local work_mem = '256MB'"); // dies with the transaction
$rows = DB::select('select customer_id, sum(total) from orders group by 1');
});Data directory, files and tablespaces Must-know
In plain words: Everything the server stores lives under one directory called PGDATA: your tables as plain files, the write-ahead log, and a few config files.
Common misunderstanding: “One table equals one file with the table's name.” Files are named by filenode numbers inside a directory named by the database OID; a big table is split into 1 GB segments; TRUNCATE or VACUUM FULL may change the filenode while the table keeps its OID.
Definition: Layout from the documentation (Database File Layout):
Item in PGDATA | Meaning |
|---|---|
PG_VERSION | Major version number |
base/ | Per-database subdirectories, named by the database's OID in pg_database |
global/ | Cluster-wide tables such as pg_database, plus pg_control |
pg_wal/ | WAL segments (16MB by default) |
pg_xact/, pg_multixact/, pg_subtrans/, pg_commit_ts/ | Transaction status data (SLRU) |
pg_tblspc/ | Symbolic links to user tablespaces |
pg_stat/, pg_stat_tmp/ | Statistics persisted at shutdown and temporary files |
pg_logical/, pg_replslot/ | Logical decoding state, replication slots |
pg_twophase/, pg_serial/, pg_snapshots/, pg_notify/, pg_dynshmem/ | Prepared transactions, serializable data, exported snapshots, LISTEN/NOTIFY, dynamic shared memory |
postgresql.conf, postgresql.auto.conf, pg_hba.conf, pg_ident.conf | Configuration (often moved to /etc/postgresql by distributions) |
postmaster.pid, postmaster.opts | Lock file with the PID, port and socket directory; last start options |
base/pgsql_tmp/ | Temporary files for spilling sorts and hashes |
Inside a relation's files: the main fork (16384), _fsm (free space map), _vm (visibility map), segments 16384.1, 16384.2, ..., and an associated TOAST table for large values (see Database Internals). Two tablespaces exist from the start: pg_default (for template1, hence default for new databases) and pg_global (shared catalogs). CREATE TABLESPACE fast LOCATION '/mnt/nvme/pgdata' makes a directory and a symlink in pg_tblspc/; objects placed there live under PG_<version>_<catversion>/<db oid>/. Tablespaces separate where files live and nothing else: they are not a security boundary and not a backup unit.
time ->
1 SELECT pg_relation_filepath('orders'); -- base/16398/16412
2 ls -l $PGDATA/base/16398/16412* -- 16412, 16412_fsm, 16412_vm, 16412.1
3 TRUNCATE orders; -- new relfilenode, old file removed
4 SELECT pg_relation_filepath('orders'); -- base/16398/16431 (OID unchanged)Real scenarios: a full disk on the pg_wal volume stops the server (put WAL on its own volume or alert on it); moving a hot index to NVMe with ALTER INDEX ... SET TABLESPACE fast; a clone from a file-system snapshot works only if PGDATA and WAL are snapshotted consistently (see backup, PITR and DR); initdb in PostgreSQL 18 enables data checksums by default (--no-data-checksums turns them off).
| Product | Storage unit | Files |
|---|---|---|
| PostgreSQL | Cluster of databases, heap files per relation | base/<db>/<filenode> |
| MySQL InnoDB | Tablespaces (file-per-table: .ibd), system tablespace, redo and undo logs | datadir/<schema>/<table>.ibd |
| SQL Server | Database = .mdf/.ndf data files plus .ldf log | filegroups |
| Oracle | Tablespaces made of datafiles, redo logs, control files | ASM or file system |
| SQLite | One file (plus -wal, -shm) | See SQLite |
Fix / how to use it:
SHOW data_directory;
SELECT pg_relation_filepath('orders');
SELECT oid, datname, pg_size_pretty(pg_database_size(oid)) FROM pg_database;
SELECT spcname, pg_tablespace_location(oid) FROM pg_tablespace;
CREATE TABLESPACE fast LOCATION '/mnt/nvme/pgdata';
ALTER TABLE big_events SET TABLESPACE fast; -- rewrites the table, takes ACCESS EXCLUSIVE// Go: pg_total_relation_size (table + indexes + TOAST) as in the catalog snippet.// Command catalog lists ordinary tables and their on-disk size by reading
// the system catalog (pg_class joined to pg_namespace).
package main
import (
"context"
"database/sql"
"fmt"
"log"
"os"
"time"
_ "github.com/jackc/pgx/v5/stdlib"
)
const query = `
SELECT n.nspname,
c.relname,
pg_total_relation_size(c.oid) AS total_bytes,
pg_size_pretty(pg_total_relation_size(c.oid)) AS total_size
FROM pg_class c
JOIN pg_namespace n ON n.oid = c.relnamespace
WHERE c.relkind = 'r'
AND n.nspname NOT IN ('pg_catalog', 'information_schema')
ORDER BY total_bytes DESC
LIMIT 20`
func main() {
db, err := sql.Open("pgx", os.Getenv("DATABASE_URL"))
if err != nil {
log.Fatal(err)
}
defer db.Close()
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
rows, err := db.QueryContext(ctx, query)
if err != nil {
log.Fatal(err)
}
defer rows.Close()
for rows.Next() {
var schema, table, pretty string
var bytes int64
if err := rows.Scan(&schema, &table, &bytes, &pretty); err != nil {
log.Fatal(err)
}
fmt.Printf("%-12s %-30s %10s\n", schema, table, pretty)
}
if err := rows.Err(); err != nil {
log.Fatal(err)
}
}// Laravel: Schema::getTables() gives portable metadata; sizes need raw SQL.
// DB::select('select relname, pg_size_pretty(pg_total_relation_size(oid)) from pg_class where relkind = ?', ['r']);<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
class TableSizes extends Command
{
protected $signature = 'db:table-sizes {--schema= : Limit the output to one schema}';
protected $description = 'List tables and their total on-disk size from the PostgreSQL catalog';
public function handle(): int
{
$schema = $this->option('schema');
// pg_class is the catalog of relations; relkind 'r' means ordinary table.
$rows = DB::select(
"SELECT n.nspname AS schema_name,
c.relname AS table_name,
pg_total_relation_size(c.oid) AS total_bytes,
pg_size_pretty(pg_total_relation_size(c.oid)) AS total_size
FROM pg_class c
JOIN pg_namespace n ON n.oid = c.relnamespace
WHERE c.relkind = 'r'
AND n.nspname NOT IN ('pg_catalog', 'information_schema')
AND (?::text IS NULL OR n.nspname = ?::text)
ORDER BY total_bytes DESC",
[$schema, $schema],
);
$this->table(
['Schema', 'Table', 'Total size'],
array_map(
fn (object $row): array => [$row->schema_name, $row->table_name, $row->total_size],
$rows,
),
);
return self::SUCCESS;
}
}System catalogs and information_schema Must-know
In plain words: PostgreSQL stores the description of your database (tables, columns, indexes, functions, roles) in ordinary tables you can SELECT from. The same trick is how psql's \d works.
Common misunderstanding: “information_schema is the real catalog.” It is the SQL-standard, portable view layer; pg_catalog is the native source with more detail and is faster. Tools such as psql and ORMs use pg_catalog.
Definition:
| Catalog | One row per | Key columns | Typical use |
|---|---|---|---|
pg_class | table, index, sequence, view, materialized view, composite type, foreign table, partitioned table or index | oid, relname, relnamespace, relkind (r, i, S, v, m, c, t, f, p, I), relfilenode, reltuples, relpages, relpersistence, relispartition | Find any relation and its file |
pg_attribute | column of any relation | attrelid, attname, atttypid, attnum, attnotnull, attisdropped | Column lists; dropped columns stay as ghosts |
pg_index | index | indexrelid, indrelid, indisunique, indisprimary, indisvalid, indkey | Find unused or invalid indexes |
pg_constraint | constraint | contype (p, u, f, c, x), conrelid, confrelid | Foreign key graph |
pg_namespace | schema | nspname, nspowner | List schemas |
pg_proc | function, procedure, aggregate | proname, prosrc, prosecdef, provolatile | Find a function, SECURITY DEFINER audit |
pg_type | data type | typname, typtype, typelem | Enums, domains, composite types |
pg_roles (view of pg_authid) | role | rolname, rolsuper, rolcanlogin, rolconnlimit | Who exists; pg_authid holds password hashes and needs superuser |
pg_database | database | datname, datistemplate, datallowconn, dattablespace | Shared by the cluster |
pg_extension | installed extension | extname, extversion | \dx |
pg_settings (view) | setting | name, setting, context, source, pending_restart, boot_val | Where a setting comes from |
pg_locks, pg_stat_activity | lock, session | see locks, observability | Live diagnostics |
The pg_stat_* views come from the cumulative statistics system (in shared memory since PostgreSQL 15; the documentation notes counters are flushed with a delay, so a view may lag slightly): pg_stat_activity, pg_stat_database, pg_stat_user_tables, pg_stat_user_indexes, pg_statio_user_tables, pg_stat_io (PG 16), pg_stat_checkpointer (PG 17), pg_stat_wal, pg_stat_replication, pg_stat_progress_*, plus pg_stat_statements from the extension.
time ->
1 psql: \d orders
2 psql runs (shown with psql -E): SELECT c.oid, n.nspname, c.relname
FROM pg_catalog.pg_class c
LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
WHERE c.relname OPERATOR(pg_catalog.~) '^(orders)$' ...
3 second query reads pg_attribute for the columns, pg_index for indexes, pg_constraint
4 psql formats it as the table you seeReal scenarios: list every table without a primary key before enabling logical replication; find invalid indexes left by a failed CREATE INDEX CONCURRENTLY; audit all SECURITY DEFINER functions without a pinned search_path; generate ALTER TABLE ... OWNER TO statements for a whole schema.
| Question | information_schema | pg_catalog |
|---|---|---|
| Portable to MySQL, SQL Server | Yes (standard views) | No |
Shows indexes, partitions, extensions, relkind | No or partial | Yes |
| Speed on large schemas | Slower (joins many views, permission filters) | Faster |
| Visibility | Only objects you own or may use | Everything readable (privileges still apply) |
Fix / how to use it:
-- Tables without a primary key.
SELECT n.nspname, c.relname
FROM pg_class c
JOIN pg_namespace n ON n.oid = c.relnamespace
WHERE c.relkind = 'r' AND n.nspname NOT IN ('pg_catalog','information_schema')
AND NOT EXISTS (SELECT 1 FROM pg_index i WHERE i.indrelid = c.oid AND i.indisprimary);
-- Portable column listing.
SELECT table_schema, table_name, column_name, data_type, is_nullable
FROM information_schema.columns WHERE table_schema = 'public' ORDER BY table_name, ordinal_position;
-- Invalid indexes.
SELECT indexrelid::regclass FROM pg_index WHERE NOT indisvalid;Go: the catalog snippet above lists the biggest tables. Laravel: Schema::getTables(), Schema::getColumns('orders'), Schema::getIndexes('orders') return metadata through the same catalogs.
Cluster, database, schema, role and search_path Must-know
In plain words: A server instance (cluster) holds several databases; a database holds schemas (folders for tables); roles (users and groups) are shared by the whole cluster.
Common misunderstanding: “I can join sales.orders in database sales with crm.customers in database crm.” Not without postgres_fdw or dblink. Schemas inside one database are the unit you can join across; a connection is bound to one database.
Definition: The documentation says an instance manages “exactly one database cluster with all its databases”. CREATE DATABASE copies template1 (or the template you name; template0 is the pristine one); the postgres database exists as a maintenance landing place. Roles are cluster-wide; there is no separate “user”: a login is a role with LOGIN. Privileges are GRANTs on objects; membership (GRANT role TO role) gives inheritance. Default and predefined roles include pg_read_all_data, pg_write_all_data, pg_monitor and pg_read_all_stats. Schemas are namespaces; unqualified names are resolved through search_path, whose default is "$user", public. The first existing schema on the path is also where new objects are created. pg_catalog is always searched first unless you list it. From PostgreSQL 15 CREATE on the public schema is no longer granted to everyone by default (the database owner keeps it); older databases migrated with pg_upgrade keep the old grant, so check.
time ->
1 psql -d appdb -U app
2 SHOW search_path; -- "$user", public
3 CREATE TABLE orders (id bigint); -- created in public (no schema "app" exists)
4 CREATE SCHEMA app AUTHORIZATION app;
5 SET search_path = app, public;
6 CREATE TABLE orders (id bigint); -- created in app.orders
7 SELECT * FROM orders; -- resolves to app.orders (first on the path)
8 SELECT * FROM public.orders; -- the other one; same name, different tableReal scenarios: one schema per tenant (see multi-tenancy); one schema per bounded context in a modular monolith; search_path pinned per role (ALTER ROLE app SET search_path = app) so a pooled connection never lands in the wrong place; a SECURITY DEFINER function that omits SET search_path = pg_catalog, pg_temp can be hijacked by a malicious schema earlier on the path (the documentation says a schema on the path “effectively trusts all users having CREATE privilege on that schema”).
| Concept | PostgreSQL | MySQL | SQL Server | Oracle |
|---|---|---|---|---|
| “Database” | Isolated catalogs; one per connection | Synonym of schema | Database (own files, log) | Instance or pluggable database (CDB/PDB) |
| “Schema” | Namespace inside a database | Same as database | Namespace inside a database (dbo) | A user's objects (schema = user) |
| Cross-database query | No (use postgres_fdw, dblink) | Yes (db.table) | Yes (db.schema.table) | Database links |
| Users | Roles, cluster-wide | user@host, global | Logins plus database users | Users, per database |
| Name resolution | search_path | Current database | Default schema of the user | Current schema |
Fix / how to use it:
CREATE ROLE app LOGIN PASSWORD 'change-me'; -- stored as SCRAM-SHA-256 by default
CREATE SCHEMA app AUTHORIZATION app;
REVOKE CREATE ON SCHEMA public FROM PUBLIC;
ALTER ROLE app IN DATABASE appdb SET search_path = app, public;
GRANT pg_read_all_data TO analyst;
SELECT current_user, current_database(), current_schemas(true);Go: put search_path in the DSN (search_path=app,public), as in the connect snippet above (pgx forwards unknown parameters as runtime parameters). Laravel: 'search_path' => 'app,public' in config/database.php (the connector issues set search_path to ... on connect), see ConnectionAnatomy.
Extensions Important
In plain words: An extension is a packaged add-on (types, functions, operators, index methods) you switch on per database with one command.
Common misunderstanding: “CREATE EXTENSION installs the software.” The files must already be on the server (apt install postgresql-18-pgvector, or your cloud's allow-list); CREATE EXTENSION runs the script that registers the objects inside a database. Some also need shared_preload_libraries and a restart.
Definition: CREATE EXTENSION name runs the extension's script and records its objects as one removable unit (DROP EXTENSION). Loading one “ordinarily requires the same privileges that would be required to create its component objects”, unless it is marked trusted in its control file. Extensions live per database (pg_extension), and contrib modules ship with PostgreSQL.
| Extension | What it adds | Needs shared_preload_libraries | Notes |
|---|---|---|---|
pg_stat_statements | Per-normalised-query timing, calls, rows, buffers | Yes | The first thing to install; see observability |
pgcrypto | Hashing (digest()), password hashing (crypt()), PGP and symmetric encryption functions | No | See encryption in use |
postgis | Geometry and geography types, spatial indexes (GiST, SP-GiST) | No | De facto standard for GIS |
pgvector (CREATE EXTENSION vector) | vector type, HNSW and IVFFlat indexes | No | See vector search |
timescaledb | Hypertables, compression, continuous aggregates for time series | Yes | Separate licence terms apply to some features |
citus | Distributed tables across worker nodes | Yes (must be first) | See partitioning and sharding |
pg_trgm, btree_gin, btree_gist | Trigram search, extra operator classes | No | See full-text search |
postgres_fdw, dblink | Query other PostgreSQL databases | No | Cross-database access |
pg_partman, pg_cron | Partition automation, in-database scheduler | pg_cron: Yes | Common managed-cloud extras |
pgaudit | Session and object audit logs | Yes | See database security |
pg_plan_advice (PG 19) | Control planner decisions (with pg_stash_advice) | Check the docs | New in PostgreSQL 19 release notes |
time ->
1 apt install postgresql-18-pgvector (files on the server)
2 psql: CREATE EXTENSION vector; (error 42501 if not allowed)
3 psql: \dx (listed with version)
4 For pg_stat_statements: shared_preload_libraries = 'pg_stat_statements'
5 restart the server, then CREATE EXTENSION pg_stat_statements;Real scenarios: managed services (Amazon RDS, Google Cloud SQL, Azure) publish an allow-list and no superuser; an upgrade breaks because an extension has no build for the new major; pg_upgrade needs the same extensions installed on the new server.
Fix / how to use it:
SELECT name, default_version, installed_version FROM pg_available_extensions WHERE name IN ('vector','postgis','pg_stat_statements');
CREATE EXTENSION IF NOT EXISTS pg_stat_statements;
SELECT query, calls, mean_exec_time FROM pg_stat_statements ORDER BY total_exec_time DESC LIMIT 5;
ALTER EXTENSION vector UPDATE;Go: run CREATE EXTENSION from a migration, not application start-up. Laravel: DB::statement('create extension if not exists pg_trgm') in a migration.
psql power use Important
In plain words: psql is the official command-line client; its backslash commands are shortcuts that run catalog queries for you.
Common misunderstanding: “\d is SQL.” Backslash commands are interpreted by psql itself, not sent to the server; with psql -E (or \set ECHO_HIDDEN on) you can see the SQL they run. They do not work in Go, PHP or any other driver.
Definition:
| Command | Does | Example |
|---|---|---|
\? / \h | Help for backslash commands / SQL syntax | \h CREATE INDEX |
\l | List databases | |
\c dbname | Connect to another database | \c appdb app |
\conninfo | Show current connection | |
\dn, \dt, \di, \dv, \ds, \dx, \du, \db, \df, \dT | List schemas, tables, indexes, views, sequences, extensions, roles, tablespaces, functions, types | \dt app.* |
\d name, \d+ name | Describe a relation (columns, indexes, constraints, triggers), + adds size and storage | \d+ orders |
\dconfig | Show configuration parameters (PG 16) | \dconfig *mem* |
\x, \x auto | Expanded (vertical) output | \x auto |
\timing | Print the time each statement took | |
\watch [interval] | Re-run the last query every N seconds (default 2) | \watch 5 |
\gexec | Execute each cell of the result as SQL | generate and run DDL |
\gset | Store a result row in psql variables | \gset ver_ |
\g file, \o file | Send results to a file or pipe | |
\copy | Client-side COPY using the local file system | \copy t FROM 'x.csv' CSV HEADER |
\e, \ef, \sf, \sv | Edit the buffer, edit a function, show function / view source | \sf my_func |
\i file, \ir file | Run a script (relative to current script) | |
\set, \unset, \pset | Variables and output format | \pset null '(null)' |
\errverbose | Show the last error with all fields (SQLSTATE, hint, position) | |
\bind, \parse, \close_prepared | Run a statement through the extended protocol with parameters | SELECT $1 \bind 42 \g |
\crosstabview | Pivot a result | |
\q | Quit |
time ->
1 appdb=# SELECT 'VACUUM ' || quote_ident(relname) AS cmd
2 appdb-# FROM pg_stat_user_tables WHERE n_dead_tup > 10000 \gexec
3 VACUUM orders
4 VACUUM events
5 appdb=# SELECT count(*) FROM pg_stat_activity WHERE state = 'active' \watch 2Real scenarios: run a nightly maintenance loop with \gexec; keep a \watch 1 window on pg_stat_activity during an incident; script migrations with psql -v ON_ERROR_STOP=1 -1 -f migration.sql (-1 wraps the file in one transaction); store defaults in ~/.psqlrc (\set HISTSIZE 5000, \x auto, \timing on) and connection parameters in ~/.pgpass and pg_service.conf.
Fix / how to use it:
\x auto
\timing on
SELECT pid, now() - query_start AS runtime, left(query, 60) FROM pg_stat_activity WHERE state <> 'idle' ORDER BY 2 DESC \watch 2
SELECT format('ALTER TABLE %I.%I OWNER TO app', schemaname, tablename) FROM pg_tables WHERE schemaname = 'app' \gexecGo and Laravel have no equivalent shortcut layer: use the catalog queries from System catalogs or Schema::getTables(). Environment variables (PGHOST, PGPORT, PGUSER, PGDATABASE, PGPASSWORD, PGSSLMODE, PGAPPNAME) work for psql, pg_dump, libpq clients and pgx alike.
Configuration: files, ALTER SYSTEM, reload versus restart Must-know
In plain words: Settings come from several layers; later and narrower layers win. Some can change while the server runs, a few need a full restart.
Common misunderstanding: “I edited postgresql.conf and the setting is live.” The file is only re-read on SIGHUP (reload), and parameters whose context is postmaster ignore a reload until restart; pg_settings.pending_restart tells you.
Definition: The documentation: “The configuration file is reread whenever the main server process receives a SIGHUP signal; this signal is most easily sent by running pg_ctl reload from the command line or by calling the SQL function pg_reload_conf().” ALTER SYSTEM writes postgresql.auto.conf, which is read after postgresql.conf. pg_file_settings pre-tests file changes. allow_alter_system = off (PG 17) forbids ALTER SYSTEM for managed setups.
| Layer (later wins) | Where | Applies to |
|---|---|---|
| Built-in default | boot_val in pg_settings | all |
postgresql.conf and include files | PGDATA or /etc/postgresql/<ver>/main | cluster |
postgresql.auto.conf | written by ALTER SYSTEM | cluster |
| Command line | postgres -c name=value, pg_ctl -o | cluster |
ALTER DATABASE ... SET | catalog pg_db_role_setting | new sessions in that database |
ALTER ROLE ... SET (optionally IN DATABASE) | catalog pg_db_role_setting | new sessions of that role |
| Connection options | options=-c work_mem=64MB, Laravel server_options | one connection |
SET, SET LOCAL, set_config() | session or transaction | until reset |
pg_settings.context | Meaning | Examples |
|---|---|---|
internal | Compile-time, read-only | block_size, server_version_num |
postmaster | Restart required | shared_buffers, max_connections, wal_level, huge_pages, shared_preload_libraries |
sighup | Reload is enough | log_min_duration_statement, checkpoint_timeout, autovacuum_naptime |
superuser-backend, backend | Fixed at connection start | log_connections, ignore_system_indexes |
superuser | SET by superusers or granted SET privilege | session_replication_role |
user | Any session may SET | work_mem, search_path, statement_timeout |
pg_hba.conf (host-based authentication) is a separate file with the same reload rule. Its records are examined sequentially and the first match wins; each record is type database user address method. Types: local, host, hostssl, hostnossl, hostgssenc, hostnogssenc. Methods include trust, reject, scram-sha-256, md5 (deprecated since PG 18, warns on use), password, peer, ident, cert, gss, sspi, ldap, pam, bsd, oauth (PG 18) and, until PG 19 removed it, radius. pg_ident.conf maps OS or certificate names to roles. listen_addresses defaults to localhost, so remote access needs it changed (restart) and an hba line (reload).
time ->
1 ALTER SYSTEM SET shared_buffers = '4GB'; -- writes postgresql.auto.conf
2 SELECT pg_reload_conf(); -- t
3 SHOW shared_buffers; -- still 128MB
4 SELECT name, pending_restart FROM pg_settings WHERE name = 'shared_buffers'; -- t
5 pg_ctl restart -D $PGDATA -- (or systemctl restart postgresql)
6 SHOW shared_buffers; -- 4GBReal scenarios: a pager goes off because max_connections was raised without restart planning; a standby refuses to start because max_connections is lower than the primary's; log_min_duration_statement = 250ms is toggled live during an incident with ALTER SYSTEM plus reload; the hba file edit that locks everyone out (always keep a local ... peer line for the postgres OS user and test with pg_hba_file_rules).
| Product | Config file | Live change |
|---|---|---|
| PostgreSQL | postgresql.conf, pg_hba.conf | SET, ALTER SYSTEM + reload |
| MySQL | my.cnf | SET GLOBAL, SET PERSIST |
| SQL Server | sp_configure, startup flags | RECONFIGURE |
| Oracle | spfile | ALTER SYSTEM SET ... SCOPE=BOTH |
| Redis | redis.conf | CONFIG SET, CONFIG REWRITE |
Fix / how to use it:
SELECT name, setting, context, source, pending_restart FROM pg_settings WHERE name ~ 'mem|connections';
ALTER SYSTEM SET log_min_duration_statement = '250ms';
SELECT pg_reload_conf();
SELECT sourcefile, name, setting, applied, error FROM pg_file_settings WHERE error IS NOT NULL;
SELECT line_number, type, database, user_name, auth_method, error FROM pg_hba_file_rules;Go: the settings snippet above prints context and pending_restart. Laravel: server_options and timezone in config/database.php (see ConnectionAnatomy).
The wire protocol: simple versus extended query Important
In plain words: A client talks to a backend with messages. In the simple protocol you send one string of SQL. In the extended protocol you first prepare the statement, then send only the parameter values, as often as you like.
Common misunderstanding: “A prepared statement is a PHP or Go feature.” It is a protocol feature: Parse, Bind, Execute messages (SQL-level PREPARE/EXECUTE exists too). Drivers decide whether to use them, and a pooler in transaction mode can break named statements that live in one backend.
Definition: From the documentation: a simple query cycle “is initiated by the frontend sending a Query message”, and the extended protocol “breaks down the above-described simple query protocol into multiple steps. The results of preparatory steps can be re-used multiple times for improved efficiency. Furthermore, additional features are available, such as the possibility of supplying data values as separate parameters instead of having to insert them directly into a query string.”
| Message | Direction | Purpose |
|---|---|---|
StartupMessage, SSLRequest, GSSENCRequest | client | Open a session (protocol 3.0; 3.2 since PG 18) |
AuthenticationOk, AuthenticationSASL | server | Auth outcome (SCRAM-SHA-256 uses SASL) |
ParameterStatus, BackendKeyData, ReadyForQuery | server | Settings the client must know; cancel key; idle/in-transaction/failed status |
Query | client | Simple protocol: SQL text, may hold several statements |
Parse, Bind, Describe, Execute, Sync, Close | client | Extended protocol steps |
RowDescription, DataRow, CommandComplete, ErrorResponse | server | Results and errors (SQLSTATE) |
CopyInResponse, CopyData | both | COPY sub-protocol |
NotificationResponse | server | LISTEN/NOTIFY |
CancelRequest | client (new connection) | Cancel a running query |
Terminate | client | Close the session |
time -> client backend
1 Parse("stmt1", "SELECT * FROM t WHERE id = $1") ->
2 Describe(S "stmt1") ->
3 Sync ->
4 <- ParseComplete, ParameterDescription, RowDescription
5 <- ReadyForQuery(I)
6 Bind("", "stmt1", [42]) Execute("", 0) Sync ->
7 <- BindComplete, DataRow, CommandComplete, ReadyForQuery
8 Bind("", "stmt1", [43]) Execute("", 0) Sync -> (no Parse: plan reuse)Real scenarios: SQL injection is blocked by parameters because the values never become SQL text; PgBouncer in transaction pooling mode breaks named prepared statements unless the pooler supports protocol-level prepared statements (PgBouncer added that in 1.21; check your version and max_prepared_statements) or the driver uses unnamed or simple mode; an application loops over 10 000 inserts and a prepared statement cuts parse and plan time; a generic plan after several executions is worse for a skewed column (plan_cache_mode = force_custom_plan fixes it, see query planning).
| Layer | Setting | Effect |
|---|---|---|
| pgx | QueryExecModeCacheStatement (default) | Extended protocol with a per-connection prepared-statement cache |
| pgx | QueryExecModeCacheDescribe | Cache descriptions only |
| pgx | QueryExecModeDescribeExec | Describe each time, unnamed statement; two round trips |
| pgx | QueryExecModeExec | Extended protocol, one round trip, no named statements (pooler-friendly) |
| pgx | QueryExecModeSimpleProtocol | Simple protocol; client-side interpolation; multiple statements |
Go database/sql + pgx stdlib | DSN default_query_exec_mode=exec | Same choice through the DSN |
| PHP PDO pgsql | PDO::ATTR_EMULATE_PREPARES (Laravel uses the default, off) | Server-side prepares; true interpolates client-side |
| libpq | PQexecParams, pipeline mode (PG 14) | Extended protocol, batching round trips |
psql | \bind | Run one statement with extended protocol |
Fix / how to use it:
PREPARE by_id (bigint) AS SELECT * FROM orders WHERE id = $1;
EXECUTE by_id(42);
SELECT name, statement, generic_plans, custom_plans FROM pg_prepared_statements;
SET plan_cache_mode = force_custom_plan; -- auto (default), force_generic_plan
DEALLOCATE by_id;Go: the native pgx pool with an explicit query-exec mode:
// Command protocol shows the native pgx pool and how the query execution
// mode maps onto PostgreSQL's simple and extended query protocols.
package main
import (
"context"
"fmt"
"log"
"os"
"time"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
)
func main() {
dsn := os.Getenv("DATABASE_URL")
if dsn == "" {
dsn = "postgres://app:secret@localhost:5432/appdb?application_name=academy-api"
}
cfg, err := pgxpool.ParseConfig(dsn)
if err != nil {
log.Fatal(err)
}
// Pool size is a server-side budget: every connection is one backend.
cfg.MaxConns = 10
cfg.MinConns = 2
cfg.MaxConnLifetime = 30 * time.Minute
cfg.MaxConnIdleTime = 5 * time.Minute
cfg.HealthCheckPeriod = time.Minute
// Default mode: extended protocol, prepared statements cached per
// connection. Behind a transaction-mode pooler use QueryExecModeExec
// (extended protocol, unnamed statements) or QueryExecModeSimpleProtocol.
cfg.ConnConfig.DefaultQueryExecMode = pgx.QueryExecModeCacheStatement
cfg.ConnConfig.StatementCacheCapacity = 512
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
pool, err := pgxpool.NewWithConfig(ctx, cfg)
if err != nil {
log.Fatal(err)
}
defer pool.Close()
// Parameters travel in Bind, apart from the SQL text, so a value like
// "x'; DROP TABLE t;--" can never change the statement's shape.
var pid int32
var backend string
err = pool.QueryRow(ctx,
`SELECT pid, backend_type FROM pg_stat_activity WHERE pid = pg_backend_pid() AND datname = $1`,
"appdb").Scan(&pid, &backend)
if err != nil {
log.Fatal(err)
}
fmt.Printf("served by backend pid=%d type=%s\n", pid, backend)
// Override the mode for one call: the simple protocol sends one text
// message and allows several statements separated by semicolons.
rows, err := pool.Query(ctx, `SELECT 1; SELECT 2`, pgx.QueryExecModeSimpleProtocol)
if err != nil {
log.Fatal(err)
}
rows.Close()
if err := rows.Err(); err != nil {
log.Fatal(err)
}
stat := pool.Stat()
fmt.Printf("pool: total=%d idle=%d acquired=%d max=%d\n",
stat.TotalConns(), stat.IdleConns(), stat.AcquiredConns(), stat.MaxConns())
}Laravel: DB::select($sql, $bindings) always binds parameters through PDO; see the command in Processes.
Versions and release policy Important
In plain words: A new major version comes about once a year; each is supported for five years, with a fix release at least every three months.
Common misunderstanding: “Minor upgrade needs a dump and restore.” Only major upgrades do (pg_upgrade, dump/restore, or logical replication). Minor upgrades are a binary swap and restart, and the project recommends always running the latest minor.
Definition: The versioning policy: “The PostgreSQL Global Development Group releases a new major version containing new features about once a year.” and “supports a major version for 5 years after its initial release. After this, a final minor version will be released and the software will then be unsupported (end-of-life).”
| Major | First release | Final release (EOL) | Current minor (page read 2026-11-25) |
|---|---|---|---|
| 19 | 2026-11-19 | 2031-11-19 | 19.0 |
| 18 | 2025-09-25 | 2030-11-14 | 18.7 |
| 17 | 2024-09-26 | 2029-11-08 | 17.12 |
| 16 | 2023-09-14 | 2028-11-09 | 16.16 |
| 15 | 2022-10-13 | 2027-11-11 | 15.20 |
| 14 | 2021-09-30 | 2026-11-12 | 14.25, no longer supported |
Headline features from the release notes (only what the notes list):
| Version | Headline features (from the release notes) |
|---|---|
| PostgreSQL 17 | New memory management for VACUUM; SQL/JSON constructors and JSON_TABLE(); streaming I/O for sequential reads and better write throughput under concurrency; multi-value B-tree searches; logical replication failover control; pg_createsubscriber; pg_upgrade preserves logical slots; sslnegotiation=direct; incremental backup in pg_basebackup; COPY ... ON_ERROR ignore; pg_stat_checkpointer; allow_alter_system |
| PostgreSQL 18 | Asynchronous I/O subsystem (io_method); pg_upgrade keeps optimizer statistics; skip scan on multicolumn B-tree; uuidv7(); virtual generated columns (the default); OAuth authentication; OLD/NEW in RETURNING; temporal constraints; data checksums on by default in initdb; MD5 passwords deprecated; wire protocol 3.2 |
| PostgreSQL 19 | REPACK command (and REPACK (CONCURRENTLY)); pg_plan_advice and pg_stash_advice; automatic scaling of I/O workers; quicker foreign-key checks; logical replication enabled without restart when wal_level = replica; logical replication of sequences; WAIT command for read-your-writes on standbys; parallel autovacuum of indexes with prioritisation scoring; RADIUS support removed; standard_conforming_strings always on |
time ->
1 pg_upgrade --check -b /usr/lib/postgresql/17/bin -B /usr/lib/postgresql/18/bin ...
2 stop old cluster, run pg_upgrade (--link for speed)
3 start new cluster; run ANALYZE (PG 18 keeps statistics, older versions need it)
4 every extension needs its binaries for the new majorReal scenarios: planning an upgrade window before a version's final release date; choosing uuidv7() for ordered primary keys (see ID generation) only on PG 18 or later; waiting on PG 19's WAIT before building read-your-writes on replicas by hand (see replication); managed clouds often lag the community by months.
| Product | Cadence | Support |
|---|---|---|
| PostgreSQL | Yearly major, minor at least quarterly | 5 years per major |
| MySQL | LTS and innovation releases (8.4 LTS, 9.x) | Oracle's schedule |
| SQL Server | Roughly every 2 to 3 years | Mainstream plus extended (10 years total) |
| Oracle | Yearly innovation, long-term releases (19c, 23ai) | Premier plus extended support |
Fix / how to use it:
SELECT version();
SHOW server_version; -- 18.7
SHOW server_version_num; -- 180007 (compare numerically in code)Go: read it with SHOW server_version_num or conn.PgConn().ParameterStatus("server_version"). Laravel: DB::connection()->getPdo()->getAttribute(PDO::ATTR_SERVER_VERSION).
Positioning: PostgreSQL against the others
| Dimension | PostgreSQL | MySQL (InnoDB) | SQL Server | Oracle | SQLite | MongoDB | CockroachDB | Redis |
|---|---|---|---|---|---|---|---|---|
| Model | Object-relational | Relational | Relational | Relational / multi-model | Embedded relational | Document | Distributed SQL (PostgreSQL wire) | Key-value / structures |
| Licence | PostgreSQL licence (permissive) | GPL + commercial | Commercial | Commercial | Public domain | SSPL | BSL / commercial | Changed across versions; check the current terms |
| Process model | Process per connection | Thread per connection | SQLOS schedulers | Dedicated or shared server | In-process library | Threads | Go processes per node | Single-threaded command execution |
| Default isolation | Read Committed | Repeatable Read | Read Committed (locking) | Read Committed | Serializable (one writer) | Snapshot inside a transaction | Serializable | Atomic commands |
| MVCC | Heap row versions, VACUUM | Undo logs, purge | Row versioning in tempdb (optional) | Undo segments | WAL snapshots | WiredTiger MVCC | MVCC on KV (Pebble) | Not applicable |
| Extensibility | Types, operators, index AMs, extensions, PL languages | Plugins, storage engines | CLR, extended procs | PL/SQL, cartridges | Loadable extensions | Aggregation stages | Limited | Modules |
| Replication | Physical streaming, logical | Binlog, Group Replication | Always On, log shipping | Data Guard, GoldenGate | Litestream (external) | Replica sets | Raft ranges | Replication, Cluster |
| Strongest at | Correctness, SQL breadth, extensions, JSONB | Simple OLTP web apps, replication ecosystem | Microsoft stack, tooling | Enterprise, RAC, partitioning | Embedded, local, edge | Flexible documents | Multi-region SQL | Caching, queues |
Chapters: MySQL storage engines, SQLite, MongoDB, Redis, NoSQL families, distributed SQL and consensus.
| When PostgreSQL is the right default | When something else wins |
|---|---|
| Transactional core with constraints, joins, JSONB side data, full-text and vectors in the same store | Single-file app or test database: SQLite |
Strong SQL, window functions, CTEs, MERGE, partitioning, row level security | Simple read-heavy web app on existing MySQL ecosystem: MySQL |
| Extension needs (PostGIS, pgvector, TimescaleDB) | Global multi-region writes with automatic failover: CockroachDB, Spanner |
| Team wants open source without vendor lock-in | Latency-critical cache or counters: Redis |
| Reporting and OLTP mixed at moderate scale | Wide-column write firehose: Cassandra / ScyllaDB |
Mechanics
Startup sequence
time ->
1 pg_ctl start (or systemd) runs the postgres binary: this process becomes the postmaster
2 read postgresql.conf, postgresql.auto.conf; check postmaster.pid (lock file)
3 allocate shared memory (shared_buffers, WAL buffers, lock tables ...) and semaphores
4 startup process: read pg_control, find last checkpoint, replay WAL (crash recovery)
5 start checkpointer, background writer, walwriter, autovacuum launcher, archiver, logical replication launcher
6 open listen sockets (listen_addresses, port); status becomes "ready to accept connections"
7 for each connection: fork a backendConnection lifecycle and costs
A new connection costs: TCP (and TLS) handshake, fork, authentication (SCRAM-SHA-256 is several round trips and some CPU), loading catalog caches. That is why drivers pool, and why connect_timeout and retry logic matter. Idle backends cost memory but little CPU; idle in transaction backends also hold snapshots and block vacuum; idle_in_transaction_session_timeout, statement_timeout, lock_timeout and tcp_keepalives_* (or keepalives* client-side) are the guards.
Error codes you meet on day one
| SQLSTATE | Name | Message (typical) | Meaning and fix |
|---|---|---|---|
53300 | too_many_connections | FATAL: sorry, too many clients already | Slots exhausted; pool, raise max_connections, add PgBouncer |
53300 | too_many_connections | remaining connection slots are reserved for roles with the SUPERUSER attribute | Only reserved slots left |
28P01 | invalid_password | password authentication failed for user "app" | Wrong password or hash type |
28000 | invalid_authorization_specification | no pg_hba.conf entry for host "10.0.0.5", user "app", database "appdb", no encryption | Add or fix the hba line, reload |
3D000 | invalid_catalog_name | database "x" does not exist | Wrong database (not wrong schema) |
3F000 | invalid_schema_name | schema "app" does not exist | Missing schema or typo in search_path |
42P01 | undefined_table | relation "orders" does not exist | Wrong search_path, not created, or case-folded quoted name |
42704 | undefined_object | type "vector" does not exist | Extension not installed in this database |
42501 | insufficient_privilege | permission denied for table orders | Missing GRANT; also thrown by CREATE EXTENSION for non-trusted |
57P01 | admin_shutdown | terminating connection due to administrator command | pg_terminate_backend or server stop; reconnect |
57P03 | cannot_connect_now | the database system is starting up | Recovery in progress; retry with backoff |
55P02 | cant_change_runtime_param | parameter "shared_buffers" cannot be changed without restarting the server | Needs restart |
25P03 | idle_in_transaction_session_timeout | terminating connection due to idle-in-transaction timeout | Fix the leak in the client |
57014 | query_canceled | canceling statement due to statement timeout | Expected with statement_timeout; retry carefully |
Solving the classic problems
| Problem | Cause | Solution | Cost or limit |
|---|---|---|---|
too many clients already | Pools times replicas exceed max_connections | PgBouncer in transaction mode, smaller app pools, budget per service | Session features (advisory locks, SET) need session pooling |
relation does not exist | Wrong search_path or database | Qualify names, set search_path per role, check current_database() | Pooled connections may reset settings (use ALTER ROLE ... SET) |
| Setting "did not apply" | postmaster context | ALTER SYSTEM then restart, check pending_restart | Restart means downtime or failover |
| Queries slow after a restart | Cold shared_buffers and OS cache | pg_prewarm, warm traffic; pg_prewarm.autoprewarm | Takes minutes at scale |
Disk full in pg_wal | Stuck replication slot or failed archive_command | Fix archiving, drop or advance the slot, set max_slot_wal_keep_size | Dropping a slot breaks its consumer |
| Idle sessions pile up | Client never closes | idle_session_timeout, idle_in_transaction_session_timeout | Clients must reconnect cleanly |
| Cannot connect remotely | listen_addresses = 'localhost', firewall, hba | Set listen_addresses, add hostssl ... scram-sha-256 line, reload | Restart for listen_addresses |
| Which database is biggest | Unknown | pg_database_size, pg_total_relation_size | Sizes include bloat |
-- Who is using my connection budget?
SELECT usename, application_name, state, count(*)
FROM pg_stat_activity WHERE backend_type = 'client backend'
GROUP BY 1,2,3 ORDER BY count(*) DESC;
-- Pin the schema per role so pooled connections cannot drift.
ALTER ROLE app SET search_path = app, public;
-- Keep idle sessions from piling up.
ALTER ROLE app SET idle_in_transaction_session_timeout = '60s';Go: handle SQLSTATE through *pgconn.PgError and keep the pool bounded.
// import "github.com/jackc/pgx/v5/pgconn" and "errors"
var pgErr *pgconn.PgError
if errors.As(err, &pgErr) && pgErr.Code == "53300" {
// too_many_connections: back off and retry later, do not retry in a tight loop.
}Laravel: catch (\Illuminate\Database\QueryException $e) and check $e->getCode() (the SQLSTATE) against '53300', '57P03'.
Retries and failure handling
| Error | Meaning | Retry? | How |
|---|---|---|---|
57P03 starting up | Server in recovery | Yes | Exponential backoff with jitter, cap at seconds to minutes |
53300 too many clients | Pool exhaustion | Yes, with limits | Backoff; fix the pool, do not hammer |
57P01 admin shutdown | Failover or restart | Yes (new connection, idempotent work only) | Reconnect; pgx pool health checks discard the dead connection |
08006 connection failure | Network drop | Yes if the transaction can be replayed | Never retry a commit whose outcome is unknown without idempotency |
40001, 40P01 | Serialization failure, deadlock | Yes, whole transaction | See isolation levels, deadlocks |
28P01, 28000 | Auth failure | No | Fix credentials or hba |
42P01, 3F000 | Wrong schema or object | No | Fix configuration |
Connection anatomy: Go and Laravel
| Piece | Go (pgx, database/sql) | Laravel (pgsql driver) |
|---|---|---|
| Driver | github.com/jackc/pgx/v5; stdlib adapter registers "pgx" for database/sql | pdo_pgsql extension via PDO |
| Pool | pgxpool (MaxConns, MinConns, MaxConnLifetime, MaxConnIdleTime, HealthCheckPeriod) or db.SetMaxOpenConns, SetMaxIdleConns, SetConnMaxLifetime | None built in: one PDO per worker process (FPM, Octane worker, queue worker) |
| DSN / URL | postgres://user:pass@host:5432/db?sslmode=verify-full&application_name=x | DB_URL or host, port, database, username, password keys |
| Session settings | Unknown DSN parameters become runtime parameters (search_path, statement_timeout) | search_path, timezone, synchronous_commit, isolation_level, server_options |
| TLS | sslmode: disable, allow, prefer, require, verify-ca, verify-full; sslrootcert | sslmode, sslcert, sslkey, sslrootcert copied into the DSN |
| Keep-alive | keepalives via libpq-style parameters, pgx ConnConfig dialer | keepalives, keepalives_idle, keepalives_interval, keepalives_count |
| Prepared statements | Extended protocol, cache per connection (QueryExecModeCacheStatement) | PDO server-side prepares by default |
| Read/write split | Manual (two pools) | read and write host arrays, sticky |
| Application name | application_name= | application_name key |
| Env defaults | PGHOST, PGUSER, PGPASSWORD, ~/.pgpass, pg_service.conf | .env (DB_*) |
Laravel's connector source shows exactly what it does on connect: default PDO options (ERRMODE_EXCEPTION, CASE_NATURAL, STRINGIFY_FETCHES false), a DSN of pgsql:host=...;dbname='...' with optional port, client_encoding, application_name, SSL and keepalive keys, then separate statements for timezone, search_path, isolation level (set session characteristics as transaction isolation level ...) and synchronous_commit. server_options becomes options='-c name=value' in the DSN.
Laravel configuration with every option the connector reads:
<?php
// config/database.php (excerpt) - every option the pgsql connector reads.
return [
'connections' => [
'pgsql' => [
'driver' => 'pgsql',
'url' => env('DB_URL'),
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '5432'),
'database' => env('DB_DATABASE', 'laravel'),
'username' => env('DB_USERNAME', 'app'),
'password' => env('DB_PASSWORD', ''),
'charset' => 'utf8',
'search_path' => 'app,public',
// Becomes: set time zone 'UTC'
'timezone' => 'UTC',
// Becomes: set synchronous_commit to 'off' (per connection).
'synchronous_commit' => env('DB_SYNC_COMMIT', 'on'),
// Becomes: set session characteristics as transaction isolation level ...
'isolation_level' => 'read committed',
// Passed in the DSN as "-c name=value" start-up options.
'server_options' => [
'statement_timeout' => '30s',
'lock_timeout' => '5s',
'idle_in_transaction_session_timeout' => '60s',
],
// Copied into the DSN when present.
'sslmode' => env('DB_SSLMODE', 'verify-full'),
'sslrootcert' => env('DB_SSLROOTCERT'),
'keepalives' => 1,
'keepalives_idle' => 30,
'application_name' => env('APP_NAME', 'laravel') . '-web',
],
],
];Laravel basic configuration (as used in the earlier chapters):
<?php
// config/database.php (excerpt) - the pgsql connection block.
return [
'default' => env('DB_CONNECTION', 'pgsql'),
'connections' => [
'pgsql' => [
'driver' => 'pgsql',
'url' => env('DB_URL'),
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '5432'),
'database' => env('DB_DATABASE', 'laravel'),
'username' => env('DB_USERNAME', 'root'),
'password' => env('DB_PASSWORD', ''),
'charset' => 'utf8',
'prefix' => '',
'prefix_indexes' => true,
// Applied with "set search_path" when the connection opens.
'search_path' => env('DB_SEARCH_PATH', 'app,public'),
// Passed into the DSN; verify-full also checks the server name.
'sslmode' => env('DB_SSLMODE', 'prefer'),
// Shows up in pg_stat_activity.application_name.
'application_name' => env('APP_NAME', 'laravel') . '-web',
],
],
];Read search_path, shared_buffers and application_name back from Go (the connect snippet above) and from the Laravel command in Processes. The details of pool sizing are in connection pooling; ORM behaviour in ORM pitfalls.
Choosing
| Situation | Recommendation | Extra technique | Reason |
|---|---|---|---|
| New transactional service, unsure of the database | PostgreSQL | Start with one cluster, one database, schemas per module | Broadest feature set, one fewer system |
| Hundreds of app replicas | PostgreSQL + PgBouncer (transaction mode) | Per-service pool budget | Process per connection |
| Multi-tenant SaaS, few tenants | Schema per tenant or tenant_id + RLS | ALTER ROLE ... SET search_path | See multi-tenancy |
| Needs full-text, geo, vectors | Extensions inside PostgreSQL first | pg_trgm, PostGIS, pgvector | Fewer moving parts |
| Mixed OLTP and heavy reporting | Read replica for reports | statement_timeout, separate role and work_mem | Keep primary latency stable |
| Settings per workload | Role-level ALTER ROLE ... SET | work_mem, statement_timeout per role | Safe, no restart |
| Upgrades | pg_upgrade --link or logical replication | Read release notes for each major in between | Avoid long downtime |
| Embedded or edge | SQLite | Litestream | Not a server |
In architecture: from a single process to a distributed system
Monolith (one process, one database)
One application, one PostgreSQL cluster, one database, one app schema, one role for the application, one for migrations, one read-only for analysts. Defaults are fine to start: shared_buffers at 25% of RAM, max_connections = 100, a pool of 10 to 20 per app instance, pg_stat_statements on. Example: a Laravel monolith on one VM with PHP-FPM; each FPM worker holds one backend, so 50 workers need 50 slots plus queue workers and Horizon.
Modular monolith / multiple databases
Bounded contexts become schemas (billing, catalog, identity), each owned by its own role with GRANT USAGE only on what it may read; cross-schema foreign keys are allowed but a design smell. Pin search_path per role. When a module must scale on its own, a schema moves to its own database or cluster with pg_dump --schema or logical replication, and the cross-module joins become API calls. Example: orders and inventory in one database today; tomorrow inventory gets its own cluster and the join orders JOIN inventory turns into a service call.
Microservices
Each service owns one database (or at least one schema with one role) and nobody reads another's tables; process-per-connection makes the total connection budget a shared, finite resource across all services. Example flow for checkout:
time ->
1 orders-service BEGIN; INSERT orders; INSERT outbox(order_created); COMMIT (one local transaction)
2 relay reads outbox, publishes order.created to the broker
3 inventory-svc consumes, UPDATE stock ... WHERE stock >= n (its own cluster)
4 billing-svc consumes, INSERT ledger ... ON CONFLICT DO NOTHING (idempotent)Cross-service consistency uses outbox, sagas and idempotent consumers; here, per service, you tune pools, application_name per service and statement_timeout per role.
Distributed data (replicas, caches, sharded SQL, multi-region)
A cluster is the unit of replication and failover: streaming replicas copy the whole cluster, logical replication copies chosen tables (PG 19 can replicate sequences and enable logical replication without a restart). Replicas lag, so read-your-writes needs session pinning, synchronous_commit = remote_apply, or PG 19's WAIT. A cache (Redis) in front removes load but adds staleness. Sharding (Citus, application-level) multiplies the number of clusters, each with its own max_connections. See replication and failover, storage and data scaling and distributed SQL.
Scaling path
| Load | What changes | Chapter |
|---|---|---|
| 1x (hundreds of requests per second) | One primary, defaults, pg_stat_statements, backups with WAL archiving | Backup and PITR |
| 10x | PgBouncer, a read replica, indexes, tuned work_mem, autovacuum settings, connection budgets | Connection pooling, Indexing |
| 100x | Partitioning, caching tier, several replicas, per-service clusters, queues for async work | Partitioning and sharding |
| 1000x | Sharding or distributed SQL, multi-region, separate OLAP store | OLTP, OLAP and columnar |
Map of the chapters
This path has three groups after this page; every chapter below teaches one thing completely, and this page only gives the sentence.
| Chapter | In one sentence | Link |
|---|---|---|
| Database Internals | Pages, heap, tuples, TOAST and how an index points into the heap | /database/database-internals |
| ACID & Transactions | What atomicity, consistency, isolation and durability promise | /database/acid-transactions |
| Isolation Levels | Which anomalies each level forbids in each engine | /database/isolation-levels |
| MVCC, VACUUM & Bloat | Row versions, snapshots, dead tuples, autovacuum | /database/mvcc-vacuum |
| Locks & Concurrency | Row, table and advisory lock modes, pg_locks | /database/locks-concurrency |
| Deadlocks | Detection, deadlock_timeout, lock ordering | /database/deadlocks |
| Optimistic vs Pessimistic Locking | Version columns versus FOR UPDATE | /database/optimistic-pessimistic-locking |
| Indexing | B-tree, Hash, GIN, GiST, BRIN design | /database/indexing |
| B-Tree vs B+Tree | Fan-out, page splits, leaf links | /database/btree-bplustree |
| Storage Engines | B-tree versus LSM trees | /database/storage-engines |
| Query Planning | EXPLAIN, statistics, join algorithms | /database/query-planning |
| Bloom Filters & Probabilistic Structures | Bloom, HyperLogLog, Count-Min | /database/bloom-filters-probabilistic |
| Pagination | Offset versus keyset | /database/pagination |
| Cursors & Streaming | Server-side cursors, row streaming | /database/cursors-streaming |
| Billion-Row Tables | Operational playbook for huge tables | /database/billion-row-tables |
| Partitioning & Sharding in PostgreSQL | Declarative partitions, pruning, Citus | /database/partitioning-sharding-postgresql |
| Consistent Hashing | Ring, virtual nodes, rendezvous | /database/consistent-hashing |
| Storage & Data Scaling | The scale ladder | /database/storage-data-scaling |
| Distributed SQL, Consensus & 2PC | Raft, 2PC, global transactions | /database/distributed-sql-consensus |
| OLTP vs OLAP & Columnar | Row versus column storage for analytics | /database/oltp-olap-columnar |
| Replication, Read Replicas & Failover | Streaming and logical replication, lag, failover | /database/replication-failover |
| Durability, WAL & Crash Recovery | WAL, checkpoints, fsync, recovery | /database/durability-crash-recovery |
| Backup, PITR & Disaster Recovery | Base backups, WAL archive, restore tests | /database/backup-pitr-dr |
| Eventual Consistency in Databases | Consistency models and quorums | /database/eventual-consistency-databases |
| Database System Design | Requirements to worked sketches | /database/database-system-design |
| Schema Design | Normal forms, keys, data types | /database/schema-design |
| Zero-Downtime Schema Migrations | Safe DDL on live tables | /database/schema-migrations |
| Connection Pooling | PgBouncer, pool sizing | /database/connection-pooling |
| ORM Pitfalls | N+1, lazy loading, bulk operations | /database/orm-pitfalls |
| Multi-Tenancy | Schema, database, RLS strategies | /database/multi-tenancy |
| ID Generation | UUIDv7, ULID, Snowflake | /database/id-generation |
| Database Observability | pg_stat_*, wait events, alerts | /database/database-observability |
| Database Security | Roles, RLS, TLS, injection, audit | /database/database-security |
| Encryption | At rest, in transit, in use | /database/encryption-in-use |
| MySQL Storage Engines | InnoDB versus MyISAM | /database/mysql-storage-engines |
| SQLite | Embedded engine in depth | /database/sqlite |
| NoSQL Families | Data models and the map | /database/nosql-families |
| Redis | Data structures and patterns | /database/redis |
| MongoDB | Documents in depth | /database/mongodb |
| Wide-Column & Key-Value | Cassandra and DynamoDB model | /database/wide-column-key-value |
| Cassandra & ScyllaDB | CQL, compaction, repair | /database/cassandra-scylladb |
| Graph Databases | Property graphs and traversals | /database/graph-databases |
| Full-Text Search | PostgreSQL FTS versus Elasticsearch | /database/full-text-search |
| Vector Search | pgvector and ANN indexes | /database/vector-search |
| PostgreSQL Cheatsheet | Commands and settings at a glance | /cheatsheets/postgresql |
Lab: tour a fresh cluster
Start a throwaway server (any of PostgreSQL 17, 18 or 19 works; the official image tag is the major version):
docker run --rm -d --name pgtour -e POSTGRES_PASSWORD=secret -p 5432:5432 postgres:18
docker exec -it pgtour psql -U postgres1. See the processes and the hierarchy.
SELECT pid, backend_type FROM pg_stat_activity ORDER BY backend_type;
-- expect: client backend (you), checkpointer, background writer, walwriter,
-- autovacuum launcher, logical replication launcher (+ io worker on 18)
\l
\dn
\du
-- expect: databases postgres, template0, template1; schemas public (+ pg_catalog, information_schema hidden); role postgres2. Find your data directory and a table's file.
SHOW data_directory; -- /var/lib/postgresql/data
CREATE TABLE tour (id bigint PRIMARY KEY, note text);
INSERT INTO tour SELECT g, repeat('x', 100) FROM generate_series(1, 10000) g;
SELECT pg_relation_filepath('tour'); -- base/5/16388 (numbers differ)
SELECT oid, relname, relkind, relfilenode, reltuples FROM pg_class WHERE relname IN ('tour', 'tour_pkey');
TRUNCATE tour;
SELECT pg_relation_filepath('tour'); -- filenode changed, relname/oid same3. Memory and settings.
SELECT name, setting, unit, context FROM pg_settings WHERE name IN ('shared_buffers','work_mem','maintenance_work_mem','wal_buffers','effective_cache_size','huge_pages','max_connections');
-- expect: shared_buffers 16384 (8kB) = 128MB, work_mem 4096 kB, max_connections 100
ALTER SYSTEM SET shared_buffers = '256MB';
SELECT pg_reload_conf();
SELECT name, setting, pending_restart FROM pg_settings WHERE name = 'shared_buffers'; -- pending_restart = t4. Catalog queries and psql -E.
\d+ tour
-- restart psql with: psql -U postgres -E then \d tour and read the SQL it prints
SELECT a.attnum, a.attname, format_type(a.atttypid, a.atttypmod) FROM pg_attribute a WHERE a.attrelid = 'tour'::regclass AND a.attnum > 0 AND NOT a.attisdropped;
SELECT indexrelid::regclass, indisunique, indisprimary FROM pg_index WHERE indrelid = 'tour'::regclass;
SELECT proname, prosecdef FROM pg_proc p JOIN pg_namespace n ON n.oid = p.pronamespace WHERE nspname = 'pg_catalog' LIMIT 3;
SELECT table_name, column_name FROM information_schema.columns WHERE table_name = 'tour';5. \timing, \watch, \gexec.
\timing on
SELECT count(*) FROM tour;
SELECT count(*) FROM pg_stat_activity \watch 1
SELECT format('CREATE TABLE tour_%s (id int)', g) FROM generate_series(1,3) g \gexec
\dt6. Extensions and the protocol.
SELECT name FROM pg_available_extensions WHERE name IN ('pg_stat_statements','pgcrypto','pg_trgm');
CREATE EXTENSION pgcrypto;
\dx
SELECT $1::int + 1 \bind 41 \g -- extended protocol from psql: 42
PREPARE one (int) AS SELECT $1 * 2;
SELECT name, generic_plans, custom_plans FROM pg_prepared_statements;Clean up with docker stop pgtour.
Misconceptions
| Belief | Reality |
|---|---|
| A connection is a thread | A connection is a forked backend process with private memory |
More max_connections is free capacity | It sizes shared memory and invites contention; pool instead |
shared_buffers should be most of RAM | The OS cache also holds pages; start near 25% |
work_mem is per connection | Per sort or hash operation, times parallel workers and queries |
effective_cache_size allocates memory | It is only a planner estimate |
| The stats collector is a process | Removed in PostgreSQL 15; statistics live in shared memory |
information_schema is the native catalog | pg_catalog is native; the schema is the portable view |
| Schemas are like MySQL databases | In PostgreSQL schemas are inside one database; MySQL calls its databases schemas |
ALTER SYSTEM applies immediately | It writes postgresql.auto.conf; reload or restart per context |
trust in pg_hba.conf is only for tests | Every line is first-match; a stray trust opens the door |
CREATE EXTENSION installs software | Files must exist on the server first; some need shared_preload_libraries |
| Minor upgrades need dump/restore | Only majors do; minors swap binaries |
\d works in application code | Backslash commands are psql features only |
| Prepared statements are always faster | Poolers and generic plans can make them slower or break them |
Cheat sheet
| Topic | What to remember |
|---|---|
| Process model | postmaster forks one backend per connection; auxiliary: checkpointer, background writer, walwriter, autovacuum, archiver |
| Port and slots | 5432; max_connections 100, restart to change |
shared_buffers | Start near 25% of RAM; 128MB default; restart |
work_mem | 4MB per sort or hash node; use SET LOCAL for heavy queries |
maintenance_work_mem | 64MB default; raise for index builds |
wal_buffers | -1 = 1/32 of shared_buffers, 64kB to 16MB |
| Layout | base/<db oid>/<filenode>, pg_wal/, global/, pg_tblspc/; use pg_relation_filepath() |
| Hierarchy | Cluster > database > schema > object; roles are cluster-wide |
search_path | "$user", public; pin per role; qualify names in SECURITY DEFINER functions |
| Catalogs | pg_class (relkind), pg_attribute, pg_index, pg_namespace, pg_proc, pg_settings |
| Config | pg_settings.context: postmaster restart, sighup reload, user SET |
| Reload | SELECT pg_reload_conf(); or pg_ctl reload |
pg_hba.conf | First match wins; scram-sha-256; reload |
| psql | \d+, \x auto, \timing, \watch, \gexec, \conninfo, -E |
| Protocol | Simple = Query; extended = Parse/Bind/Execute; pgx default is extended with a statement cache |
| Versions | Yearly major, 5-year support; 19.0 released 2026-11-19; minors need no dump |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — Why does PostgreSQL need a pooler sooner than MySQL? Must-know
Answer
Answer: Every connection is an OS process with private memory and a start-up cost; max_connections sizes shared structures. A pooler multiplexes many clients over few backends.
2 — Name five processes you see in pg_stat_activity.backend_type on an idle server. Good to know
Answer
Answer: checkpointer, background writer, walwriter, autovacuum launcher, logical replication launcher (and client backend for you; on PG 18 also io worker).
3 — What replaced the statistics collector process, and from which version? Good to know
Answer
Answer: Cumulative statistics in shared memory, since PostgreSQL 15; there is no separate collector process.
4 — ALTER SYSTEM SET shared_buffers = '2GB' plus pg_reload_conf(): is it live? Important
Answer
Answer: No. shared_buffers has context postmaster; pending_restart is true until the server restarts.
5 — Where is the table orders stored on disk? Good to know
Answer
Answer: base/<database oid>/<relfilenode> (plus _fsm, _vm, 1 GB segments); SELECT pg_relation_filepath('orders') returns it; TRUNCATE changes the filenode.
6 — What does search_path default to and why does it matter for security? Important
Answer
Answer: "$user", public. Unqualified names resolve in order, so a writable schema earlier on the path can shadow objects; pin it per role and in SECURITY DEFINER functions.
7 — What is the difference between pg_catalog and information_schema? Important
Answer
Answer: pg_catalog is native, complete and fast; information_schema is the SQL-standard portable view layer with less detail and slower queries.
8 — Which setting is only a planner hint and allocates nothing? Good to know
Answer
Answer: effective_cache_size.
9 — How do simple and extended query protocol differ, and which does pgx use by default? Important
Answer
Answer: Simple sends one text Query with values inlined; extended splits into Parse, Bind, Execute with separate parameters and reusable statements. pgx defaults to extended with a per-connection prepared-statement cache.
10 — How long is a PostgreSQL major version supported, and is a minor upgrade a dump/restore? Must-know
Answer
Answer: Five years from first release; minor upgrades are only a binary swap and restart.
11 — Which \ command runs each result cell as SQL? Good to know
Answer
Answer: \gexec.
12 — Why is a stray trust line dangerous in pg_hba.conf? Must-know
Answer
Answer: Records are checked in order and the first match wins, so a broad trust line before stricter ones lets everyone matching it in without a password.
Glossary
| Term | Meaning |
|---|---|
| Cluster / instance | One postmaster with one PGDATA; contains all databases |
| Postmaster | First process; listens, authenticates, forks, restarts children |
| Backend | Per-connection server process |
| Auxiliary process | Long-lived helper: checkpointer, background writer, walwriter, autovacuum launcher, archiver |
| Checkpoint | Point at which all dirty pages are flushed and a recovery start is recorded |
| Background writer | Process that writes dirty buffers ahead of need |
| WAL (write-ahead log) | Sequential log of changes written before data pages |
| WAL buffers | Shared memory holding WAL not yet flushed |
| Shared buffers | PostgreSQL's page cache in shared memory |
work_mem | Memory limit per sort or hash operation before spilling |
maintenance_work_mem | Memory for VACUUM, index builds, foreign-key additions |
effective_cache_size | Planner's estimate of total cache available; allocates nothing |
| Huge pages | Large OS memory pages for the shared segment (huge_pages) |
PGDATA | The data directory |
| Filenode | Number naming a relation's file; pg_class.relfilenode |
| TOAST | Out-of-line storage for large column values |
| Tablespace | A directory where relation files can be stored |
| System catalog | Table describing the database's own objects (pg_class etc.) |
information_schema | SQL-standard portable catalog views |
| Schema | Namespace for objects inside a database |
| Role | User, group or both; cluster-wide |
search_path | Ordered schema list for resolving unqualified names |
| Extension | Packaged set of SQL objects installed with CREATE EXTENSION |
shared_preload_libraries | Libraries loaded at server start (restart needed) |
pg_hba.conf | Host-based authentication rules; first match wins |
pg_settings | View of all parameters with context and source |
pg_reload_conf() | Function that makes the server re-read config files |
| Simple query protocol | One Query message with SQL text |
| Extended query protocol | Parse, Bind, Execute; separate parameters, reusable statements |
| Prepared statement | Parsed (and possibly planned) statement reused across executions |
| SQLSTATE | Five-character error code (53300, 42P01, ...) |
| Major / minor version | Yearly feature release / bug-fix release (18.7) |
pg_upgrade | Tool for in-place major upgrades |
| psql meta-command | Backslash command interpreted by psql, not the server |
References
- PostgreSQL documentation, Architectural Fundamentals (saved:
arch.txt) - PostgreSQL documentation, Database File Layout (saved:
layout.txt), Tablespaces (tablespaces.txt) - PostgreSQL documentation, Resource Consumption (
resource.txt), WAL settings (runtimeshmem.txt), Connections and Authentication (conn.txt), Query Planning (query.txt), Kernel Resources, Linux Huge Pages (hugepages.txt) - PostgreSQL documentation, Setting Parameters (
configfile.txt), pg_hba.conf (hba.txt) - PostgreSQL documentation, Schemas (
schemas.txt), System Catalogs (catalogs.txt), CREATE EXTENSION (ext.txt), Glossary (glossary.txt), psql (psql.txt) - PostgreSQL documentation, Message Flow (
protoflow.txt), Cumulative Statistics System (pgstat.txt), A Brief History of PostgreSQL (history.txt) - PostgreSQL, Versioning Policy (
versioning.txt), About (about.txt) - Release notes: PostgreSQL 15, 17, 18, 19 (
release15.txt,release17.txt,release18.txt,release19.txt) - pgx on pkg.go.dev (
pkggodev.txt), jackc/pgx (pgx.txt) - Laravel 13 documentation, Database: Getting Started (
laravel.txt); connector source, PostgresConnector.php (laravel-pgconnector.php)