Skip to content

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 forGo to
Every process, every memory area, every directory in one tableEverything in one minute
Why one process per connection, and the restaurant analogyWhy it is built this way
Ingres, POSTGRES, Postgres95, PostgreSQLWhere it comes from
Postmaster, backends, background writer, checkpointer, WAL writer, autovacuum, archiverProcesses
shared_buffers, work_mem, maintenance_work_mem, wal_buffers, effective_cache_size, huge pagesMemory
PGDATA, base/, pg_wal/, pg_tblspc/, tablespaces, filenodesData directory
pg_class, pg_attribute, pg_index, pg_namespace, pg_proc, pg_stat_*, information_schemaSystem catalogs
Cluster, database, schema, role, search_pathHierarchy and naming
pg_stat_statements, pgcrypto, PostGIS, pgvector, TimescaleDB, CitusExtensions
\d, \x, \timing, \watch, \gexecpsql power use
postgresql.conf, ALTER SYSTEM, pg_hba.conf, reload versus restartConfiguration
Simple versus extended protocol, prepared statementsThe wire protocol
pgx, database/sql, Laravel pgsql optionsConnection anatomy: Go and Laravel
Major release cadence, 5-year support, PG 17, 18, 19 featuresVersions
PostgreSQL against MySQL, SQL Server, Oracle, SQLite, MongoDB, CockroachDB, RedisPositioning
Startup order, connection lifecycle, error codesMechanics
Too many connections, wrong schema, setting not appliedSolving the classic problems
Which tool for which situationChoosing
Monolith to distributed dataIn architecture
Every other chapter of the pathMap of the chapters
Hands-on tour of a fresh clusterLab
Wrong beliefs, cheat sheet, self-check, glossaryMisconceptions, 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)JobIf it stops
postmasterFirst process; listens on port 5432, authenticates by pg_hba.conf, forks children, restarts after a crashNothing works; clients get connection refused
client backendOne per connection; parses, plans and executes your SQLOnly that session ends
checkpointerWrites all dirty pages at a checkpoint, advances the recovery start pointCrash recovery gets longer, pg_wal grows
background writerTrickles dirty buffers to disk so backends rarely writeBackends write more themselves; latency spikes
walwriterFlushes wal_buffers to pg_wal between commitsCommits flush WAL themselves; slower
autovacuum launcher / workerStarts workers that VACUUM and ANALYZE tablesBloat, stale statistics, wraparound risk
archiverCopies finished WAL segments (archive_command, archive_library)Archive falls behind, pg_wal fills
logical replication launcher / workerStarts apply workers for subscriptionsLogical subscribers stop applying
walsender / walreceiverStreams WAL to a standby / receives itReplica lag grows
startupReplays WAL during crash or archive recovery, and on standbysServer cannot finish starting
io worker (PG 18)Executes asynchronous reads when io_method = workerFalls back; reads stall
parallel workerHelps one query scan or join in parallelQuery runs serially

The memory areas. Unpacked in Memory.

AreaSettingDefaultChange needs
Shared page cacheshared_buffers128MBrestart (postmaster)
Per sort or hash operationwork_mem4MBper session SET
Hash tables multiplierhash_mem_multiplier2.0per session SET
VACUUM, CREATE INDEX, ADD FOREIGN KEYmaintenance_work_mem64MBper session SET
WAL not yet on diskwal_buffers-1 (1/32 of shared_buffers, 64kB to one WAL segment)restart
Temporary tablestemp_buffers8MBbefore first temp-table use in a session
Planner hint onlyeffective_cache_size4GBper session SET; allocates nothing
Huge pages for the shared segmenthuge_pagestryrestart
Connection slotsmax_connections100restart

The hierarchy and the catalogs. Unpacked in Hierarchy and Catalogs.

LevelWhat it isHow to list itCatalog
Cluster (instance)One postmaster, one PGDATA, one portSHOW data_directoryfiles under global/
RoleUser or group, shared by the cluster\dupg_authid, view pg_roles
DatabaseIsolated catalogs and files; a connection binds to one\lpg_database
SchemaNamespace inside a database\dnpg_namespace
Table, index, sequence, viewRelations\d, \dt, \dipg_class (relkind)
ColumnAttribute of a relation\d tablepg_attribute
Function, procedureRoutines\dfpg_proc
TypeBase, composite, enum, domain\dTpg_type
ExtensionPackaged set of objects\dxpg_extension
TablespaceDirectory for relation files\dbpg_tablespace

The three things to remember.

SituationDo this
Connection count grows with services and replicasBudget 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 memoryCheaper per connection, more connections feasible
Shared state must live in an explicit shared memory segmentShared state is just process memory
Pooling (PgBouncer) is close to mandatory above a few hundred clientsBuilt-in thread pools exist (MySQL Enterprise/Percona, SQL Server schedulers)
Each backend has its own catalog and plan cachesCaches 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 ​

  1. “A database connection is cheap.” In PostgreSQL it is an operating-system process with private memory, and max_connections sizes shared memory at start. Thousands of idle connections are a cost, not a convenience.
  2. “shared_buffers should 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”.
  3. “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.

