PostgreSQL settings and diagnosis: shared_buffers, work_mem, pg_stat_statements
The handful of settings that matter, the per-operation memory trap, and the views that find slow queries. A free visual lesson with sample data.
More on PostgreSQL
Keep learning
Overview
~25% of RAM Restart. Above ~40% rarely helps: the OS cache holds a second copy. 50-75% of RAM 16-64MB, more per session Per sort or hash node, per connection. Hash nodes may use hash_mem_multiplier (2.0) × this. VACUUM, CREATE INDEX, ALTER TABLE ADD FOREIGN KEY. Each autovacuum worker may use it. a few hundred at most Restart. Put PgBouncer in front instead of raising it. 1.1-1.5 on SSD Lower makes index scans look cheaper. -1 (off) Logs each slower statement with its duration. Adds I/O Timings to EXPLAIN and blk_read_time to pg_stat_statements. Check pg_test_timing first. Which statements cost the most time overall ORDER BY total_exec_time DESC What is running now and what it waits on WHERE state <> 'idle' pg_locks + pg_blocking_pids() Who blocks whom WHERE NOT granted Seq scans, dead tuples, last (auto)vacuum per table ORDER BY n_dead_tup DESC Unused indexes The plan of a slow statement, as it ran Each slow execution with parameters server log 64 GB server (toy) 16 GB, all backends work_mem per node OS page cache the rest: files, WAL, temp files effective_cache_size ≈ shared_buffers + OS cache (a hint to the planner) grows with connections × nodes fixed at start shrinks when backends grow A page read from a table may come from shared_buffers, from the OS cache, or from disk. 800 application connections go to PgBouncer in transaction mode, which lends 40 server connections to whichever client has an open transaction. PostgreSQL runs one operating system process per server connection. 800 app connections 40 server connections random_page_cost (default) random_page_cost (SSD) Planner page costs: seq_page_cost 1.0, random_page_cost default 4.0, which assumes spinning disks, and about 1.1 recommended for SSD. A lower random cost makes index scans look cheaper. The default 4.0 dates from spinning disks. On SSD, 1.1 lets the planner pick index and bitmap scans where they really are cheaper. chapters · postgresql PostgreSQL settings and diagnosis: shared_buffers, work_mem, pg_stat_statements A few memory and planner settings decide most of the speed. A few views tell you where the time goes.
1. Memory: one shared cache, many private budgets
Start shared_buffers near 25% of RAM. PostgreSQL reads through the OS, so the rest of RAM still caches data. effective_cache_size only tells the planner how likely an index page is already cached.
2. Connections: processes are expensive, so pool them
Every connection is an OS process with its own memory and catalog caches. Hundreds of mostly idle connections still cost RAM and slow snapshot building. PgBouncer in transaction mode lends a backend per transaction. Session state does not survive between transactions: SET, temp tables, advisory locks and LISTEN. PgBouncer 1.21+ can keep protocol-level prepared statements (max_prepared_statements).
3. Planner costs and the knobs that live elsewhere
Autovacuum settings (autovacuum_vacuum_scale_factor, cost limits, workers) are in MVCC and VACUUM. WAL settings (max_wal_size, checkpoint_timeout, synchronous_commit) are in WAL and checkpoints.
4. Find the statement worth fixing
Sort by total_exec_time: a 4 ms query run two million times beats a 48 s report run once a month. Reset with pg_stat_statements_reset() after a fix and compare. Latency spikes that come and go are covered in jitter.
Reference: settings and views
Settings that matter (defaults for PostgreSQL 16/17) Starting point Where to look View or setting Start with
Recap
work_mem applies per sort or hash node, per connection, per parallel worker. Keep it modest globally and raise it per session. Each connection is a process. Pool with PgBouncer in transaction mode rather than raising max_connections. On SSD set random_page_cost near 1.1. Autovacuum and WAL knobs have their own chapters. pg_stat_activity shows what runs and waits now, pg_locks who blocks, pg_stat_user_tables where scans and dead tuples pile up.
More courses
- Jobs, linked to lessons — Browse jobs where every requirement links to the chapter that teaches it. See how ready you are, how long the gap takes to close, and which listings look stale.
- Match a job post to courses — Paste a job post. Each skill is matched to a track here and put in learning order, foundations first.
- React patterns from open source — Patterns extracted from Material UI, Radix, React Aria, React Hook Form, Redux Toolkit, TanStack, and Next.js — not slides about hooks.
- System Design — Core concepts first (SQL vs NoSQL, CAP, indexing, replication, sharding), then designs grouped by what carries them: the database, Redis, Kafka, or many services.
- NestJS: build a real API — One ticket-booking API, built in order: a plain Node server first, then NestJS modules, validation, a real database, and the features real clients lean on.
- Microservices — Microservice patterns one diagram at a time: how to split a monolith, how services talk, and how data stays consistent without distributed transactions.
- Kafka — A beginner-to-senior path through event logs, reliable delivery, production operations, and disaster recovery.
- AI engineering for software engineers — Eight free reads, in order, for software engineers moving into AI: when to build an agent, how to build one, how to test it, and how the model works underneath.
- Frontend system design — How a UI is sliced when it is a product, not a page: ownership of state, cache, routes, and what happens when the network lies.
- TypeScript in depth — The type system as a design tool. Inference, narrowing, generics, and the errors that mean the model is wrong — not a catalog of utility types.
- CSS in depth — See the box, then the page. Visual chapters from the box model through Flexbox surprises, Grid, selectors, and units, then backgrounds, shapes, and visual effects, each with a playground.
- Accessibility — Foundations first (WCAG in plain words, semantic HTML, lists, alt text), then hands-on HTML labs, a full pass of WAI-ARIA 1.3, and a final fix-the-page challenge.
- Docker — What an image is, why layers cache, and how containers find each other on a network.
- Redis — Fifteen Redis patterns, one picture each: cache, session, lock, counter, rate limiter, queue, and when Redis is the wrong tool.
- Kubernetes — Kubernetes from zero to operators: why it exists, Pods, Deployments and Services, then configuration, networking, storage, scheduling, scaling and security.
- AWS — AWS networking in plain English. A VPC is a gated housing society: streets are subnets, the Internet Gateway is the main gate, and a route table is the signboard.
- Networking: the NetRoute game — NetRoute is a packet logistics game. You wire up computers, switches, routers, firewalls and gateways, set each device, and watch glowing packets travel. If a packet gets dropped, the game shows you which header field was wrong.