EraNameWhat changed
1986 to 1994POSTGRES (Berkeley)Extensible types, rules system, multiple storage managers; query language PostQUEL
1994 to 1996Postgres95SQL replaced PostQUEL; code in ANSI C, about 25% smaller; libpq keeps the old name's echo
1996PostgreSQL 6.0New name; version numbers resume the Berkeley sequence
Since PostgreSQL 10Two-part version numbersMajor version is the first number (10, 11, ... 19); minor releases are 18.7
YearlyA major releaseDump/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 it

Real 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).

AspectPostgreSQLMySQL (InnoDB)SQL ServerOracle
Unit of a sessionOS 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 costHigh (fork, private caches)MediumLow to mediumHigh (dedicated), lower (shared server)
Built-in poolingNone (use PgBouncer, pgcat, Odyssey, RDS Proxy)Thread pool in Enterprise and PerconaSchedulers; client-side poolsShared server, DRCP
Default port5432330614331521
Slot limitmax_connections (100)max_connections (151)Configured maximum user connectionsprocesses / sessions

Fix / how to use it:

sql
-- 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.

go
// 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
<?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 ​

Clientspsqlapp (pgx, PDO)PgBouncerreplica (walreceiver)TCP 5432 / unix socketpostmasterlistens, authenticates (pg_hba.conf),forks, restarts childrenbackend (conn 1)one OS process per sessionbackend (conn 2)parse, plan, executebackend (conn N)max_connections caps Nauxiliary and background processescheckpointerflushes dirty pages, CHECKPOINTbackground writertrickles dirty buffers outWAL writerflushes wal_buffers to pg_walautovacuum launcherstarts autovacuum workersarchiverarchive_command / archive_librarylogical replication launcherapply workers (subscriptions)walsender / walreceiverstreaming replicationio workers (PG 18)io_method = worker+ parallel workers, WAL summarizer (PG 17), startup (recovery)shared memory (allocated at start; attached by every process)shared_buffers | wal_buffers | lock tables | proc array | cumulative statistics (PG 15+)stats collector process was removed in PG 15PGDATA on disk: base/ | global/ | pg_wal/ | pg_tblspc/ | postgresql.conf | pg_hba.conf

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.

ProcessJob (docs wording where quoted)Key settingsLook at
checkpointer“is responsible for executing checkpoints”checkpoint_timeout (5min), max_wal_size, checkpoint_completion_targetpg_stat_checkpointer (PG 17), older pg_stat_bgwriter
background writer“writes dirty data pages from shared memory to the file system” gentlybgwriter_delay, bgwriter_lru_maxpagespg_stat_bgwriter
walwriter“writes WAL records from shared memory to WAL files”wal_writer_delay, wal_writer_flush_afterpg_stat_wal
autovacuum launchercoordinates the workers that VACUUM and ANALYZEautovacuum, autovacuum_max_workers, autovacuum_naptimepg_stat_user_tables, pg_stat_progress_vacuum
archivercopies completed WAL segmentsarchive_mode, archive_command, archive_librarypg_stat_archiver
logical replication launcherstarts apply workers for subscriptionsmax_logical_replication_workerspg_stat_subscription
walsender / walreceiverstreaming replicationmax_wal_senders, primary_conninfopg_stat_replication, pg_stat_wal_receiver
startupWAL replay during recoveryrecovery_target_*, hot_standbypg_stat_recovery_prefetch
WAL summarizer (PG 17)records changed blocks for incremental backupsummarize_walpg_available_wal_summaries()
io worker (PG 18)asynchronous I/Oio_method, io_workerspg_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 WAL

Real 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:

sql
-- 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
// 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")
php
// Laravel: DB::select('select relname, n_dead_tup from pg_stat_user_tables order by 2 desc limit 10');

Memory areas Must-know ​

Shared memory (one segment, sized at server start)shared_buffers8 kB page cache; ~25% of RAM start; restartwal_buffersdefault -1 = 1/32 ofshared_buffers (cap 16 MB)lock tables, proc arraysized by max_connections,max_locks_per_transactioncumulative statistics, SLRUpg_stat_* counters (PG 15+),commit log, subtrans, multixactPrivate memory (per backend)work_mem (4 MB default)per sort / hash node, times hash_mem_multipliermaintenance_work_mem (64 MB)VACUUM, CREATE INDEX, ALTER TABLE ADD FKtemp_buffers (8 MB), cachestemp tables, relcache, catcache, plan cacheOperating system page cache (kernel)second cache for the same pages; effective_cache_size is the planner's guess of shared_buffers + this; allocates nothingDisk (PGDATA, pg_wal)read() / write() through the kernel; fsync at checkpoint and at commit (WAL); huge_pages applies to the shared segment

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:

AreaScopeSetting and defaultNotes
Shared bufferssharedshared_buffers, 128MBPostgreSQL'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 bufferssharedwal_buffers, -1Auto size 1/32 of shared_buffers, at least 64kB, at most one WAL segment (16MB); flushed at every commit
Lock tables, proc arraysharedsized by max_connections, max_locks_per_transactionFixed at start
Cumulative statistics, SLRU cachessharedtrack_counts, commit_timestamp_buffers, ...pg_stat_* counters live here since PG 15
Sort and hash memoryper operationwork_mem 4MB, hash_mem_multiplier 2.0Spills to temp files in base/pgsql_tmp when exceeded
Maintenance memoryper operationmaintenance_work_mem 64MB, autovacuum_work_mem -1VACUUM, CREATE INDEX, ALTER TABLE ADD FOREIGN KEY; autovacuum may use workers times this value
Temp table buffersper sessiontemp_buffers 8MBOnly for temporary tables
Planner assumptionnoneeffective_cache_size 4GBAllocates nothing; tells the planner how much cache a query may count on
Huge pagesOShuge_pages = try, huge_page_sizeApplies only to the main shared segment; see shared_memory_size_in_huge_pages
Plan, catalog, relation cachesper backendplan_cache_mode, none for the restRebuilt 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 column

Real 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.

ProductPage cachePer-query memoryNote
PostgreSQLshared_buffers plus OS cachework_mem per operationDouble caching; effective_cache_size is a hint
MySQL InnoDBinnodb_buffer_pool_size (often 50 to 75% of RAM; bypasses the OS cache with O_DIRECT)sort_buffer_size, join_buffer_size per sessionOpposite sizing philosophy
SQL ServerBuffer pool (max server memory)Memory grants per queryGrants queue (RESOURCE_SEMAPHORE waits)
OracleSGA buffer cachePGA (pga_aggregate_target)Automatic memory management available
SQLiteOS cache plus cache_sizePer connectionEmbedded; see SQLite

Fix / how to use it:

sql
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.

go
// 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.

php
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 PGDATAMeaning
PG_VERSIONMajor 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.confConfiguration (often moved to /etc/postgresql by distributions)
postmaster.pid, postmaster.optsLock 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).

ProductStorage unitFiles
PostgreSQLCluster of databases, heap files per relationbase/<db>/<filenode>
MySQL InnoDBTablespaces (file-per-table: .ibd), system tablespace, redo and undo logsdatadir/<schema>/<table>.ibd
SQL ServerDatabase = .mdf/.ndf data files plus .ldf logfilegroups
OracleTablespaces made of datafiles, redo logs, control filesASM or file system
SQLiteOne file (plus -wal, -shm)See SQLite

Fix / how to use it:

sql
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
// Go: pg_total_relation_size (table + indexes + TOAST) as in the catalog snippet.
go
// 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)
	}
}
php
// 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
<?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 ​

Cluster = one postmaster + one PGDATA (port 5432)Shared by all databasesroles: pg_authid / pg_rolesmemberships: pg_auth_membersdatabases: pg_databasetablespaces: pg_tablespacesettings: pg_db_role_setting(stored under global/)Roles and accessGRANT ... TO rolepg_hba.conf decides who mayconnect to which databaseDatabase (one connection = one database)per-database catalogspg_namespace (schemas)pg_class (relations, relkind)pg_attribute (columns)pg_index, pg_constraintpg_proc, pg_type, pg_extensioncopied from template1 at CREATE DATABASEviews over the catalogsinformation_schema (SQL standard)pg_tables, pg_indexes, pg_viewspg_stat_activity, pg_stat_user_tablespg_stat_statements (extension)pg_settings, pg_locksread-only, built from catalogs and shared memorySchemas inside the database: public, app, billing, pg_catalog, information_schema, pg_toastsearch_path = "$user", public (pg_catalog is searched first implicitly)schema.table | schema.index | schema.sequence | schema.view | schema.function | schema.typeeach table = relfilenode file(s) in base/<database oid>/ (1 GB segments, _fsm, _vm, TOAST)Qualify names (app.orders) or set search_path; never rely on public in shared databasesobjects live in exactly one schema; schemas are namespaces, not security boundaries by themselves

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:

CatalogOne row perKey columnsTypical use
pg_classtable, index, sequence, view, materialized view, composite type, foreign table, partitioned table or indexoid, relname, relnamespace, relkind (r, i, S, v, m, c, t, f, p, I), relfilenode, reltuples, relpages, relpersistence, relispartitionFind any relation and its file
pg_attributecolumn of any relationattrelid, attname, atttypid, attnum, attnotnull, attisdroppedColumn lists; dropped columns stay as ghosts
pg_indexindexindexrelid, indrelid, indisunique, indisprimary, indisvalid, indkeyFind unused or invalid indexes
pg_constraintconstraintcontype (p, u, f, c, x), conrelid, confrelidForeign key graph
pg_namespaceschemanspname, nspownerList schemas
pg_procfunction, procedure, aggregateproname, prosrc, prosecdef, provolatileFind a function, SECURITY DEFINER audit
pg_typedata typetypname, typtype, typelemEnums, domains, composite types
pg_roles (view of pg_authid)rolerolname, rolsuper, rolcanlogin, rolconnlimitWho exists; pg_authid holds password hashes and needs superuser
pg_databasedatabasedatname, datistemplate, datallowconn, dattablespaceShared by the cluster
pg_extensioninstalled extensionextname, extversion\dx
pg_settings (view)settingname, setting, context, source, pending_restart, boot_valWhere a setting comes from
pg_locks, pg_stat_activitylock, sessionsee locks, observabilityLive 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 see

Real 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.

Questioninformation_schemapg_catalog
Portable to MySQL, SQL ServerYes (standard views)No
Shows indexes, partitions, extensions, relkindNo or partialYes
Speed on large schemasSlower (joins many views, permission filters)Faster
VisibilityOnly objects you own or may useEverything readable (privileges still apply)

Fix / how to use it:

sql
-- 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 table

Real 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”).

ConceptPostgreSQLMySQLSQL ServerOracle
“Database”Isolated catalogs; one per connectionSynonym of schemaDatabase (own files, log)Instance or pluggable database (CDB/PDB)
“Schema”Namespace inside a databaseSame as databaseNamespace inside a database (dbo)A user's objects (schema = user)
Cross-database queryNo (use postgres_fdw, dblink)Yes (db.table)Yes (db.schema.table)Database links
UsersRoles, cluster-wideuser@host, globalLogins plus database usersUsers, per database
Name resolutionsearch_pathCurrent databaseDefault schema of the userCurrent schema

Fix / how to use it:

sql
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.

ExtensionWhat it addsNeeds shared_preload_librariesNotes
pg_stat_statementsPer-normalised-query timing, calls, rows, buffersYesThe first thing to install; see observability
pgcryptoHashing (digest()), password hashing (crypt()), PGP and symmetric encryption functionsNoSee encryption in use
postgisGeometry and geography types, spatial indexes (GiST, SP-GiST)NoDe facto standard for GIS
pgvector (CREATE EXTENSION vector)vector type, HNSW and IVFFlat indexesNoSee vector search
timescaledbHypertables, compression, continuous aggregates for time seriesYesSeparate licence terms apply to some features
citusDistributed tables across worker nodesYes (must be first)See partitioning and sharding
pg_trgm, btree_gin, btree_gistTrigram search, extra operator classesNoSee full-text search
postgres_fdw, dblinkQuery other PostgreSQL databasesNoCross-database access
pg_partman, pg_cronPartition automation, in-database schedulerpg_cron: YesCommon managed-cloud extras
pgauditSession and object audit logsYesSee database security
pg_plan_advice (PG 19)Control planner decisions (with pg_stash_advice)Check the docsNew 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:

sql
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:

CommandDoesExample
\? / \hHelp for backslash commands / SQL syntax\h CREATE INDEX
\lList databases
\c dbnameConnect to another database\c appdb app
\conninfoShow current connection
\dn, \dt, \di, \dv, \ds, \dx, \du, \db, \df, \dTList schemas, tables, indexes, views, sequences, extensions, roles, tablespaces, functions, types\dt app.*
\d name, \d+ nameDescribe a relation (columns, indexes, constraints, triggers), + adds size and storage\d+ orders
\dconfigShow configuration parameters (PG 16)\dconfig *mem*
\x, \x autoExpanded (vertical) output\x auto
\timingPrint the time each statement took
\watch [interval]Re-run the last query every N seconds (default 2)\watch 5
\gexecExecute each cell of the result as SQLgenerate and run DDL
\gsetStore a result row in psql variables\gset ver_
\g file, \o fileSend results to a file or pipe
\copyClient-side COPY using the local file system\copy t FROM 'x.csv' CSV HEADER
\e, \ef, \sf, \svEdit the buffer, edit a function, show function / view source\sf my_func
\i file, \ir fileRun a script (relative to current script)
\set, \unset, \psetVariables and output format\pset null '(null)'
\errverboseShow the last error with all fields (SQLSTATE, hint, position)
\bind, \parse, \close_preparedRun a statement through the extended protocol with parametersSELECT $1 \bind 42 \g
\crosstabviewPivot a result
\qQuit
 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 2

Real 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:

sql
\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' \gexec

Go 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)WhereApplies to
Built-in defaultboot_val in pg_settingsall
postgresql.conf and include filesPGDATA or /etc/postgresql/<ver>/maincluster
postgresql.auto.confwritten by ALTER SYSTEMcluster
Command linepostgres -c name=value, pg_ctl -ocluster
ALTER DATABASE ... SETcatalog pg_db_role_settingnew sessions in that database
ALTER ROLE ... SET (optionally IN DATABASE)catalog pg_db_role_settingnew sessions of that role
Connection optionsoptions=-c work_mem=64MB, Laravel server_optionsone connection
SET, SET LOCAL, set_config()session or transactionuntil reset
pg_settings.contextMeaningExamples
internalCompile-time, read-onlyblock_size, server_version_num
postmasterRestart requiredshared_buffers, max_connections, wal_level, huge_pages, shared_preload_libraries
sighupReload is enoughlog_min_duration_statement, checkpoint_timeout, autovacuum_naptime
superuser-backend, backendFixed at connection startlog_connections, ignore_system_indexes
superuserSET by superusers or granted SET privilegesession_replication_role
userAny session may SETwork_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;                             -- 4GB

Real 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).

ProductConfig fileLive change
PostgreSQLpostgresql.conf, pg_hba.confSET, ALTER SYSTEM + reload
MySQLmy.cnfSET GLOBAL, SET PERSIST
SQL Serversp_configure, startup flagsRECONFIGURE
OraclespfileALTER SYSTEM SET ... SCOPE=BOTH
Redisredis.confCONFIG SET, CONFIG REWRITE

Fix / how to use it:

sql
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 ​

Simple query protocolExtended query protocolclientbackendclientbackendQuery("SELECT ... 42")RowDescriptionDataRow x NCommandComplete, ReadyForQuerySQL text with values inlinedtext format results onlyseveral statements allowed(one implicit transaction)psql, simple_query_mode, PgBouncer-safeParse(name, SQL, param types)Bind(portal, params, formats)Describe(statement or portal)Execute(portal, max_rows)SyncParseComplete, BindCompleteRowDescription, DataRow x NCommandCompleteReadyForQuerynext call: Bind + Execute only (reuse the plan)parameters travel apart from SQL: no injection, binary formats

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.”

MessageDirectionPurpose
StartupMessage, SSLRequest, GSSENCRequestclientOpen a session (protocol 3.0; 3.2 since PG 18)
AuthenticationOk, AuthenticationSASLserverAuth outcome (SCRAM-SHA-256 uses SASL)
ParameterStatus, BackendKeyData, ReadyForQueryserverSettings the client must know; cancel key; idle/in-transaction/failed status
QueryclientSimple protocol: SQL text, may hold several statements
Parse, Bind, Describe, Execute, Sync, CloseclientExtended protocol steps
RowDescription, DataRow, CommandComplete, ErrorResponseserverResults and errors (SQLSTATE)
CopyInResponse, CopyDatabothCOPY sub-protocol
NotificationResponseserverLISTEN/NOTIFY
CancelRequestclient (new connection)Cancel a running query
TerminateclientClose 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).

LayerSettingEffect
pgxQueryExecModeCacheStatement (default)Extended protocol with a per-connection prepared-statement cache
pgxQueryExecModeCacheDescribeCache descriptions only
pgxQueryExecModeDescribeExecDescribe each time, unnamed statement; two round trips
pgxQueryExecModeExecExtended protocol, one round trip, no named statements (pooler-friendly)
pgxQueryExecModeSimpleProtocolSimple protocol; client-side interpolation; multiple statements
Go database/sql + pgx stdlibDSN default_query_exec_mode=execSame choice through the DSN
PHP PDO pgsqlPDO::ATTR_EMULATE_PREPARES (Laravel uses the default, off)Server-side prepares; true interpolates client-side
libpqPQexecParams, pipeline mode (PG 14)Extended protocol, batching round trips
psql\bindRun one statement with extended protocol

Fix / how to use it:

sql
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:

go
// 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).”

MajorFirst releaseFinal release (EOL)Current minor (page read 2026-11-25)
192026-11-192031-11-1919.0
182025-09-252030-11-1418.7
172024-09-262029-11-0817.12
162023-09-142028-11-0916.16
152022-10-132027-11-1115.20
142021-09-302026-11-1214.25, no longer supported

Headline features from the release notes (only what the notes list):

VersionHeadline features (from the release notes)
PostgreSQL 17New 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 18Asynchronous 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 19REPACK 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 major

Real 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.

ProductCadenceSupport
PostgreSQLYearly major, minor at least quarterly5 years per major
MySQLLTS and innovation releases (8.4 LTS, 9.x)Oracle's schedule
SQL ServerRoughly every 2 to 3 yearsMainstream plus extended (10 years total)
OracleYearly innovation, long-term releases (19c, 23ai)Premier plus extended support

Fix / how to use it:

sql
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 ​

DimensionPostgreSQLMySQL (InnoDB)SQL ServerOracleSQLiteMongoDBCockroachDBRedis
ModelObject-relationalRelationalRelationalRelational / multi-modelEmbedded relationalDocumentDistributed SQL (PostgreSQL wire)Key-value / structures
LicencePostgreSQL licence (permissive)GPL + commercialCommercialCommercialPublic domainSSPLBSL / commercialChanged across versions; check the current terms
Process modelProcess per connectionThread per connectionSQLOS schedulersDedicated or shared serverIn-process libraryThreadsGo processes per nodeSingle-threaded command execution
Default isolationRead CommittedRepeatable ReadRead Committed (locking)Read CommittedSerializable (one writer)Snapshot inside a transactionSerializableAtomic commands
MVCCHeap row versions, VACUUMUndo logs, purgeRow versioning in tempdb (optional)Undo segmentsWAL snapshotsWiredTiger MVCCMVCC on KV (Pebble)Not applicable
ExtensibilityTypes, operators, index AMs, extensions, PL languagesPlugins, storage enginesCLR, extended procsPL/SQL, cartridgesLoadable extensionsAggregation stagesLimitedModules
ReplicationPhysical streaming, logicalBinlog, Group ReplicationAlways On, log shippingData Guard, GoldenGateLitestream (external)Replica setsRaft rangesReplication, Cluster
Strongest atCorrectness, SQL breadth, extensions, JSONBSimple OLTP web apps, replication ecosystemMicrosoft stack, toolingEnterprise, RAC, partitioningEmbedded, local, edgeFlexible documentsMulti-region SQLCaching, queues

Chapters: MySQL storage engines, SQLite, MongoDB, Redis, NoSQL families, distributed SQL and consensus.

When PostgreSQL is the right defaultWhen something else wins
Transactional core with constraints, joins, JSONB side data, full-text and vectors in the same storeSingle-file app or test database: SQLite
Strong SQL, window functions, CTEs, MERGE, partitioning, row level securitySimple 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-inLatency-critical cache or counters: Redis
Reporting and OLTP mixed at moderate scaleWide-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 backend

Connection 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 ​

SQLSTATENameMessage (typical)Meaning and fix
53300too_many_connectionsFATAL: sorry, too many clients alreadySlots exhausted; pool, raise max_connections, add PgBouncer
53300too_many_connectionsremaining connection slots are reserved for roles with the SUPERUSER attributeOnly reserved slots left
28P01invalid_passwordpassword authentication failed for user "app"Wrong password or hash type
28000invalid_authorization_specificationno pg_hba.conf entry for host "10.0.0.5", user "app", database "appdb", no encryptionAdd or fix the hba line, reload
3D000invalid_catalog_namedatabase "x" does not existWrong database (not wrong schema)
3F000invalid_schema_nameschema "app" does not existMissing schema or typo in search_path
42P01undefined_tablerelation "orders" does not existWrong search_path, not created, or case-folded quoted name
42704undefined_objecttype "vector" does not existExtension not installed in this database
42501insufficient_privilegepermission denied for table ordersMissing GRANT; also thrown by CREATE EXTENSION for non-trusted
57P01admin_shutdownterminating connection due to administrator commandpg_terminate_backend or server stop; reconnect
57P03cannot_connect_nowthe database system is starting upRecovery in progress; retry with backoff
55P02cant_change_runtime_paramparameter "shared_buffers" cannot be changed without restarting the serverNeeds restart
25P03idle_in_transaction_session_timeoutterminating connection due to idle-in-transaction timeoutFix the leak in the client
57014query_canceledcanceling statement due to statement timeoutExpected with statement_timeout; retry carefully

Solving the classic problems ​

ProblemCauseSolutionCost or limit
too many clients alreadyPools times replicas exceed max_connectionsPgBouncer in transaction mode, smaller app pools, budget per serviceSession features (advisory locks, SET) need session pooling
relation does not existWrong search_path or databaseQualify names, set search_path per role, check current_database()Pooled connections may reset settings (use ALTER ROLE ... SET)
Setting "did not apply"postmaster contextALTER SYSTEM then restart, check pending_restartRestart means downtime or failover
Queries slow after a restartCold shared_buffers and OS cachepg_prewarm, warm traffic; pg_prewarm.autoprewarmTakes minutes at scale
Disk full in pg_walStuck replication slot or failed archive_commandFix archiving, drop or advance the slot, set max_slot_wal_keep_sizeDropping a slot breaks its consumer
Idle sessions pile upClient never closesidle_session_timeout, idle_in_transaction_session_timeoutClients must reconnect cleanly
Cannot connect remotelylisten_addresses = 'localhost', firewall, hbaSet listen_addresses, add hostssl ... scram-sha-256 line, reloadRestart for listen_addresses
Which database is biggestUnknownpg_database_size, pg_total_relation_sizeSizes include bloat
sql
-- 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.

go
// 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 ​

ErrorMeaningRetry?How
57P03 starting upServer in recoveryYesExponential backoff with jitter, cap at seconds to minutes
53300 too many clientsPool exhaustionYes, with limitsBackoff; fix the pool, do not hammer
57P01 admin shutdownFailover or restartYes (new connection, idempotent work only)Reconnect; pgx pool health checks discard the dead connection
08006 connection failureNetwork dropYes if the transaction can be replayedNever retry a commit whose outcome is unknown without idempotency
40001, 40P01Serialization failure, deadlockYes, whole transactionSee isolation levels, deadlocks
28P01, 28000Auth failureNoFix credentials or hba
42P01, 3F000Wrong schema or objectNoFix configuration

Connection anatomy: Go and Laravel ​

PieceGo (pgx, database/sql)Laravel (pgsql driver)
Drivergithub.com/jackc/pgx/v5; stdlib adapter registers "pgx" for database/sqlpdo_pgsql extension via PDO
Poolpgxpool (MaxConns, MinConns, MaxConnLifetime, MaxConnIdleTime, HealthCheckPeriod) or db.SetMaxOpenConns, SetMaxIdleConns, SetConnMaxLifetimeNone built in: one PDO per worker process (FPM, Octane worker, queue worker)
DSN / URLpostgres://user:pass@host:5432/db?sslmode=verify-full&application_name=xDB_URL or host, port, database, username, password keys
Session settingsUnknown DSN parameters become runtime parameters (search_path, statement_timeout)search_path, timezone, synchronous_commit, isolation_level, server_options
TLSsslmode: disable, allow, prefer, require, verify-ca, verify-full; sslrootcertsslmode, sslcert, sslkey, sslrootcert copied into the DSN
Keep-alivekeepalives via libpq-style parameters, pgx ConnConfig dialerkeepalives, keepalives_idle, keepalives_interval, keepalives_count
Prepared statementsExtended protocol, cache per connection (QueryExecModeCacheStatement)PDO server-side prepares by default
Read/write splitManual (two pools)read and write host arrays, sticky
Application nameapplication_name=application_name key
Env defaultsPGHOST, 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
<?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
<?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 ​

SituationRecommendationExtra techniqueReason
New transactional service, unsure of the databasePostgreSQLStart with one cluster, one database, schemas per moduleBroadest feature set, one fewer system
Hundreds of app replicasPostgreSQL + PgBouncer (transaction mode)Per-service pool budgetProcess per connection
Multi-tenant SaaS, few tenantsSchema per tenant or tenant_id + RLSALTER ROLE ... SET search_pathSee multi-tenancy
Needs full-text, geo, vectorsExtensions inside PostgreSQL firstpg_trgm, PostGIS, pgvectorFewer moving parts
Mixed OLTP and heavy reportingRead replica for reportsstatement_timeout, separate role and work_memKeep primary latency stable
Settings per workloadRole-level ALTER ROLE ... SETwork_mem, statement_timeout per roleSafe, no restart
Upgradespg_upgrade --link or logical replicationRead release notes for each major in betweenAvoid long downtime
Embedded or edgeSQLiteLitestreamNot 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 ​

LoadWhat changesChapter
1x (hundreds of requests per second)One primary, defaults, pg_stat_statements, backups with WAL archivingBackup and PITR
10xPgBouncer, a read replica, indexes, tuned work_mem, autovacuum settings, connection budgetsConnection pooling, Indexing
100xPartitioning, caching tier, several replicas, per-service clusters, queues for async workPartitioning and sharding
1000xSharding or distributed SQL, multi-region, separate OLAP storeOLTP, 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.

ChapterIn one sentenceLink
Database InternalsPages, heap, tuples, TOAST and how an index points into the heap/database/database-internals
ACID & TransactionsWhat atomicity, consistency, isolation and durability promise/database/acid-transactions
Isolation LevelsWhich anomalies each level forbids in each engine/database/isolation-levels
MVCC, VACUUM & BloatRow versions, snapshots, dead tuples, autovacuum/database/mvcc-vacuum
Locks & ConcurrencyRow, table and advisory lock modes, pg_locks/database/locks-concurrency
DeadlocksDetection, deadlock_timeout, lock ordering/database/deadlocks
Optimistic vs Pessimistic LockingVersion columns versus FOR UPDATE/database/optimistic-pessimistic-locking
IndexingB-tree, Hash, GIN, GiST, BRIN design/database/indexing
B-Tree vs B+TreeFan-out, page splits, leaf links/database/btree-bplustree
Storage EnginesB-tree versus LSM trees/database/storage-engines
Query PlanningEXPLAIN, statistics, join algorithms/database/query-planning
Bloom Filters & Probabilistic StructuresBloom, HyperLogLog, Count-Min/database/bloom-filters-probabilistic
PaginationOffset versus keyset/database/pagination
Cursors & StreamingServer-side cursors, row streaming/database/cursors-streaming
Billion-Row TablesOperational playbook for huge tables/database/billion-row-tables
Partitioning & Sharding in PostgreSQLDeclarative partitions, pruning, Citus/database/partitioning-sharding-postgresql
Consistent HashingRing, virtual nodes, rendezvous/database/consistent-hashing
Storage & Data ScalingThe scale ladder/database/storage-data-scaling
Distributed SQL, Consensus & 2PCRaft, 2PC, global transactions/database/distributed-sql-consensus
OLTP vs OLAP & ColumnarRow versus column storage for analytics/database/oltp-olap-columnar
Replication, Read Replicas & FailoverStreaming and logical replication, lag, failover/database/replication-failover
Durability, WAL & Crash RecoveryWAL, checkpoints, fsync, recovery/database/durability-crash-recovery
Backup, PITR & Disaster RecoveryBase backups, WAL archive, restore tests/database/backup-pitr-dr
Eventual Consistency in DatabasesConsistency models and quorums/database/eventual-consistency-databases
Database System DesignRequirements to worked sketches/database/database-system-design
Schema DesignNormal forms, keys, data types/database/schema-design
Zero-Downtime Schema MigrationsSafe DDL on live tables/database/schema-migrations
Connection PoolingPgBouncer, pool sizing/database/connection-pooling
ORM PitfallsN+1, lazy loading, bulk operations/database/orm-pitfalls
Multi-TenancySchema, database, RLS strategies/database/multi-tenancy
ID GenerationUUIDv7, ULID, Snowflake/database/id-generation
Database Observabilitypg_stat_*, wait events, alerts/database/database-observability
Database SecurityRoles, RLS, TLS, injection, audit/database/database-security
EncryptionAt rest, in transit, in use/database/encryption-in-use
MySQL Storage EnginesInnoDB versus MyISAM/database/mysql-storage-engines
SQLiteEmbedded engine in depth/database/sqlite
NoSQL FamiliesData models and the map/database/nosql-families
RedisData structures and patterns/database/redis
MongoDBDocuments in depth/database/mongodb
Wide-Column & Key-ValueCassandra and DynamoDB model/database/wide-column-key-value
Cassandra & ScyllaDBCQL, compaction, repair/database/cassandra-scylladb
Graph DatabasesProperty graphs and traversals/database/graph-databases
Full-Text SearchPostgreSQL FTS versus Elasticsearch/database/full-text-search
Vector Searchpgvector and ANN indexes/database/vector-search
PostgreSQL CheatsheetCommands 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):

bash
docker run --rm -d --name pgtour -e POSTGRES_PASSWORD=secret -p 5432:5432 postgres:18
docker exec -it pgtour psql -U postgres

1. See the processes and the hierarchy.

sql
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 postgres

2. Find your data directory and a table's file.

sql
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 same

3. Memory and settings.

sql
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 = t

4. Catalog queries and psql -E.

sql
\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.

sql
\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
\dt

6. Extensions and the protocol.

sql
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 ​

BeliefReality
A connection is a threadA connection is a forked backend process with private memory
More max_connections is free capacityIt sizes shared memory and invites contention; pool instead
shared_buffers should be most of RAMThe OS cache also holds pages; start near 25%
work_mem is per connectionPer sort or hash operation, times parallel workers and queries
effective_cache_size allocates memoryIt is only a planner estimate
The stats collector is a processRemoved in PostgreSQL 15; statistics live in shared memory
information_schema is the native catalogpg_catalog is native; the schema is the portable view
Schemas are like MySQL databasesIn PostgreSQL schemas are inside one database; MySQL calls its databases schemas
ALTER SYSTEM applies immediatelyIt writes postgresql.auto.conf; reload or restart per context
trust in pg_hba.conf is only for testsEvery line is first-match; a stray trust opens the door
CREATE EXTENSION installs softwareFiles must exist on the server first; some need shared_preload_libraries
Minor upgrades need dump/restoreOnly majors do; minors swap binaries
\d works in application codeBackslash commands are psql features only
Prepared statements are always fasterPoolers and generic plans can make them slower or break them

Cheat sheet ​

TopicWhat to remember
Process modelpostmaster forks one backend per connection; auxiliary: checkpointer, background writer, walwriter, autovacuum, archiver
Port and slots5432; max_connections 100, restart to change
shared_buffersStart near 25% of RAM; 128MB default; restart
work_mem4MB per sort or hash node; use SET LOCAL for heavy queries
maintenance_work_mem64MB default; raise for index builds
wal_buffers-1 = 1/32 of shared_buffers, 64kB to 16MB
Layoutbase/<db oid>/<filenode>, pg_wal/, global/, pg_tblspc/; use pg_relation_filepath()
HierarchyCluster > database > schema > object; roles are cluster-wide
search_path"$user", public; pin per role; qualify names in SECURITY DEFINER functions
Catalogspg_class (relkind), pg_attribute, pg_index, pg_namespace, pg_proc, pg_settings
Configpg_settings.context: postmaster restart, sighup reload, user SET
ReloadSELECT pg_reload_conf(); or pg_ctl reload
pg_hba.confFirst match wins; scram-sha-256; reload
psql\d+, \x auto, \timing, \watch, \gexec, \conninfo, -E
ProtocolSimple = Query; extended = Parse/Bind/Execute; pgx default is extended with a statement cache
VersionsYearly major, 5-year support; 19.0 released 2026-11-19; minors need no dump

Self-check: questions & answers ​

Show:
  • 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 ​

TermMeaning
Cluster / instanceOne postmaster with one PGDATA; contains all databases
PostmasterFirst process; listens, authenticates, forks, restarts children
BackendPer-connection server process
Auxiliary processLong-lived helper: checkpointer, background writer, walwriter, autovacuum launcher, archiver
CheckpointPoint at which all dirty pages are flushed and a recovery start is recorded
Background writerProcess that writes dirty buffers ahead of need
WAL (write-ahead log)Sequential log of changes written before data pages
WAL buffersShared memory holding WAL not yet flushed
Shared buffersPostgreSQL's page cache in shared memory
work_memMemory limit per sort or hash operation before spilling
maintenance_work_memMemory for VACUUM, index builds, foreign-key additions
effective_cache_sizePlanner's estimate of total cache available; allocates nothing
Huge pagesLarge OS memory pages for the shared segment (huge_pages)
PGDATAThe data directory
FilenodeNumber naming a relation's file; pg_class.relfilenode
TOASTOut-of-line storage for large column values
TablespaceA directory where relation files can be stored
System catalogTable describing the database's own objects (pg_class etc.)
information_schemaSQL-standard portable catalog views
SchemaNamespace for objects inside a database
RoleUser, group or both; cluster-wide
search_pathOrdered schema list for resolving unqualified names
ExtensionPackaged set of SQL objects installed with CREATE EXTENSION
shared_preload_librariesLibraries loaded at server start (restart needed)
pg_hba.confHost-based authentication rules; first match wins
pg_settingsView of all parameters with context and source
pg_reload_conf()Function that makes the server re-read config files
Simple query protocolOne Query message with SQL text
Extended query protocolParse, Bind, Execute; separate parameters, reusable statements
Prepared statementParsed (and possibly planned) statement reused across executions
SQLSTATEFive-character error code (53300, 42P01, ...)
Major / minor versionYearly feature release / bug-fix release (18.7)
pg_upgradeTool for in-place major upgrades
psql meta-commandBackslash command interpreted by psql, not the server

References ​

Built by Morteza Negahi