Working with Billion-Row Tables
"Note that loading a large number of rows using COPY is almost always faster than using INSERT, even if PREPARE is used and multiple insertions are batched into a single transaction." — PostgreSQL documentation, Populating a Database (Performance Tips)
Summary: A table with a billion rows is not a different kind of table, it is the same table with every cost multiplied: a full scan, an index build, a VACUUM, a backfill or a DELETE that took seconds now takes hours and can hurt everyone else; the playbook is to estimate first, load in bulk, change data in small key-range slices, and remove data by dropping whole partitions. Focus: Size and capacity arithmetic, bulk loading (COPY, LOAD DATA, UNLOGGED, wal_level), statistics and index choices at scale (BRIN, partial indexes), batched backfills, vacuum and freeze on huge tables, index builds and REINDEX CONCURRENTLY, archiving and deletion, replication lag, monitoring, and the MySQL/InnoDB equivalents. Learning goal: Given a table of 1-10 billion rows, estimate its size and how long each maintenance operation will take, pick the load, backfill, index and retention strategy that does not stall production, and watch it with the progress views.
This page is the operational playbook for very large tables in PostgreSQL, with MySQL/InnoDB alongside. It deliberately links instead of re-teaching: how pages, tuples and TOAST are laid out is in Database Internals; dead tuples, VACUUM, bloat and transaction-ID wraparound are in MVCC, VACUUM & Bloat; index types and design are in Indexing; statistics, EXPLAIN and planner choices are in Query Planning; declarative partitioning and sharding are in Partitioning & Sharding in PostgreSQL; online ALTER TABLE and gh-ost are in Zero-Downtime Schema Migrations; replication lag is in Replication & Failover; WAL is in Durability & Crash Recovery; columnar engines are in OLTP vs OLAP & Columnar Storage; keyset scanning is in Pagination and Cursors & Streaming; when one server is no longer enough is in Storage & Data Scaling.
Page map
| If you are looking for | Go to |
|---|---|
| The one-page summary of what changes at a billion rows | Everything in one minute |
| Why "just run it" stops working | Why big tables behave differently |
| How big will it be, and what does it cost? | Estimating size and capacity |
| Fast initial or recurring loads | Bulk loading |
ANALYZE, default_statistics_target, estimated counts | Statistics and counting |
| BRIN, partial indexes, parallel index builds | Indexes that stay affordable |
| Changing every row without a lock or WAL storm | Batched backfills and updates |
| Autovacuum thresholds, freeze, wraparound risk | Vacuum on huge tables |
| Removing old data | Deleting, dropping and archiving |
| Replicas, analytics offload, columnar | Replication lag and read offload |
Progress views, pg_stat_io | Monitoring long operations |
| WAL flow, HOT updates, parallel query, error codes | Mechanics |
InnoDB LOAD DATA, buffer pool, online DDL, history list | MySQL and InnoDB at scale |
| Code in Go and Laravel | Solving the classic problems |
| Which technique for which job | Choosing a technique |
| Monolith to sharded | In architecture |
| Reproduce with 50 million rows | Lab |
Everything in one minute
What breaks first as a table grows.
| Operation | At a million rows | At a billion rows | Do this instead |
|---|---|---|---|
SELECT count(*) | Instant | Minutes of sequential I/O | Estimate from pg_class.reltuples, or keep a counter |
UPDATE t SET x = ... (all rows) | Seconds | Hours, one transaction, huge WAL, bloat doubled | Batched backfill by key range |
CREATE INDEX | Seconds | Hours, big temp sort | Parallel build, large maintenance_work_mem, CONCURRENTLY on live tables |
DELETE old rows | Seconds | WAL storm, dead tuples, long VACUUM | DROP/DETACH PARTITION |
| Autovacuum | Rarely noticed | Fires late (20% of a billion would be 200 million dead tuples; the default cap is 100 million) or runs for days | Per-table thresholds, absolute limits |
Row-by-row INSERT | Fine | Days | COPY, LOAD DATA |
ALTER TABLE ... ADD COLUMN with rewrite | Seconds | Table rewrite, long lock | Online DDL, gh-ost, ADD COLUMN without rewrite |
| Wraparound safety | Invisible | A real operational risk | Watch age(relfrozenxid) |
The four rules.
| Rule | In plain words | Tool |
|---|---|---|
| Estimate before you run | Size, WAL volume and duration are arithmetic, not surprises | pg_total_relation_size, row width, throughput benchmark on a slice |
| Bulk in, slices out | Load in one big stream; change in small committed slices | COPY, key-range batches |
| Remove data by dropping containers | Never DELETE a month; drop its partition | Partitioning |
| Watch it while it runs | Every long operation reports progress | pg_stat_progress_*, pg_stat_io |
Defaults you will meet (PostgreSQL 19 manual, MySQL 8.4 manual).
| Knob | Default | Why it matters at scale |
|---|---|---|
maintenance_work_mem | 64MB | Index builds and VACUUM are slow with a tiny sort/dead-tuple budget |
default_statistics_target | 100 | Skewed columns on huge tables may need more |
autovacuum_vacuum_scale_factor | 0.2 | 20% of a billion rows would be 200 million dead tuples; the default cap below lowers it to 100 million |
autovacuum_vacuum_max_threshold | 100,000,000 | Caps the trigger; check the docs for your version |
autovacuum_vacuum_cost_delay | 2 ms | Throttles autovacuum I/O |
vacuum_cost_limit | 200 | Work allowed between sleeps |
autovacuum_freeze_max_age | 200 million | Forces an anti-wraparound vacuum |
BRIN pages_per_range | 128 | Range granularity of a BRIN index |
innodb_buffer_pool_size (MySQL) | See manual | On a dedicated server, the manual suggests 80% of physical memory |
Why big tables behave differently
Three things scale with row count at the same time. I/O volume grows linearly: a sequential scan of a 1 TB table at 1 GB/s still takes about 17 minutes, and almost nothing you do on the whole table is faster than that. Per-row overhead adds up: a 24-byte header (23 bytes plus padding) and a 4-byte line pointer per row (see Database Internals) is 28 GB of pure overhead per billion rows. Background work is triggered by proportions (autovacuum by 20%, statistics by 10% changed) and therefore fires later and lasts longer on a big table. The result is that operations stop being "a query" and become "a project" that must be planned, throttled and observed.
| Small table instinct | Billion-row reality |
|---|---|
| One transaction is simplest | One transaction holds locks and a snapshot for hours, blocks vacuum everywhere |
| Add an index, it is quick | A B-tree can be as large as the table; the build competes for I/O with production |
DELETE WHERE created_at < ... | Writes every deleted row to WAL, leaves dead tuples, bloats indexes |
| Let autovacuum handle it | Defaults are proportional; you tune per table |
| The replica is a copy | The replica replays the same WAL storm and lags or cancels queries |
The analogy we reuse on this page: a city's water pipe network. Maintenance on a small block is a bucket job. Maintenance on a whole city means closing valves street by street (slices), never draining everything at once (one transaction), measuring flow while you work (progress views), and building the new main pipe next to the old one before switching (concurrent builds). Retiring old pipe is lifting a whole section out (drop partition), not unscrewing each fitting (DELETE).
Three common misunderstandings, up front
- "It is only slow because the table is big, so a bigger machine fixes it." Notion's engineers wrote that "Query performance and upkeep processes often begin to degrade well before a table reaches the maximum hardware-bound size." Maintenance cost is superlinear in practice because of vacuum, caching and replication interactions.
- "
DELETEis how you remove data." On a huge tableDELETEis the most expensive way: it logs every row, leaves dead tuples and needs a vacuum afterwards. Dropping a partition does none of that. - "
count(*)is a cheap metadata lookup." PostgreSQL and InnoDB must scan to count under MVCC; only an estimate is cheap.
Estimating size and capacity
Row width, tuple overhead and page fit Must-know
In plain words: A row costs more than the sum of its columns: there is a fixed header, a null bitmap, alignment padding and a 4-byte pointer. Narrow rows pay proportionally more overhead.
Common misunderstanding: "A table with three bigint columns is 24 bytes per row." In PostgreSQL it is closer to 24 (header, padded) + 24 (data) + 4 (line pointer) = about 52 bytes, and the page (8 kB, 24-byte page header) fits fewer rows than division by 24 suggests.
Definition: In a PostgreSQL heap page, "All table rows are structured in the same way. There is a fixed-size header (occupying 23 bytes on most machines), followed by an optional null bitmap, an optional object ID field, and the user data." Each row also needs a 4-byte item identifier. Column order creates alignment padding (an int8 aligns to 8 bytes), so putting wide fixed columns first and boolean/smallint last can save bytes per row. InnoDB rows have their own overhead (a hidden transaction id and roll pointer, and the clustered index stores the primary key in every secondary index).
1 estimate rows/page = (8192 - 24) / (24 header + data_width + 4 pointer)
2 estimate heap size = rows / rows_per_page * 8192 bytes
3 estimate index size = rows * (key_width + ~8 bytes pointer/overhead) / fill (~0.7-0.9)
4 compare with reality -> SELECT pg_total_relation_size('events') on a 1% sampleReal scenario: an events table with (id bigint, account_id bigint, created_at timestamptz, amount_cents bigint, payload text). Data width is about 32 bytes plus a short text; call it 80 bytes per row all-in. One billion rows is about 80 GB heap, plus a primary key B-tree (about 30 GB for bigint) and a second index on (account_id, created_at) (about 40 GB). Backups, replicas and WAL scale with this sum, not with the heap.
| Measure | PostgreSQL | MySQL InnoDB |
|---|---|---|
| Row header | 23 bytes + padding, 4-byte pointer | Variable record header, hidden DB_TRX_ID and DB_ROLL_PTR |
| Page size | 8 kB | 16 KB |
| Table size function | pg_table_size, pg_total_relation_size | information_schema.TABLES (DATA_LENGTH, INDEX_LENGTH) |
| Value size function | pg_column_size(col) | LENGTH() / OCTET_LENGTH() |
| Secondary index carries | ctid (heap pointer) | The primary key |
-- PostgreSQL: measure real width and size on a sample, then extrapolate
SELECT avg(pg_column_size(t.*)) AS avg_row_bytes FROM (SELECT * FROM events TABLESAMPLE SYSTEM (1)) t;
SELECT pg_size_pretty(pg_table_size('events')) AS heap,
pg_size_pretty(pg_indexes_size('events')) AS indexes,
pg_size_pretty(pg_total_relation_size('events')) AS total;
-- per-index size
SELECT indexrelid::regclass AS idx, pg_size_pretty(pg_relation_size(indexrelid)) FROM pg_index WHERE indrelid = 'events'::regclass;TOAST: wide values live elsewhere Important
In plain words: Big values (long text, jsonb, bytea) are compressed and moved into a side table, so the main heap stays narrow.
Common misunderstanding: "pg_relation_size is the table size." It excludes TOAST and indexes; use pg_total_relation_size. Also, "a jsonb column is free to update" is wrong: changing a TOASTed value rewrites the whole value.
Definition: PostgreSQL's manual says that "The TOAST management code is triggered only when a row value to be stored in a table is wider than TOAST_TUPLE_THRESHOLD bytes (normally 2 kB)". It then compresses or moves values out-of-line until the row is shorter than TOAST_TUPLE_TARGET (also normally 2 kB, adjustable per table with ALTER TABLE ... SET (toast_tuple_target = N)). "an UPDATE of a row with out-of-line values incurs no TOAST costs if none of the out-of-line values change." Details of the layout are in Database Internals.
1 INSERT row with 6 kB payload
2 heap tuple exceeds 2 kB -> payload compressed, then chunked into pg_toast.pg_toast_NNNN
3 heap row keeps a pointer -> scans that never read payload never touch TOAST
4 UPDATE ... SET status = 'x' (payload unchanged) -> new heap tuple, same TOAST pointerReal scenario: a 2 TB table is 400 GB of heap and 1.6 TB of TOAST; a backfill that touches only a narrow status column is cheap, while SELECT * pulls the TOAST data and is not.
| Situation | Effect | Action |
|---|---|---|
SELECT * on wide rows | Detoasts every large value | Select needed columns only |
| Updating a TOASTed column | Writes the new value to TOAST, old chunks dead | Avoid frequent updates of big blobs |
| Updating a narrow column of a wide row | Heap tuple is new; TOAST untouched | Cheap relative to row size |
| Size reporting | pg_relation_size hides TOAST | pg_total_relation_size |
Capacity planning arithmetic Must-know
In plain words: Before you start, write down four numbers: how big, how fast the disk is, how much WAL it will produce, and how long it will take.
Common misunderstanding: "WAL is small, the data is the cost." Every modified byte is logged (plus full-page images after a checkpoint), so a full-table update can write more WAL than the table is large, and WAL is what replicas, archive storage and backups must carry.
Definition: Capacity planning = size (heap + indexes + TOAST) x copies (replicas, backups, PITR archive) x growth, plus transient space for the operation itself (index build sort files, VACUUM FULL/rewrite needs 2x, online DDL log).
1 size_now = pg_total_relation_size(table)
2 throughput = measure: COPY or UPDATE of 1% slice, rows/s and MB/s of WAL
3 duration = size / throughput (index builds: ~ sort + write, 2-3x scan time)
4 free disk = need size (new index) + WAL until archived + safety 30%
5 replica budget = WAL bytes/s <= replica replay bytes/s, else lag grows| Resource | What consumes it | Check |
|---|---|---|
| Disk | New indexes, rewrites (VACUUM FULL, ALTER TYPE), temp files, WAL not yet archived | df, pg_wal size, replication slots |
| WAL | Bulk updates, index builds, full-page writes after checkpoint | pg_stat_wal, pg_current_wal_lsn() delta |
| I/O | Scans, builds, vacuum, replica catch-up | pg_stat_io, cloud IOPS graphs |
| Memory | maintenance_work_mem, shared buffers hit ratio | pg_stat_io, buffer cache hit |
| Time | Everything above divided by throughput | A trial on a slice |
Bulk loading
COPY and LOAD DATA Must-know
In plain words: COPY (PostgreSQL) and LOAD DATA (MySQL) stream a file or a client feed straight into a table with far less per-row work than INSERT statements.
Common misunderstanding: "Batching INSERTs in one transaction is nearly as good." It is much better than autocommit per row, but PostgreSQL's manual says COPY is almost always faster than INSERT even with PREPARE and batching, and the MySQL manual says LOAD DATA "is usually 20 times faster than using INSERT statements".
Definition: COPY table FROM STDIN | 'file' reads text, CSV or binary rows in one command. The "Populating a Database" page lists the recipe: disable autocommit (one commit at the end) or use COPY; remove indexes; remove foreign key constraints; raise maintenance_work_mem and max_wal_size; consider disabling WAL archival and streaming replication; run ANALYZE afterwards.
1 client opens COPY events FROM STDIN (FORMAT binary)
2 client streams rows -> server parses, no per-row planning, no per-row round trip
3 rows inserted into heap pages in bulk; indexes (if present) updated per row
4 COPY ends -> one commit; WAL written (unless the load qualifies for minimal WAL)
5 ANALYZE -> planner statistics are fresh| Method | Per-row cost | Notes |
|---|---|---|
Autocommit single-row INSERT | A WAL flush per row | Slowest by a wide margin |
Multi-row INSERT ... VALUES (...), (...) in one transaction | Parse once per statement | Typical batch sizes 500-5,000 rows; bounded by the 65,535 bind-parameter limit in PostgreSQL's protocol |
INSERT ... SELECT / CREATE TABLE AS | No client round trip | Best when data is already in the database |
COPY FROM (PostgreSQL), text/CSV | One command | Needs file access or STDIN |
COPY ... (FORMAT binary) | No text parsing | Used by pgx CopyFrom |
LOAD DATA [LOCAL] INFILE (MySQL) | One statement | LOCAL needs local_infile; server-side files need secure_file_priv rules |
pg_restore -j | Parallel per table / index | For dumps |
-- PostgreSQL: fastest steady load
BEGIN;
SET LOCAL maintenance_work_mem = '2GB';
COPY events (id, account_id, created_at, amount_cents, payload)
FROM '/data/events.csv' WITH (FORMAT csv);
COMMIT;
ANALYZE events;
-- MySQL: LOAD DATA
SET autocommit = 0; SET unique_checks = 0; SET foreign_key_checks = 0;
LOAD DATA LOCAL INFILE '/data/events.csv' INTO TABLE events
FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n'
(id, account_id, created_at, amount_cents, payload);
COMMIT; SET unique_checks = 1; SET foreign_key_checks = 1;"When loading a table from a text file, use LOAD DATA. This is usually 20 times faster than using INSERT statements." — MySQL 8.4 Reference Manual, Optimizing INSERT Statements
The Go loader for this is copyload/main.go: one connection per worker, binary CopyFrom, one transaction per id slice.
Load order: stage, load bare, index, constrain, analyze Must-know
In plain words: Create the table with no secondary indexes and no foreign keys, load it, then build the indexes in one pass.
Common misunderstanding: "Keep the indexes so the table is always ready." Updating a B-tree row by row during load means random writes and page splits; building once from sorted data is faster and produces a tighter index. PostgreSQL's manual: "Creating an index on pre-existing data is quicker than updating it incrementally as each row is loaded."
Definition: For an empty or newly created table: create, COPY, create indexes, add constraints, ANALYZE. For adding to a live table: weigh dropping indexes (other users suffer) against load time; "One should also think twice before dropping a unique index, since the error checking afforded by the unique constraint will be lost".
1 CREATE TABLE events (...) -- no indexes yet
2 COPY events FROM ... -- parallel slices possible
3 CREATE INDEX ... (parallel, big maintenance_work_mem)
4 ALTER TABLE ... ADD FOREIGN KEY ... NOT VALID; ALTER TABLE ... VALIDATE CONSTRAINT ...
5 ANALYZE events -- fresh statistics| Step | Why this order | Risk if reversed |
|---|---|---|
| Load before indexes | Index built once | Per-row index maintenance multiplies load time |
| Foreign keys after load | Checked in bulk | Pending trigger queue can exhaust memory: the manual says it "may be necessary, not just desirable, to drop and re-apply foreign keys" |
ANALYZE last | Planner needs true distribution | Bad plans on first queries |
COPY ... FREEZE on a new/truncated table | Rows written already frozen | Not allowed on partitioned tables |
Batch sizes, autocommit and checkpoints
In plain words: Commit often enough that a failure costs little, rarely enough that you are not paying a flush per row.
Common misunderstanding: "Bigger batches are always faster." Beyond a point (thousands of rows per statement; 100k-1M rows per transaction) returns flatten, memory and lock hold time grow, and a failed batch is expensive to redo.
Definition: Each commit forces a WAL flush; a batch of N rows amortizes it. max_wal_size and checkpoint_timeout govern checkpoint frequency; the manual notes that "loading a large amount of data into PostgreSQL will cause checkpoints to occur more often than the normal checkpoint frequency" and recommends temporarily raising max_wal_size.
| Engine | Setting | Effect during bulk load |
|---|---|---|
| PostgreSQL | max_wal_size up | Fewer checkpoints |
| PostgreSQL | synchronous_commit = off (session) | No wait for flush; a crash loses the last moments, never corrupts |
| MySQL | autocommit = 0 | "performs a log flush to disk for every insert" otherwise |
| MySQL | innodb_autoinc_lock_mode = 2 | Interleaved lock mode for bulk inserts with AUTO_INCREMENT |
| MySQL | bulk_insert_buffer_size | Larger buffer for bulk inserts into a non-empty table (a MyISAM setting; InnoDB ignores it) |
| MySQL | Insert in PRIMARY KEY order | Clustered index appends instead of splitting pages |
UNLOGGED tables and wal_level=minimal Important
In plain words: You can skip writing WAL for a load, at the price of crash safety and replication for that table.
Common misunderstanding: "UNLOGGED is a safe speed-up." The manual: unlogged data "is not written to the write-ahead log (see Chapter 28), which makes them considerably faster than ordinary tables. However, they are not crash-safe: an unlogged table is automatically truncated after a crash or unclean shutdown. The contents of an unlogged table are also not replicated to standby servers."
Definition: Two separate mechanisms. UNLOGGED makes one table skip WAL for ever (until ALTER TABLE ... SET LOGGED, which writes the whole table to WAL). wal_level = minimal (with archive_mode = off, max_wal_senders = 0) lets COPY into a table created or truncated in the same transaction skip WAL, because "They can guarantee crash safety more cheaply by doing an fsync at the end than by writing WAL". It needs a restart and "makes any base backups taken before unavailable for archive recovery and standby server".
1 stop writes; take note: a new base backup is required afterwards
2 set wal_level = minimal, archive_mode = off, max_wal_senders = 0; restart
3 BEGIN; TRUNCATE events; COPY events FROM ...; COMMIT; -- no WAL for the data
4 restore wal_level = replica (or logical); restart
5 take a fresh base backup; rebuild standbys if they were detached| Approach | Crash-safe | Replicated | Backup/PITR | When |
|---|---|---|---|---|
Normal table, wal_level = replica | Yes | Yes | Yes | Default; production tables |
UNLOGGED table | No (truncated after crash) | No | Not in WAL | Staging area, derived data you can rebuild |
wal_level = minimal + same-transaction COPY | Yes | Standbys impossible while set | Breaks PITR for the window | One-time migration into an empty system |
SET LOGGED after loading unlogged | Yes after the rewrite | Yes | Yes | Load fast, then promote; costs a full WAL write |
MySQL bulk-load settings
In plain words: InnoDB wants the same shape: few commits, ordered keys, checks relaxed during the load.
Common misunderstanding: "SET unique_checks=0 is free." The manual: "Be certain that the data contains no duplicate keys", because the checks are skipped and violations are not detected.
Definition: The manual's bulk-loading page: turn off autocommit, optionally unique_checks=0 and foreign_key_checks=0 ("For big tables, this saves a lot of disk I/O because InnoDB can use its change buffer"), use multi-row INSERT, innodb_autoinc_lock_mode = 2, and insert in PRIMARY KEY order.
| Knob | Safe? | Revert |
|---|---|---|
SET autocommit=0; ... COMMIT; | Yes | Commit |
SET unique_checks=0 | Only if data is known unique | SET unique_checks=1 |
SET foreign_key_checks=0 | Only if data is known consistent | SET foreign_key_checks=1 |
LOAD DATA LOCAL | Needs local_infile enabled; a security trade-off | Disable local_infile after |
Statistics and counting
default_statistics_target and ANALYZE sampling Must-know
In plain words: The planner does not read your table; it reads a small summary built from a random sample. On a billion rows the summary is the whole basis for its choices.
Common misunderstanding: "ANALYZE reads the whole table, so statistics are exact." The manual says that "For large tables, ANALYZE takes a random sample of the table contents, rather than examining every row" and that statistics are "only approximate, and will change slightly each time ANALYZE is run".
Definition: The sample size depends on the largest statistics target among the analyzed columns: "Increasing the target causes a proportional increase in the time and space needed to do ANALYZE". default_statistics_target defaults to 100; raise it per column with ALTER TABLE ... ALTER COLUMN ... SET STATISTICS n for skewed columns (a few tenants own most rows, status values with a rare but important value). Planner behaviour itself is in Query Planning.
1 ANALYZE events -- samples ~ a multiple of the target, not all rows
2 pg_statistic: most_common_vals, histogram_bounds, n_distinct per column
3 query: WHERE account_id = 7 AND created_at > ... -> planner multiplies selectivities
4 correlated columns -> underestimate -> nested loop on millions of rows
5 fix -> CREATE STATISTICS (dependencies, ndistinct, mcv) or raise the target| Symptom | Likely cause | Action |
|---|---|---|
| Estimate off by 100x after a bulk load | No ANALYZE yet | ANALYZE events ("strongly recommended" after bulk load) |
| Good plan for most tenants, terrible for the biggest | Skew not captured at target 100 | SET STATISTICS 1000 on the column |
| Correlated columns underestimated | Independence assumption | CREATE STATISTICS ... (dependencies, mcv) |
ANALYZE slow on a huge table | High target | Raise only on columns that need it; autovacuum analyses in background |
| Partitioned table never analysed | Autovacuum does not analyse the parent | Run ANALYZE parent manually or on a schedule |
ALTER TABLE events ALTER COLUMN account_id SET STATISTICS 1000;
ANALYZE VERBOSE events;
SELECT attname, n_distinct, correlation FROM pg_stats WHERE tablename = 'events';Counting rows: estimate versus exact Must-know
In plain words: An exact count means visiting every visible row; a good-enough count is already stored.
Common misunderstanding: "Add an index and count(*) becomes fast." An index-only scan helps but still visits the visibility map; on a billion rows it is still a long scan. Under MVCC each row's visibility depends on your snapshot, so there is no single stored exact count.
Definition: The planner keeps reltuples and relpages in pg_class; "They are updated by VACUUM, ANALYZE, and a few DDL commands such as CREATE INDEX" and "usually contain somewhat out-of-date values". For InnoDB TABLE_ROWS in information_schema.TABLES is likewise an estimate.
1 need a number for a dashboard
2 accurate to ~1%? -> SELECT reltuples FROM pg_class WHERE oid = 'events'::regclass
3 need a filtered estimate? -> parse EXPLAIN (FORMAT JSON) "Plan Rows"
4 need exact? -> maintained counter table, or count within a partition, or accept the scan| Need | Technique | Accuracy | Cost |
|---|---|---|---|
| Table size for UI | pg_class.reltuples | Approximate | Instant |
| Rows matching a filter (estimate) | EXPLAIN row estimate | Planner-quality | Instant |
| Exact total, rarely | count(*) (parallel seq scan) | Exact | Full scan |
| Exact total, often | Counter table updated in the same transaction, or a trigger-maintained rollup | Exact | Write contention on one row; shard the counter |
| Distinct count at scale | HyperLogLog (postgresql-hll), see Bloom Filters & Probabilistic Structures | ~1-2% | Small |
| Redis style counters | INCR in Redis | Exact, outside the DB | Extra system |
SELECT reltuples::bigint AS approx_rows FROM pg_class WHERE oid = 'events'::regclass;
-- estimated rows for a predicate, without running it
EXPLAIN (FORMAT JSON) SELECT 1 FROM events WHERE account_id = 7;
SET max_parallel_workers_per_gather = 8; -- exact count: parallel sequential scan
SELECT count(*) FROM events;Indexes that stay affordable
BRIN for append-only time data Must-know
In plain words: A BRIN index stores only the minimum and maximum of a column for every group of adjacent pages. If the data is physically in order (timestamps in insertion order), that is enough to skip most of the table, at a tiny fraction of a B-tree's size.
Common misunderstanding: "BRIN is a smaller B-tree." It is a different trade: it never finds an exact row, only ranges of pages to scan; if the column is not correlated with physical order (random UUIDs, heavily updated rows), it prunes nothing.
Definition: "BRIN stands for Block Range Index. BRIN is designed for handling very large tables in which certain columns have some natural correlation with their physical location within the table." The range is set by pages_per_range (default 128): "the smaller the number, the larger the index becomes (because of the need to store more index entries), but at the same time the summary data stored can be more precise and more data blocks can be skipped". New ranges are summarised by VACUUM or by brin_summarize_new_values; autosummarize (default off) queues it on insertion. BRIN supports parallel builds.
1 table pages 0..127 -> summary: created_at min=2026-01-01, max=2026-01-01 00:08
2 table pages 128..255-> summary: min=...00:08, max=...00:16
3 query WHERE created_at >= '2026-01-01 00:10'
4 scan index (tiny) -> ranges whose max < cutoff are skipped
5 heap scan only the matching ranges (bitmap heap scan), recheck the rows"BRIN stands for Block Range Index. BRIN is designed for handling very large tables in which certain columns have some natural correlation with their physical location within the table." — PostgreSQL documentation, BRIN Indexes
| Index | Size on 1 billion timestamps (indicative) | Finds one row | Range query | Needs physical order |
|---|---|---|---|---|
| B-tree | Tens of GB | Yes, fast | Yes | No |
BRIN (pages_per_range 128) | Megabytes | No | Yes, if correlated | Yes |
BRIN (pages_per_range 32) | Larger, still small | No | Finer pruning | Yes |
| Partitioning by range | Metadata only | n/a | Prunes whole partitions | Data lands in right partition |
CREATE INDEX events_created_brin ON events USING brin (created_at) WITH (pages_per_range = 64);
SELECT pg_size_pretty(pg_relation_size('events_created_brin'));
SELECT correlation FROM pg_stats WHERE tablename = 'events' AND attname = 'created_at'; -- near 1.0 is goodPartial indexes Important
In plain words: Index only the rows you actually look up. If 98% of orders are "done" and you only query the 2% that are not, index just those.
Common misunderstanding: "More indexed rows means faster queries." On a huge table every indexed row costs write time, space and vacuum work; the manual's reason for partial indexes is "to avoid indexing common values", because a query for a common value will not use an index anyway.
Definition: CREATE INDEX ... WHERE predicate. The query must contain a predicate the planner can prove implies the index predicate. Details are in Indexing.
1 orders: 1,000,000,000 rows, status='done' for 99%, status in ('new','paid') for 1%
2 CREATE INDEX orders_open ON orders (created_at) WHERE status <> 'done'
3 index holds ~10,000,000 entries instead of 1,000,000,000
4 WHERE status = 'new' AND created_at > now() - interval '1 day' -> index usable
5 WHERE created_at > ... (no status predicate) -> index NOT usable| Pattern | Index | Saves |
|---|---|---|
| Queue of unprocessed rows | WHERE processed_at IS NULL | 99% of entries |
| Soft deletes | WHERE deleted_at IS NULL | Dead rows |
| Hot recent data | WHERE created_at >= date (rotate) | Old entries; prefer partitioning |
| Rare flag | WHERE is_flagged | Nearly everything |
| MySQL equivalent | None (use generated column + index, or functional index) | n/a |
Partition pruning Must-know
In plain words: If the table is split by date and your query names a date range, the planner skips every partition outside it without opening them.
Common misunderstanding: "Partitioning makes every query faster." Only queries that filter on the partition key benefit; a query without the key visits every partition and can be slower than on one table (more planning, more files).
Definition: "Partition pruning is a query optimization technique that improves performance for declaratively partitioned tables." It is "driven only by the constraints defined implicitly by the partition keys, not by the presence of indexes", and depends on enable_partition_pruning (default on). Design and sharding live in Partitioning & Sharding in PostgreSQL.
1 events PARTITION BY RANGE (created_at): 36 monthly partitions
2 SELECT ... WHERE created_at >= '2026-06-01' AND created_at < '2026-07-01'
3 EXPLAIN -> Append -> only events_2026_06 listed (others pruned at plan time)
4 parameterised query -> pruning can also happen at executor start ("Subplans Removed: N")
5 SELECT ... WHERE account_id = 7 (no key) -> all 36 partitions scanned| Query filter | Partitions touched | Note |
|---|---|---|
| Constant range on the key | Only matching ones | Best case |
| Parameter / prepared statement | Pruned at executor start | EXPLAIN shows removed subplans |
Function wrapped around the key (date_trunc('month', created_at)) | Often all | Compare the raw column to constants |
No key in WHERE | All | Add the key or a covering index per partition |
MySQL (PARTITION BY RANGE) | Pruning by the same idea | EXPLAIN partitions column |
Parallel index builds, maintenance_work_mem and CONCURRENTLY Must-know
In plain words: Index builds sort the whole column; give them memory, workers and a way not to block writes.
Common misunderstanding: "CREATE INDEX CONCURRENTLY is just slower CREATE INDEX." It does two table scans and waits for old transactions, so a single long transaction anywhere delays the finish; it also leaves an invalid index on failure.
Definition: "PostgreSQL can build indexes while leveraging multiple CPUs... known as parallel index build" for B-tree, GIN and BRIN; maintenance_work_mem "specifies the maximum amount of memory that can be used by each index build operation as a whole, regardless of how many worker processes were started". Workers need at least a 32MB share and the leader another 32MB. max_parallel_maintenance_workers caps workers; per-table parallel_workers overrides the cost model. For CONCURRENTLY "only the first table scan is actually performed in parallel". Concurrent builds need "two scans of the table" and wait for transactions that predate each scan.
1 SET maintenance_work_mem = '4GB'; SET max_parallel_maintenance_workers = 6;
2 CREATE INDEX CONCURRENTLY events_acct ON events (account_id, created_at);
3 phase "building index: scanning table" -> "sorting live tuples" -> "loading tuples in tree"
4 waits for older transactions twice; a stuck idle-in-transaction session stalls it
5 failed? -> invalid index remains: DROP INDEX CONCURRENTLY, retry| Knob | Effect | Caution |
|---|---|---|
maintenance_work_mem | Bigger sort in memory, fewer spill passes | Autovacuum workers can each use up to this unless autovacuum_work_mem is set |
max_parallel_maintenance_workers | More workers on B-tree, GIN, BRIN builds and plain VACUUM | Limited by max_parallel_workers and max_worker_processes |
ALTER TABLE ... SET (parallel_workers = n) | Forces worker count | Reset afterwards: affects query plans too |
CONCURRENTLY | Writes continue | Twice the scans; check pg_stat_progress_create_index |
effective_io_concurrency / maintenance_io_concurrency | Prefetch depth | Storage-dependent |
REINDEX CONCURRENTLY durations
In plain words: Rebuilding a bloated index without blocking writes works by building a copy next to it and swapping.
Common misunderstanding: "REINDEX is quick maintenance." On a 100 GB index it is a multi-hour build that needs the same free space again; the concurrent form takes longer than the plain one.
Definition: REINDEX INDEX CONCURRENTLY creates a new index, waits for transactions, switches validity flags and drops the old one: "must perform two scans of the table for each index that needs to be rebuilt and wait for termination of all existing transactions that could potentially use the index. This method requires more total work than a standard index rebuild." A failed build leaves an invalid index (_ccnew is dropped and retried; _ccold is a leftover to drop).
| Task | Command | Locking | Time driver |
|---|---|---|---|
| Rebuild one index | REINDEX INDEX CONCURRENTLY idx | Reduced; waits on long transactions | Table scan x2 + sort |
| Rebuild all indexes of a table | REINDEX TABLE CONCURRENTLY t | Per index | Sum of indexes |
| Rebuild everything faster, offline | REINDEX TABLE t | ACCESS EXCLUSIVE on the table | Single pass |
| New index, never built | CREATE INDEX CONCURRENTLY | Reduced | As above |
| MySQL | ALTER TABLE ... ENGINE=InnoDB / OPTIMIZE TABLE (online DDL) | Mostly online | Rebuild of clustered index |
Batched backfills and updates
Why a full-table UPDATE is a lock and WAL storm Must-know
In plain words: One UPDATE of a billion rows is a single transaction: it locks every row it touches until the end, writes a new version of every row, and the table temporarily needs room for two copies.
Common misunderstanding: "It is just one statement, the database handles it." Under MVCC an update is an insert of a new row version plus a dead old version. The old rows cannot be vacuumed until the whole transaction ends, and indexes get new entries too, unless HOT applies (see MVCC & VACUUM).
Definition: The cost is: row locks (blocking writers to those rows for the whole duration), WAL (new tuple image per row, plus full-page images after checkpoints), table and index bloat (dead tuples), replica lag (the standby must replay it), and a held snapshot (vacuum horizon pinned). Rollback of a failed statement redoes the pain as dead tuples that vacuum must clean.
T1 (backfill) T2 (application)
1 BEGIN; UPDATE events SET region = 'eu';
2 -- 1,000,000,000 row versions written
3 UPDATE events SET status='x' WHERE id = 5; -- waits for T1's row lock
4 -- 6 hours later, WAL volume >= table size; replica lag grows
5 COMMIT;
6 -- T2 finally proceeds; dead tuples = table size, VACUUM runs for hours| Consequence | Mechanism | Visible as |
|---|---|---|
| Lock waits | Row locks held until commit | pg_stat_activity wait_event_type = Lock |
| WAL storm | Every new tuple logged | Disk full in pg_wal; pg_stat_wal |
| Bloat | Dead old versions | Table twice as large; slower scans |
| Replica lag | Standby replays one huge transaction | pg_stat_replication.replay_lag |
| Long snapshot | Oldest xmin pinned | Vacuum cannot remove anything newer |
| InnoDB | Undo log grows, history list length rises | Purge lags, SHOW ENGINE INNODB STATUS |
Batching by key range with sleeps Must-know
In plain words: Cut the id range into slices, update each slice in its own short transaction, sleep a little between slices, and make every slice safe to run twice.
Common misunderstanding: "Use LIMIT 10000 in the UPDATE and loop until 0 rows." That rescans from the start each time (cost grows with progress) and can loop forever if rows still match. Use a moving key range, as keyset pagination does in Pagination.
Definition: UPDATE ... WHERE id >= $lo AND id < $hi AND new_col IS NULL, then advance $lo. Each statement commits; locks last milliseconds; WAL arrives in steady small amounts; autovacuum and replicas keep up; the IS NULL predicate makes the job idempotent and resumable.
1 lo = MIN(id) WHERE region IS NULL ; hi = MAX(id)
2 UPDATE events SET region = ... WHERE id >= lo AND id < lo + 10000 AND region IS NULL; COMMIT
3 sleep 200 ms (or while replay_lag > 5 s)
4 lo = lo + 10000 ; goto 2 until lo > hi
5 crash? restart: MIN(id) WHERE region IS NULL resumes where it stopped| Parameter | Typical start | Tune by |
|---|---|---|
| Slice size | 5,000-20,000 rows | Aim for each statement under about 100 ms |
| Sleep | 100-500 ms | Replica lag, autovacuum keeping up, p99 latency of the app |
| Isolation | Read Committed default | Slices are independent |
| Lock wait | SET lock_timeout = '2s' | Retry on timeout instead of queueing behind a long app transaction |
| Index on the new column | Add after the backfill | Otherwise every update also maintains it |
-- one slice
UPDATE events SET region = CASE WHEN account_id % 2 = 0 THEN 'eu' ELSE 'us' END
WHERE id >= 5000000 AND id < 5010000 AND region IS NULL;
-- find where to resume
SELECT min(id) FROM events WHERE region IS NULL;Go (one connection, resumable, stops on Ctrl-C) and Laravel (chunkById) versions are in Solving the classic problems.
Generated columns, default values and rewrites
In plain words: Some ALTER TABLE forms rewrite the whole table; others only change the catalog.
Common misunderstanding: "Adding a column is always instant." Adding a nullable column with no default is a catalog change in PostgreSQL; since PostgreSQL 11 a constant DEFAULT is also instant, but a volatile default or a type change rewrites the table. Details in Zero-Downtime Schema Migrations.
Definition: A rewrite takes ACCESS EXCLUSIVE, writes a new copy of every row and index, and needs 2x the space. Prefer: add nullable column, backfill in slices, add NOT NULL via a CHECK ... NOT VALID then VALIDATE.
| Change | PostgreSQL | MySQL InnoDB |
|---|---|---|
| Add nullable column | Catalog only | Instant (8.0+ ALGORITHM=INSTANT) |
| Add column with constant default | Catalog only (11+) | Instant |
| Change column type | Usually rewrites | Rebuilds table |
Add NOT NULL | Scan, or CHECK ... NOT VALID + VALIDATE | Rebuild (online) |
| Large rebuild online | pg_repack, logical replication swap | gh-ost, pt-online-schema-change |
Vacuum on huge tables
Autovacuum thresholds are proportional Must-know
In plain words: Autovacuum starts after "20% of the table is dead" by default. On a billion rows that would be two hundred million dead tuples first; the default cap (autovacuum_vacuum_max_threshold, 100 million) lowers it to a hundred million, which is still a long wait.
Common misunderstanding: "Autovacuum defaults protect large tables." They protect the average one. The docs define: "vacuum threshold = Minimum(vacuum max threshold, vacuum base threshold + vacuum scale factor * number of tuples)", where the max threshold is autovacuum_vacuum_max_threshold (default 100,000,000 tuples), the base is autovacuum_vacuum_threshold (50) and the scale factor is autovacuum_vacuum_scale_factor (0.2). Insert-only tables get autovacuum_vacuum_insert_threshold (1000) and autovacuum_vacuum_insert_scale_factor (0.2).
Definition: Set per-table storage parameters on the big tables.
1 1,000,000,000 rows, scale 0.2 -> threshold min(100,000,000, 50 + 0.2*1e9) = 100,000,000 dead tuples
2 vacuum starts after 100M updates/deletes -> long run, big bloat first
3 with scale 0.01 and max cap: starts after ~10M -> shorter, more frequent
4 autovacuum cost delay (2 ms) + limit 200 throttles its I/O
5 tune cost limit up so it finishes before the next trigger| Parameter | Default | Large-table setting |
|---|---|---|
autovacuum_vacuum_scale_factor | 0.2 | 0.01 or 0 with absolute threshold |
autovacuum_vacuum_threshold | 50 | 10,000-1,000,000 |
autovacuum_vacuum_max_threshold | 100,000,000 | Lower per table |
autovacuum_analyze_scale_factor | 0.1 | 0.005-0.01 |
autovacuum_vacuum_cost_limit | -1 (uses vacuum_cost_limit 200) | 1,000-10,000 on fast storage |
autovacuum_vacuum_cost_delay | 2 ms | 0-2 ms |
autovacuum_max_workers | 3 | Raise if several giants; total cost limit is shared |
maintenance_work_mem / autovacuum_work_mem | 64MB | Larger dead-item memory = fewer index passes |
ALTER TABLE events SET (
autovacuum_vacuum_scale_factor = 0.01,
autovacuum_vacuum_threshold = 100000,
autovacuum_analyze_scale_factor = 0.01,
autovacuum_vacuum_cost_limit = 4000
);Throttling and cost-based delay
In plain words: Vacuum deliberately sleeps so it does not hog the disk; on a big table the sleep dominates the runtime.
Common misunderstanding: "A slow autovacuum means the server is overloaded." Often it is just throttled: "When the accumulated cost reaches a limit (specified by vacuum_cost_limit), the process performing the operation will sleep for a short period of time, as specified by vacuum_cost_delay". Manual VACUUM defaults to no delay; autovacuum defaults to 2 ms.
Definition: Every page hit, miss or dirtied adds cost; at vacuum_cost_limit (200) the worker sleeps cost_delay. The limit is divided among running autovacuum workers. Raise it for big tables on SSD.
| Symptom | Cause | Action |
|---|---|---|
| Autovacuum runs for days | Cost throttling plus index passes | Raise autovacuum_vacuum_cost_limit for that table, more maintenance_work_mem |
| Vacuum starts again immediately | Threshold too low or too slow to finish | Check n_dead_tup, last_autovacuum |
| Many index scans per vacuum | Dead-item memory too small | Raise maintenance_work_mem |
| I/O saturated by vacuum | Limit too high | Lower, or schedule a manual VACUUM in a quiet window |
Freezing, wraparound and the failsafe Must-know
In plain words: Transaction ids are 32-bit and wrap around; old rows must be marked "frozen" before that, and a huge table needs a long vacuum to do it.
Common misunderstanding: "An insert-only table never needs vacuum." It does: freezing is the reason. The docs: "autovacuum is invoked on any table that might contain unfrozen rows with XIDs older than the age specified by the configuration parameter autovacuum_freeze_max_age" (default 200 million), "even if autovacuum is disabled". Full explanation: MVCC, VACUUM & Bloat.
Definition: An anti-wraparound vacuum scans (aggressively) pages not yet all-frozen. On a 5 TB table that is hours of I/O at the worst moment. Remedies: freeze at load time (COPY ... FREEZE into a new or truncated table, "intended as a performance option for initial data loading"), lower vacuum_freeze_min_age, run VACUUM (FREEZE) in a quiet window, or partition so old partitions are frozen once and left. As a last resort the failsafe (vacuum_failsafe_age) makes vacuum skip cost delays and index vacuuming.
1 table receives inserts only; the system consumes ~100M transaction ids per day (XIDs are used per transaction, not per row)
2 after ~2 days the table's age passes autovacuum_freeze_max_age (200M)
3 anti-wraparound autovacuum starts, cannot be cancelled by DDL locks easily
4 reads every unfrozen page (hours); cost delay applies
5 if age still grows -> failsafe at vacuum_failsafe_age: no cost delay, skip index vacuuming| Tool | Use | Watch |
|---|---|---|
age(relfrozenxid) per table | Distance to wraparound | SELECT relname, age(relfrozenxid) FROM pg_class ORDER BY 2 DESC LIMIT 10 |
pg_stat_progress_vacuum | Phases and heap blocks scanned | heap_blks_scanned / heap_blks_total |
COPY ... FREEZE | Frozen at load | Not allowed on partitioned or foreign tables |
vacuum_freeze_table_age, autovacuum_freeze_max_age | When aggressive vacuums happen | Keep a gap |
VACUUM (FREEZE, PARALLEL n) | Manual catch-up | Parallel applies to index vacuuming |
| MySQL | n/a (no xid wraparound; purge of undo log instead) | History list length |
Deleting, dropping and archiving
DELETE in batches versus DROP PARTITION Must-know
In plain words: Deleting a month of rows one by one rewrites history; dropping the month's partition just removes a file.
Common misunderstanding: "DELETE ... WHERE created_at < X followed by VACUUM is the standard way." It is the way that costs the most: all rows go to WAL, replicas replay them, dead tuples need vacuum, and indexes are left bloated.
Definition: PostgreSQL's partitioning chapter: "Bulk loads and deletes can be accomplished by adding or removing partitions... Dropping an individual partition using DROP TABLE, or doing ALTER TABLE DETACH PARTITION, is far faster than a bulk operation. These commands also entirely avoid the VACUUM overhead caused by a bulk DELETE." DETACH PARTITION CONCURRENTLY uses a reduced lock (SHARE UPDATE EXCLUSIVE) in two transactions; FINALIZE completes an interrupted detach. Partitioning design is in Partitioning & Sharding in PostgreSQL.
"Dropping an individual partition using DROP TABLE, or doing ALTER TABLE DETACH PARTITION, is far faster than a bulk operation. These commands also entirely avoid the VACUUM overhead caused by a bulk DELETE." — PostgreSQL documentation, Table Partitioning
1 events_2026_01 .. events_2026_12 are partitions of events (RANGE on created_at)
2 retention policy: keep 12 months
3 ALTER TABLE events DETACH PARTITION events_2025_11 CONCURRENTLY;
4 archive events_2025_11 (pg_dump, COPY to Parquet/S3, or move to a cheaper tablespace)
5 DROP TABLE events_2025_11; -- instant, no dead tuples, no vacuum| Method | Speed | WAL | Dead tuples | Locks |
|---|---|---|---|---|
DELETE one statement | Slow | Every row | Yes | Row locks for the duration |
DELETE in key-range batches | Slow but throttled | Every row | Yes (vacuum needed) | Short row locks |
DROP TABLE partition | Instant | Tiny (catalog) | None | ACCESS EXCLUSIVE on the partition (and brief on parent) |
DETACH PARTITION CONCURRENTLY | Instant | Tiny | None | SHARE UPDATE EXCLUSIVE then waits |
TRUNCATE | Instant | Minimal | None | ACCESS EXCLUSIVE; not MVCC-safe |
MySQL ALTER TABLE ... DROP PARTITION | Instant | Small | None | Metadata lock |
TRUNCATE
In plain words: TRUNCATE empties a table by replacing its files, not by deleting row by row.
Common misunderstanding: "TRUNCATE is DELETE without a WHERE, so it is the same inside a transaction." It takes ACCESS EXCLUSIVE, blocking all other access, and the manual warns "TRUNCATE is not MVCC-safe. After truncation, the table will appear empty to concurrent transactions, if they are using a snapshot taken before the truncation occurred."
Definition: Fast, minimal WAL, resets storage immediately, resets sequences only with RESTART IDENTITY. TRUNCATE (or CREATE TABLE) in the same transaction as the COPY is what makes the COPY ... FREEZE and wal_level = minimal shortcuts available.
| Aspect | DELETE | TRUNCATE | DROP PARTITION |
|---|---|---|---|
| Row triggers | Fire | Do not fire | Not applicable |
| Foreign keys | Checked | Needs CASCADE or no referencing tables | Same as drop |
| Transaction-safe | Yes | Yes (rolls back) but not MVCC-safe for old snapshots | Yes |
| Space returned | After vacuum rewrite | Immediately | Immediately |
Batched DELETE when partitioning is not available
In plain words: If you cannot drop a partition, delete in slices exactly like a backfill.
Common misunderstanding: "DELETE ... LIMIT works in PostgreSQL." It does not exist; use a CTE with ctid or a key range. MySQL does support DELETE ... LIMIT.
Definition: Delete in key-order slices with lock_timeout, sleep between slices, and run VACUUM (or let autovacuum) and monitor bloat. For MySQL use DELETE ... LIMIT n in a loop, or pt-archiver.
-- PostgreSQL
DELETE FROM events WHERE id IN (
SELECT id FROM events WHERE created_at < now() - interval '400 days' ORDER BY id LIMIT 10000
);
-- MySQL
DELETE FROM events WHERE created_at < NOW() - INTERVAL 400 DAY ORDER BY id LIMIT 10000;Archiving, cold storage and tiering
In plain words: Old data is still data, but it does not need to live on the fastest disk or in the database.
Common misunderstanding: "Archive means backup." A backup is for recovery of the live system; an archive is a queryable, cheaper, read-mostly copy of old data with its own retention.
Definition: Options: move partitions to a slower TABLESPACE; export detached partitions to Parquet/CSV in object storage and query with a foreign data wrapper or an engine such as DuckDB/ClickHouse; use a tiering extension (TimescaleDB compression and tiered storage, Citus columnar); or keep a rollup table and drop raw rows.
| Tier | Storage | Latency | Cost | Typical content |
|---|---|---|---|---|
| Hot | Primary heap, NVMe | ms | Highest | Last 30-90 days |
| Warm | Replica or slower tablespace | tens of ms | Medium | 1-2 years |
| Cold | Object storage, Parquet | seconds | Lowest | History, audits |
| Rollup | Aggregated table | ms | Small | Counts and sums per hour/day |
Replication lag and read offload
Bulk operations and replication lag Important
In plain words: Replicas replay what the primary logged. A load or backfill that writes a lot of WAL makes replicas fall behind, and anything reading from them sees old data.
Common misunderstanding: "Lag is a network problem." In bulk work it is replay speed: a single replay process applies WAL in order, so one fast writer can outrun it. Throttle the writer, not the network.
Definition: Watch pg_stat_replication (write_lag, flush_lag, replay_lag) and pg_wal_lsn_diff. Replication slots retain WAL until the consumer catches up, which can fill the primary's disk. Standby query conflicts (max_standby_streaming_delay, hot_standby_feedback) trade lag against cancelled queries. See Replication & Failover.
1 backfill writes 200 MB/s WAL; replica replays 120 MB/s
2 lag grows 80 MB/s -> after 10 minutes, 48 GB behind
3 app reads from replica -> read-your-writes breaks, dashboards stale
4 slot retains 48 GB of WAL on the primary
5 fix: slice the backfill, sleep while replay_lag > 5s, or pause at a lag threshold| Engine | Where to look | Throttle by |
|---|---|---|
| PostgreSQL streaming | pg_stat_replication.replay_lag | Backfill sleeps |
| PostgreSQL logical | pg_replication_slots confirmed_flush_lsn | Reduce write volume |
| MySQL | Seconds_Behind_Source, replication lag in performance schema | Smaller transactions; one big transaction is replayed as one |
| Cloud (RDS/Aurora) | CloudWatch ReplicaLag | Same |
Read replicas for analytics and columnar offload
In plain words: Do not run analytics on the primary. Send them to a replica, and if scans are still too heavy, copy the data into a column store.
Common misunderstanding: "A replica is a free place for heavy queries." Long queries on a hot standby conflict with WAL replay; they get cancelled or make the standby lag (or, with feedback, bloat the primary).
Definition: Use a dedicated analytics replica with tuned conflict settings, or a CDC pipeline to a columnar engine (ClickHouse, BigQuery, Snowflake, DuckDB/Parquet). Which store fits which workload is in OLTP vs OLAP & Columnar Storage; the scale decisions are in Storage & Data Scaling.
| Option | Isolation from OLTP | Freshness | Effort |
|---|---|---|---|
| Read replica (same engine) | Good (separate server) | Seconds | Low |
| Dedicated reporting replica | Better; relaxed standby settings | Minutes | Low |
| Logical replication to another PostgreSQL | Full | Seconds | Medium |
| CDC to columnar store | Full | Seconds-minutes | High |
| Nightly export to Parquet | Full | A day | Low |
Monitoring long operations
Progress views and pg_stat_io Must-know
In plain words: PostgreSQL tells you how far a long command has got. Use that to estimate the remaining time instead of guessing.
Common misunderstanding: "I can only see that it is running." For VACUUM, CREATE INDEX/REINDEX, ANALYZE, COPY, CLUSTER and base backups there are pg_stat_progress_* views.
Definition: "Whenever VACUUM is running, the pg_stat_progress_vacuum view will contain one row for each backend (including autovacuum worker processes) that is currently vacuuming." Likewise pg_stat_progress_create_index (also for REINDEX), pg_stat_progress_analyze, pg_stat_progress_copy. pg_stat_io shows "cluster-wide I/O statistics" per backend type, object and context (reads, writes, extends, hits), useful for seeing who consumes the I/O during a load.
1 start CREATE INDEX CONCURRENTLY in session A
2 session B: SELECT phase, blocks_done, blocks_total FROM pg_stat_progress_create_index;
3 phase = "building index: scanning table" -> blocks_done/blocks_total = 41%
4 phase = "waiting for old snapshots" -> an old transaction is blocking: find it in pg_stat_activity
5 estimate: elapsed / fraction_done - elapsed = remaining| View | Key columns | Reading |
|---|---|---|
pg_stat_progress_vacuum | phase, heap_blks_total, heap_blks_scanned, heap_blks_vacuumed, index_vacuum_count | A high index_vacuum_count means dead-item memory is too small |
pg_stat_progress_create_index | phase, blocks_done/blocks_total, tuples_done/tuples_total | Phase names show scan, sort, load, wait |
pg_stat_progress_copy | bytes_processed, tuples_processed | Throughput of a COPY |
pg_stat_progress_analyze | sample_blks_scanned | Time to finish ANALYZE |
pg_stat_io | reads, writes, extends, hits by backend_type and context | Is vacuum or a bulk write hogging I/O? |
pg_stat_activity | wait_event, state, xact_start | Long transactions that hold back vacuum and index builds |
pg_stat_user_tables | n_dead_tup, last_autovacuum, n_mod_since_analyze | Is autovacuum keeping up? |
SELECT p.relid::regclass, p.phase, round(100.0*p.heap_blks_scanned/NULLIF(p.heap_blks_total,0),1) AS pct
FROM pg_stat_progress_vacuum p;
SELECT phase, blocks_done, blocks_total FROM pg_stat_progress_create_index;
SELECT backend_type, context, reads, writes, extends FROM pg_stat_io WHERE writes > 0 ORDER BY writes DESC LIMIT 10;MySQL and InnoDB at scale
InnoDB large-table essentials Important
In plain words: InnoDB keeps the table as a clustered B+tree on the primary key, so primary-key choice, buffer pool size and online DDL behaviour matter more than any single knob.
Common misunderstanding: "More RAM on the buffer pool is optional tuning." The manual: "A larger buffer pool requires less disk I/O to access the same table data more than once. On a dedicated database server, you might set the buffer pool size to 80% of the machine's physical memory size."
Definition: Size innodb_buffer_pool_size to hold the hot working set (resize happens online in chunks of innodb_buffer_pool_chunk_size times instances). Insert in primary-key order; use AUTO_INCREMENT or time-ordered ids to avoid random clustered-index inserts (see ID Generation at Scale).
| Topic | MySQL InnoDB | Note |
|---|---|---|
| Buffer pool | innodb_buffer_pool_size ~ 50-80% of RAM on a dedicated server | Dump/load for warm restarts |
| Bulk load | LOAD DATA, autocommit=0, unique_checks=0, foreign_key_checks=0 | Verify data first |
Large DELETE | Batches with LIMIT; pt-archiver | Purge lag if big |
| Table rebuild | OPTIMIZE TABLE / ALTER TABLE ... ENGINE=InnoDB | Online but needs temp space |
| Partition drop | ALTER TABLE ... DROP PARTITION | Instant |
Online DDL, gh-ost, pt-online-schema-change and innodb_online_alter_log_max_size
In plain words: InnoDB can change many table definitions while writes continue, logging concurrent changes to a side log; for the cases it cannot, external tools copy the table in the background.
Common misunderstanding: "Online DDL means no cost." Concurrent changes accumulate in a temporary log; the manual: if concurrent DML exceeds innodb_online_alter_log_max_size, "the online DDL operation fails with a DB_ONLINE_LOG_TOO_BIG error, and uncommitted concurrent DML operations are rolled back". A larger value "permits more DML during an online DDL operation, but it also extends the period of time at the end of the DDL operation when the table is locked to apply logged DML."
Definition: For tables where in-place DDL is not enough or too risky, use gh-ost (binlog-based, triggerless) or pt-online-schema-change (trigger-based) to build a shadow table and swap; both are covered in Zero-Downtime Schema Migrations.
| Tool | Mechanism | Throttling | Caveat |
|---|---|---|---|
| InnoDB online DDL | In-place with a row log | innodb_online_alter_log_max_size | Log overflow aborts |
pt-online-schema-change | Triggers copy changes | --max-lag, --chunk-time | Triggers add load, not usable with some triggers |
| gh-ost | Reads binlog, no triggers | Dynamic throttle, replica lag aware | Needs row-based binlog |
PostgreSQL pg_repack | Trigger plus table copy | Cooperative locks | Needs extra space |
Large transactions and the history list
In plain words: InnoDB keeps old versions in undo logs; a long transaction stops the purge from cleaning them and the "history list length" grows.
Common misunderstanding: "Large transactions just take longer." They hold undo history, make rollback slow (rollback re-applies the undo), and a replica must replay them as one unit.
Definition: The history list is "a list of undo log pages" awaiting purge; watch Trx history list length in SHOW ENGINE INNODB STATUS. The remedy is the same as in PostgreSQL: slice big changes into short transactions. Details of InnoDB undo versus PostgreSQL vacuum are in MVCC, VACUUM & Bloat.
| PostgreSQL | InnoDB |
|---|---|
Dead tuples wait for VACUUM | Undo pages wait for purge |
| Old snapshot pins xmin horizon | Old read view lengthens history list |
| Autovacuum thresholds | innodb_purge_threads, purge lag |
| Table bloat | Undo tablespace growth |
Mechanics
What happens underneath, with the knobs and error codes you will actually see.
Where the time and the WAL go
1 statement modifies a row -> new tuple in a heap page (shared buffers), page marked dirty
2 WAL record written (tuple image; full-page image on the first change after a checkpoint)
3 commit -> WAL flushed (fsync) unless synchronous_commit=off or the table is UNLOGGED
4 checkpointer later writes dirty pages; max_wal_size / checkpoint_timeout decide how often
5 WAL sender ships records to standbys; standby replays them in order, single-threaded| Phase | Knob | Large-table effect |
|---|---|---|
| Heap write | fillfactor (table storage parameter) | Lower fillfactor leaves room for HOT updates, but makes the table larger |
| WAL volume | wal_compression, full_page_writes | Compression shrinks full-page images; never turn full_page_writes off without understanding the risk |
| Checkpoints | max_wal_size, checkpoint_timeout | Raise for loads; frequent checkpoints = more full-page images |
| Flush | synchronous_commit | off per session for loads you can redo |
| Replication | max_wal_senders, slots | Retained WAL fills disk if a standby is stuck |
| Replay | one startup process | Replay speed bounds how fast you may write |
HOT updates, fillfactor and index maintenance in a backfill
An update that changes no indexed column and fits on the same page can be a heap-only tuple (HOT): no new index entries. A backfill that sets a new, unindexed column on a table with fillfactor = 100 fills the page, so most updates cannot be HOT and every index gets a new entry for every row. Two remedies: do the backfill before creating the index on the new column, and for tables that will be updated heavily later, set fillfactor below 100 for new data. Layout details are in Database Internals.
Parallel query and parallel utility commands
max_parallel_workers_per_gather sets workers for a scan (the planner only uses them above min_parallel_table_scan_size), while parallel utility commands are governed by max_parallel_maintenance_workers and the memory rule in the manual: "Parallel utility commands treat the resource limit maintenance_work_mem as a limit to be applied to the entire utility command, regardless of the number of parallel worker processes." Parallel COUNT(*) or aggregate scans over a billion rows turn minutes into tens of seconds only if the storage has the bandwidth.
Error codes and messages you will meet
| Code / message | Engine | Meaning | Action |
|---|---|---|---|
53100 disk_full | PostgreSQL | WAL or temp files filled the disk | Throttle or free space; check slots |
55P03 lock_not_available | PostgreSQL | lock_timeout hit | Retry the slice later |
57014 query_canceled | PostgreSQL | statement_timeout or user cancel | Reduce slice size |
40001 serialization_failure | PostgreSQL | Concurrent update at higher isolation | Retry the slice |
ERROR: out of memory on huge COPY with FKs | PostgreSQL | Pending trigger events exhausted memory | Drop FKs, reload, re-add |
could not resize shared memory segment | PostgreSQL | Parallel query shm exhausted | Lower parallelism |
1206 (ER_LOCK_TABLE_FULL) | MySQL | Too many row locks in one transaction | Smaller batches |
1205 (ER_LOCK_WAIT_TIMEOUT) | MySQL | innodb_lock_wait_timeout | Retry |
DB_ONLINE_LOG_TOO_BIG | MySQL | Online DDL log exceeded innodb_online_alter_log_max_size | Raise or run during quiet time |
1114 (ER_RECORD_FILE_FULL) | MySQL | Disk full | Free space |
Solving the classic problems
| Problem | Solution | How | Advantage | Cost / limitation |
|---|---|---|---|---|
| Load 500M rows fast | Parallel COPY by id slice | One connection per worker, binary CopyFrom | Near disk speed | Needs bare table and a sorted source |
| Add and fill a column | Add nullable, key-range backfill, then NOT NULL via NOT VALID + VALIDATE | UPDATE ... WHERE id BETWEEN with sleep | No long lock | Takes long wall time |
| Keep indexes small | BRIN or partial index | USING brin, WHERE status <> 'done' | 100-1000x smaller | Requires correlation / predicate match |
| Retention | Range partitions + DETACH + DROP | Scheduled job (pg_partman or cron) | Instant, no vacuum | Partition key must match filters |
| Dashboard count | reltuples estimate or counter | pg_class or rollup table | Instant | Approximate or write contention |
| Autovacuum never finishes | Per-table settings, bigger memory | ALTER TABLE SET (autovacuum_*) | Predictable cadence | Needs I/O headroom |
| Analytics hurting OLTP | Replica / columnar store | Streaming replica, CDC to ClickHouse | Isolation | Staleness, extra system |
Go: parallel COPY loader with pgx
Setup in a fresh module (go.mod pins go 1.24; pgx/v5 v5.7.2):
go get github.com/jackc/pgx/v5@v5.7.2
go mod tidy
gofmt -l . && go vet ./...The loader divides the id range between workers, gives each its own connection, streams rows with CopyFrom (a CopyFromSource), and wraps each slice in a transaction so a failed slice is retryable.
// Parallel COPY loader: split an id range into slices, give every worker its
// own connection, and stream rows with the binary COPY protocol.
// It compiles without a database; run it with PG_DSN set to actually load.
package main
import (
"context"
"fmt"
"log"
"os"
"sync"
"time"
"github.com/jackc/pgx/v5"
)
const (
workers = 4
totalRows = 4_000_000
)
var columns = []string{"id", "account_id", "created_at", "amount_cents", "payload"}
// rowSource implements pgx.CopyFromSource for the half-open id range [from, to).
type rowSource struct {
next, to int64
base time.Time
row []any
}
func newRowSource(from, to int64, base time.Time) *rowSource {
return &rowSource{next: from, to: to, base: base, row: make([]any, len(columns))}
}
func (s *rowSource) Next() bool { return s.next < s.to }
func (s *rowSource) Values() ([]any, error) {
id := s.next
s.next++
s.row[0] = id
s.row[1] = id % 100_000
s.row[2] = s.base.Add(time.Duration(id) * time.Second)
s.row[3] = (id * 37) % 100_000
s.row[4] = fmt.Sprintf("event-%d", id)
return s.row, nil
}
func (s *rowSource) Err() error { return nil }
func loadSlice(ctx context.Context, dsn string, from, to int64, base time.Time) (int64, error) {
// One connection per worker: COPY occupies the connection for its whole duration.
conn, err := pgx.Connect(ctx, dsn)
if err != nil {
return 0, err
}
defer conn.Close(ctx)
// One transaction per slice keeps a failed slice retryable on its own.
tx, err := conn.Begin(ctx)
if err != nil {
return 0, err
}
defer tx.Rollback(ctx) //nolint:errcheck // rollback after commit is a no-op
n, err := tx.CopyFrom(ctx, pgx.Identifier{"events"}, columns, newRowSource(from, to, base))
if err != nil {
return 0, err
}
return n, tx.Commit(ctx)
}
func main() {
dsn := os.Getenv("PG_DSN")
if dsn == "" {
fmt.Println("set PG_DSN to run, e.g. postgres://postgres:pg@localhost:5432/lab")
return
}
ctx := context.Background()
base := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC)
slice := int64(totalRows / workers)
start := time.Now()
var (
wg sync.WaitGroup
mu sync.Mutex
total int64
)
for w := range workers {
from := int64(w) * slice
wg.Add(1)
go func() {
defer wg.Done()
n, err := loadSlice(ctx, dsn, from, from+slice, base)
if err != nil {
log.Printf("slice %d-%d failed: %v", from, from+slice, err)
return
}
mu.Lock()
total += n
mu.Unlock()
}()
}
wg.Wait()
fmt.Printf("loaded %d rows with %d workers in %s\n", total, workers, time.Since(start).Round(time.Millisecond))
}Go: batched backfill by key range
// Batched backfill by key range: one short transaction per slice of the
// primary key, no OFFSET, a pause between slices so autovacuum, replicas and
// other sessions keep up. Safe to stop and restart: it resumes from MIN(id).
package main
import (
"context"
"fmt"
"log"
"os"
"os/signal"
"time"
"github.com/jackc/pgx/v5"
)
const (
batchSize = 10_000
pause = 200 * time.Millisecond
)
// The "region IS NULL" predicate makes every slice idempotent and lets the
// job resume after a crash without a separate cursor table.
const updateSlice = `
UPDATE events
SET region = CASE WHEN account_id % 2 = 0 THEN 'eu' ELSE 'us' END
WHERE id >= $1 AND id < $2
AND region IS NULL`
func run(ctx context.Context, conn *pgx.Conn) error {
var lo, hi int64
err := conn.QueryRow(ctx, `SELECT COALESCE(MIN(id), 0), COALESCE(MAX(id), 0) FROM events WHERE region IS NULL`).Scan(&lo, &hi)
if err != nil {
return err
}
var updated int64
for from := lo; from <= hi; from += batchSize {
if err := ctx.Err(); err != nil {
return err
}
// Every slice is its own transaction: row locks last milliseconds
// and WAL is produced in small, steady amounts.
tag, err := conn.Exec(ctx, updateSlice, from, from+batchSize)
if err != nil {
return fmt.Errorf("slice %d: %w", from, err)
}
updated += tag.RowsAffected()
if (from-lo)/batchSize%100 == 0 {
log.Printf("progress id=%d/%d updated=%d", from, hi, updated)
}
select {
case <-ctx.Done():
return ctx.Err()
case <-time.After(pause):
}
}
log.Printf("done, updated %d rows", updated)
return nil
}
func main() {
dsn := os.Getenv("PG_DSN")
if dsn == "" {
fmt.Println("set PG_DSN to run, e.g. postgres://postgres:pg@localhost:5432/lab")
return
}
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
defer stop()
conn, err := pgx.Connect(ctx, dsn)
if err != nil {
log.Fatal(err)
}
defer conn.Close(context.Background())
if err := run(ctx, conn); err != nil {
log.Fatal(err)
}
}Laravel: chunkById backfill job
Laravel's documentation says "If you plan to update the retrieved records while chunking, it is always best to use the chunkById method instead", which "will automatically paginate the results based on the record's primary key". The job below updates one slice per statement and sleeps between slices.
<?php
// app/Jobs/BackfillEventRegion.php
namespace App\Jobs;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Queue\Attributes\Timeout;
use Illuminate\Queue\Attributes\Tries;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
// Each run is bounded (SLICES_PER_RUN slices) so it finishes well inside the
// worker timeout; the job then re-dispatches itself from the last id it saw.
#[Tries(3)]
#[Timeout(120)]
final class BackfillEventRegion implements ShouldQueue
{
use Queueable;
// Rows per slice: small enough that each UPDATE commits in milliseconds.
private const SLICE = 5_000;
private const SLICES_PER_RUN = 200;
public function __construct(public int $afterId = 0) {}
public function handle(): void
{
$lastId = $this->afterId;
$slices = 0;
// chunkById pages on "id > last_seen_id ORDER BY id LIMIT n":
// no OFFSET, so slice 40,000 costs the same as slice 1.
DB::table('events')
->where('id', '>', $this->afterId)
->whereNull('region')
->chunkById(self::SLICE, function (Collection $rows) use (&$lastId, &$slices) {
$ids = $rows->pluck('id');
// One short statement (and transaction) per slice. The
// IS NULL predicate keeps a retried slice idempotent.
DB::table('events')
->whereIn('id', $ids)
->whereNull('region')
->update(['region' => DB::raw("CASE WHEN account_id % 2 = 0 THEN 'eu' ELSE 'us' END")]);
$lastId = (int) $ids->last();
// Give autovacuum, replicas and other sessions room to breathe.
usleep(200_000);
// Returning false stops chunkById after this slice.
return ++$slices < self::SLICES_PER_RUN;
});
// Stopped because the budget ran out, not because rows ran out:
// continue from the last id instead of holding one worker for hours.
if ($slices >= self::SLICES_PER_RUN) {
self::dispatch($lastId)->delay(now()->addSeconds(5));
}
}
}Laravel: COPY and LOAD DATA
DB::unprepared() runs a raw SQL string without bindings, which is fine for LOAD DATA LOCAL INFILE on MySQL (the connection needs PDO::MYSQL_ATTR_LOCAL_INFILE in its options and the server needs local_infile on). PostgreSQL's COPY ... FROM STDIN is a protocol-level operation that cannot be issued as a plain statement through PDO, so use the driver's pgsqlCopyFromFile / pgsqlCopyFromArray on the underlying PDO, or a server-side COPY FROM '/path' (needs pg_read_server_files).
<?php
// app/Console/Commands/BulkLoadEvents.php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
final class BulkLoadEvents extends Command
{
protected $signature = 'events:bulk-load {file} {--driver=pgsql}';
protected $description = 'Load a delimited file with COPY (PostgreSQL) or LOAD DATA (MySQL)';
public function handle(): int
{
$file = (string) $this->argument('file');
if ($this->option('driver') === 'pgsql') {
// COPY ... FROM STDIN cannot be sent through DB::unprepared() as a
// normal statement; the PDO PostgreSQL driver has a dedicated call.
// (PHP 8.4 also exposes it as Pdo\Pgsql::copyFromFile.)
$pdo = DB::connection('pgsql')->getPdo();
$ok = $pdo->pgsqlCopyFromFile(
'events',
$file,
"\t",
'\\N',
'id,account_id,created_at,amount_cents,payload',
);
return $ok ? self::SUCCESS : self::FAILURE;
}
// MySQL: LOAD DATA LOCAL needs local_infile=1 on the server AND
// PDO::MYSQL_ATTR_LOCAL_INFILE => true in config/database.php options.
DB::connection('mysql')->unprepared(
"LOAD DATA LOCAL INFILE '".addslashes($file)."'
INTO TABLE events
FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n'
(id, account_id, created_at, amount_cents, payload)"
);
return self::SUCCESS;
}
}Retry and failure handling
| Error | Meaning | Retry? |
|---|---|---|
55P03 lock timeout | A slice waited too long for a row lock | Yes, with backoff; the slice is idempotent |
40001 / 40P01 | Serialization failure / deadlock | Yes, retry the slice |
Connection reset during COPY | Slice transaction rolled back | Yes, re-run that slice (transaction was atomic) |
53100 disk full | Capacity | No: stop, free space, then resume |
Constraint violation in COPY | Bad data in the stream | No: fix data; whole COPY is atomic |
Rules: make every slice idempotent (WHERE new_col IS NULL), persist the last finished key if the job can be restarted from another machine, never retry a failed COPY blindly into a table that now has partial data (it rolled back, but a second loader may have raced).
The same job in other engines
| Product | Bulk load | Retention and notes |
|---|---|---|
| PostgreSQL | COPY, pg_restore -j | Partition drop, UNLOGGED, BRIN |
| MySQL InnoDB | LOAD DATA, multi-row INSERT, pt-archiver | Partition drop, gh-ost for DDL |
| SQL Server | BULK INSERT, bcp, INSERT ... SELECT with minimal logging in bulk-logged/simple recovery | Partition switching (SWITCH PARTITION) and sliding window |
| Oracle | Direct-path INSERT /*+ APPEND */, SQL*Loader, external tables | EXCHANGE PARTITION, DROP PARTITION |
| SQLite | One big transaction, PRAGMA journal_mode=WAL, .import | Whole-file size limit; not for billions of rows on one writer |
| MongoDB | insertMany unordered, bulkWrite, mongoimport | TTL index for expiry; sharding for scale |
| CockroachDB | IMPORT/COPY, batch inserts of a few thousand rows | Row-level TTL, range splits |
| Redis | redis-cli --pipe, pipelining | Eviction/expiry; not a table store at this size |
Choosing a technique
| Situation | Recommended | Extra technique | Reason |
|---|---|---|---|
| One-time initial load into an empty table | COPY into bare table, then indexes | wal_level=minimal, COPY FREEZE, big maintenance_work_mem | Fewest writes, tight indexes |
| Recurring bulk load into a live table | COPY into staging table, then INSERT ... SELECT or partition attach | Keep indexes, batch by partition | Keeps production indexes valid |
| Append-only time series | Range partition + BRIN | autovacuum_vacuum_insert_*, freeze early | Cheap index, instant retention |
| Fill a new column on all rows | Key-range backfill | Add index after, lock_timeout | No lock or WAL storm |
| Skewed multi-tenant data | Higher statistics target, partial indexes | Partition by tenant hash | Planner sees skew |
| Need exact count often | Counter table | Estimate for UI | count(*) is a scan |
| Remove old rows | DETACH/DROP PARTITION | Archive first | No vacuum |
| Autovacuum lags on a giant table | Per-table thresholds | Raise cost limit and memory | Predictable cadence |
| Analytics on huge history | Replica or columnar offload | Rollups | Isolate OLTP |
| MySQL schema change on 1B rows | gh-ost / pt-online-schema-change | Throttle on replica lag | Online DDL log limits |
In architecture: from a single process to a distributed system
Monolith (one process, one database)
One PostgreSQL primary, an application and a nightly job. The table is events with 200 million rows. Apply the minimum: pg_total_relation_size reviews each quarter, a BRIN index on created_at, per-table autovacuum thresholds, monthly range partitions created ahead of time, and a retention job that detaches the oldest partition. Backfills run as a queued job doing chunkById slices with sleeps. No new infrastructure.
Modular monolith and multiple databases
The module that owns the big table (billing events) owns its partitions, retention and backfills; other modules read through views or an API, never run ad-hoc UPDATEs. A shared reporting database receives a replica or logical replication of the table so analytical modules never touch the primary. Schema changes go through a module-owned migration with a documented lock budget.
Microservices
The events service owns the table; other services send or consume events. A bulk correction is a service operation: the job runs in the events service, publishes a change event per batch (via the outbox, see Transactional Outbox), and downstream consumers (search index, cache, warehouse) apply it idempotently. Never let another service run UPDATE on the table. Backfills must be resumable and throttled by downstream lag as well as database lag, because consumers see the same burst.
Distributed data: replicas, caches, multi-region
Replica lag appears the moment a backfill starts; reads that need read-your-writes go to the primary or wait for an LSN. Caches in front of the table hold old values until invalidated: after a bulk update, expire by key range or version, not by FLUSHALL. In multi-region setups the cross-region link is the bottleneck: ship partitions as compressed files instead of replaying row WAL when you move history, and use CDC to feed a warehouse rather than querying the primary. See Replication & Failover and Storage & Data Scaling.
Scaling path: 1x, 10x, 100x
| Scale | Rows | What works | What stops working |
|---|---|---|---|
| 1x | up to ~100M | One table, normal indexes, defaults | Nothing yet |
| 10x | ~1B | Partitioning by time, BRIN/partial indexes, per-table autovacuum, batched backfills | count(*), whole-table UPDATE, DELETE retention |
| 100x | 10B+ / multi-TB | Sharding or distributed SQL, columnar offload, tiering, rollups | Single-primary maintenance windows |
Notion's engineers described the same wall: "Query performance and upkeep processes often begin to degrade well before a table reaches the maximum hardware-bound size; our stalling Postgres auto-vacuum was an example of this soft limitation." They set "an upper bound of 500 GB per table and 10 TB per physical database" and sharded across it; Figma wrote that "some of our tables, containing several terabytes and billions of rows, were becoming too large for a single database" and saw "reliability impact during Postgres vacuums". See Storage & Data Scaling for the ladder and Partitioning & Sharding in PostgreSQL for the hands-on side.
"Query performance and upkeep processes often begin to degrade well before a table reaches the maximum hardware-bound size; our stalling Postgres auto-vacuum was an example of this soft limitation." — Notion Engineering, Herding elephants: Lessons learned from sharding Postgres at Notion
"The data revealed that some of our tables, containing several terabytes and billions of rows, were becoming too large for a single database. At this size, we began to see reliability impact during Postgres vacuums, which are essential background operations that keep Postgres from running out of transaction IDs and breaking down." — Figma, How Figma's databases team lived to tell the scale
Lab
All steps use one PostgreSQL 17 container; MySQL is only needed for step 6. Timings depend entirely on hardware and settings, so the expected output describes relative shape ("several times faster"), not absolute numbers; treat every figure as indicative.
docker run -d --name pg -e POSTGRES_PASSWORD=pg -p 5432:5432 postgres:17 -c max_wal_size=8GB -c maintenance_work_mem=1GB
docker exec -it pg psql -U postgresSetup.
CREATE TABLE events_a (id bigint, account_id bigint, created_at timestamptz, amount_cents bigint, payload text);
CREATE TABLE events_b (LIKE events_a);
\timing onExperiment 1: load 50 million rows with and without indexes.
1 -- export the data once, so both loads read the same CSV
2 \copy (SELECT g, g % 100000, timestamptz '2026-01-01' + g * interval '1 second', (g*37) % 100000, 'event-' || g FROM generate_series(1,50000000) g) TO '/tmp/events.csv' CSV
3 -- A: indexes first, then COPY
4 ALTER TABLE events_a ADD PRIMARY KEY (id);
5 CREATE INDEX ON events_a (account_id, created_at);
6 \copy events_a FROM '/tmp/events.csv' CSV
7 -- B: bare table, COPY, then indexes
8 \copy events_b FROM '/tmp/events.csv' CSV
9 SET maintenance_work_mem = '2GB'; ALTER TABLE events_b ADD PRIMARY KEY (id); CREATE INDEX ON events_b (account_id, created_at); ANALYZE events_b;
10 -- expected: B (COPY + index builds) several times faster than A (COPY into indexed table); compare \timing and pg_total_relation_sizeExperiment 2: BRIN versus B-tree size.
1 CREATE INDEX events_ts_btree ON events_b (created_at);
2 CREATE INDEX events_ts_brin ON events_b USING brin (created_at) WITH (pages_per_range = 128);
3 SELECT relname, pg_size_pretty(pg_relation_size(oid)) FROM pg_class WHERE relname LIKE 'events_ts%';
4 -- expected: BRIN is roughly three orders of magnitude smaller (kilobytes-megabytes vs ~GB)
5 EXPLAIN (ANALYZE, BUFFERS) SELECT count(*) FROM events_b WHERE created_at BETWEEN '2026-01-01 10:00' AND '2026-01-01 11:00';
6 -- try with each index (DROP the other): BRIN reads more pages than a btree but far fewer than a full scanExperiment 3: single UPDATE versus batched UPDATE (lock duration).
Session A (backfill) Session B (app)
1 ALTER TABLE events_b ADD COLUMN region text;
2 BEGIN;
3 UPDATE events_b SET region = 'eu'; -- runs for a long time
4 UPDATE events_b SET amount_cents = 1 WHERE id = 1; -- waits until A commits
5 COMMIT; -- B finally proceeds
6 -- reset, then batched: each 100k slice in its own transaction
7 ALTER TABLE events_b DROP COLUMN region; ALTER TABLE events_b ADD COLUMN region text;
7a UPDATE events_b SET region = 'us' WHERE id >= 0 AND id < 100000 AND region IS NULL;
8 UPDATE events_b SET amount_cents = 1 WHERE id = 1; -- blocked only for the length of one slice
9 -- measure: pg_stat_activity wait_event_type = 'Lock' duration for B in each caseExperiment 4: watch progress while it runs.
1 Session A: CREATE INDEX CONCURRENTLY events_acct ON events_b (account_id);
2 Session B: SELECT phase, blocks_done, blocks_total FROM pg_stat_progress_create_index;
3 Session A: VACUUM (VERBOSE) events_b; Session B: SELECT * FROM pg_stat_progress_vacuum;
4 -- expected: phase changes from "building index: scanning table" through sort and loadExperiment 5: partition drop versus DELETE.
1 CREATE TABLE ev (id bigint, ts timestamptz) PARTITION BY RANGE (ts);
2 CREATE TABLE ev_2026_01 PARTITION OF ev FOR VALUES FROM ('2026-01-01') TO ('2026-02-01');
3 INSERT INTO ev SELECT g, '2026-01-01'::timestamptz + (g % 2000000) * interval '1 second' FROM generate_series(1,20000000) g;
4 \timing: DELETE FROM ev WHERE ts < '2026-02-01'; -- slow; note n_dead_tup in pg_stat_user_tables
5 INSERT again, then: ALTER TABLE ev DETACH PARTITION ev_2026_01; DROP TABLE ev_2026_01; -- instantExperiment 6 (MySQL): LOAD DATA versus multi-row INSERT. Start mysql:8.4, enable local_infile, and load the CSV once with LOAD DATA LOCAL INFILE and once with multi-row INSERT statements of 1,000 rows each in one transaction; expect LOAD DATA to be several times faster.
Common misconceptions
| Belief | Reality |
|---|---|
"count(*) is O(1)" | Under MVCC it is a scan; use reltuples or a counter |
"Batching INSERTs is as good as COPY" | PostgreSQL's manual says COPY is almost always faster even then; MySQL says LOAD DATA is usually ~20x faster than INSERT |
"UNLOGGED is safe and fast" | Crash truncates it and it is not replicated |
| "Autovacuum defaults protect huge tables" | Thresholds are proportional (20%), so they fire very late |
| "An insert-only table needs no vacuum" | It needs freezing to avoid wraparound |
"DELETE old rows then VACUUM is retention" | DROP PARTITION avoids the WAL and vacuum cost entirely |
| "BRIN works on any column" | Only on columns correlated with physical order |
"ANALYZE reads every row" | It samples; raise the target for skewed columns |
"TRUNCATE is DELETE without WHERE" | ACCESS EXCLUSIVE, not MVCC-safe, no row triggers |
| "Online DDL is free" | InnoDB's online log can overflow (DB_ONLINE_LOG_TOO_BIG); concurrent index builds hold back on old transactions |
| "A replica absorbs any load" | A bulk write makes it lag, and long queries on it get cancelled |
| "Bigger hardware fixes slow maintenance" | Upkeep degrades before hardware limits (Notion) |
Cheat sheet
| Topic | What to remember |
|---|---|
| Sizing | pg_total_relation_size, 24+4 bytes per row overhead, sample with TABLESAMPLE |
| Load | COPY bare table, then indexes, then constraints, then ANALYZE |
wal_level=minimal | Needs restart, no standbys/PITR; same-transaction TRUNCATE + COPY skips WAL |
UNLOGGED | Fast but truncated after a crash and not replicated |
| MySQL load | LOAD DATA, autocommit=0, unique_checks=0, foreign_key_checks=0, PK order |
| Statistics | default_statistics_target 100; per column SET STATISTICS; ANALYZE after load |
| Counting | pg_class.reltuples estimate; counter for exact |
| BRIN | pages_per_range 128; needs correlation; tiny index |
| Partial index | Index only the rows queried; predicate must imply |
| Backfill | Key-range slices, idempotent predicate, lock_timeout, sleep, resumable |
| Autovacuum | Per-table scale factor and threshold; raise vacuum_cost_limit; maintenance_work_mem |
| Freeze | Watch age(relfrozenxid); autovacuum_freeze_max_age 200M; COPY FREEZE at load |
| Retention | DETACH PARTITION CONCURRENTLY then DROP; never mass DELETE |
| Monitoring | pg_stat_progress_vacuum/create_index/copy, pg_stat_io, pg_stat_replication |
| InnoDB | Buffer pool ~80% on dedicated servers; watch history list length; gh-ost for DDL |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — Why is a billion-row UPDATE in one statement dangerous even though it is a single command? Must-know
Answer
Answer: It is one transaction: row locks are held until the end, WAL is written for every new tuple, dead old versions double the table, replicas must replay the whole burst, and the held snapshot blocks vacuum. Slice it by key range instead.
2 — What does COPY ... FREEZE need, and why is it useful? Good to know
Answer
Answer: The table must have been created or truncated in the same (sub)transaction, with no open cursors or older snapshots. Rows are written already frozen so a later anti-wraparound vacuum does not have to rewrite them. It cannot be used on partitioned or foreign tables.
3 — Give the autovacuum trigger formula and say why it is a problem on a large table. Important
Answer
Answer: threshold = min(max_threshold, base_threshold + scale_factor * tuples). With scale factor 0.2 a billion-row table would need 200 million dead tuples first; the default autovacuum_vacuum_max_threshold caps that at 100 million. Either way it is a very late start. Set per-table values.
4 — When is BRIN better than a B-tree, and when useless? Important
Answer
Answer: Better for huge append-only tables where the column correlates with physical order (timestamps): it is tiny and prunes page ranges. Useless on uncorrelated columns such as random UUIDs.
5 — Why is DROP PARTITION preferred over DELETE for retention? Must-know
Answer
Answer: It removes data by dropping files: no per-row WAL, no dead tuples, no vacuum. DETACH PARTITION CONCURRENTLY takes a lighter lock.
6 — How do you get a fast approximate row count in PostgreSQL, and what is its limit? Must-know
Answer
Answer: SELECT reltuples FROM pg_class; it is refreshed by VACUUM, ANALYZE and some DDL, so it can be stale. For exact counts keep a counter or accept a scan.
7 — What do maintenance_work_mem and max_parallel_maintenance_workers do for index builds? Important
Answer
Answer: The first is the memory for the whole build regardless of worker count; the second caps parallel workers (B-tree, GIN, BRIN). Workers need at least a 32MB share each plus 32MB for the leader.
8 — Why can a long-running transaction stall CREATE INDEX CONCURRENTLY? Important
Answer
Answer: The build must wait for transactions that have a snapshot older than each scan; an idle-in-transaction session can hold it in "waiting for old snapshots".
9 — What breaks if wal_level is set to minimal for a bulk load? Good to know
Answer
Answer: Streaming replication and WAL archiving cannot run, earlier base backups become unusable for PITR and standbys; you must take a new base backup afterwards.
10 — Which InnoDB setting bounds concurrent DML during online DDL, and what happens on overflow? Good to know
Answer
Answer: innodb_online_alter_log_max_size; when exceeded the DDL fails with DB_ONLINE_LOG_TOO_BIG and uncommitted concurrent DML is rolled back.
11 — How do you throttle a backfill by replica lag? Important
Answer
Answer: Between slices read pg_stat_replication.replay_lag (or MySQL replication delay) and sleep until it drops under a threshold.
Glossary
| Term | Meaning |
|---|---|
| Backfill | Filling a new column or table from existing data after a schema change |
| BRIN | Block Range Index: min/max summaries per group of adjacent pages |
pages_per_range | BRIN storage parameter, default 128 |
| Bulk load | Loading many rows at once, usually COPY/LOAD DATA |
COPY | PostgreSQL command that streams rows into or out of a table |
COPY ... FREEZE | Loads rows already frozen into a new/truncated table |
LOAD DATA | MySQL statement that loads rows from a text file |
UNLOGGED | Table that skips WAL; not crash-safe, not replicated |
wal_level | How much information is written to WAL (minimal, replica, logical) |
| TOAST | PostgreSQL's out-of-line storage for large values |
reltuples | pg_class estimate of the number of rows |
default_statistics_target | Default number of statistics entries per column (100) |
| ANALYZE | Samples a table to refresh planner statistics |
| Partial index | Index with a WHERE predicate |
| Partition pruning | Planner skipping partitions that cannot match |
DETACH PARTITION | Turns a partition into a standalone table |
| Autovacuum scale factor | Fraction of the table that must change before vacuum starts |
vacuum_cost_limit | Cost accumulated before vacuum sleeps (default 200) |
| Freeze | Marking old rows as visible to everyone to avoid xid wraparound |
| Anti-wraparound vacuum | Aggressive vacuum forced by autovacuum_freeze_max_age |
maintenance_work_mem | Memory for vacuum, index builds, FK adds (default 64MB) |
max_parallel_maintenance_workers | Cap on workers for parallel index builds and vacuum |
REINDEX CONCURRENTLY | Rebuilds an index without blocking writes |
pg_stat_progress_* | Views that report progress of long commands |
pg_stat_io | Cluster-wide I/O statistics by backend type and context |
| History list length | InnoDB count of undo pages awaiting purge |
innodb_buffer_pool_size | InnoDB cache size; ~80% of RAM on a dedicated server per the manual |
innodb_online_alter_log_max_size | Limit of the online DDL DML log |
| gh-ost | Triggerless online schema change tool for MySQL |
pt-online-schema-change | Percona's trigger-based online schema change |
| Cold storage / tiering | Moving old data to cheaper storage |
| Columnar offload | Copying data to a column store for analytics |
fillfactor | Table storage parameter: how full INSERT packs a page (default 100); lower leaves room for HOT updates |
lock_timeout | Session setting: give up with 55P03 instead of waiting for a lock |
max_wal_size | Soft limit of WAL between checkpoints; raise it during loads |
| CopyFrom | pgx method that streams rows with the COPY protocol |
chunkById | Laravel query-builder method that pages by primary key, safe while updating |
| HOT | Heap-only tuple: an update that needs no new index entries |
| TABLESAMPLE | SQL clause that reads a random sample of a table |
| batch INSERT | Several rows per INSERT ... VALUES statement or per transaction |
| key range | A slice id >= a AND id < b of the primary key used to walk a table in batches |
vacuum_failsafe_age | Table age at which vacuum drops cost delay and index vacuuming to avoid wraparound |
autovacuum_vacuum_max_threshold | Cap on dead tuples that trigger autovacuum (default 100,000,000) |
unique_checks | MySQL session variable; 0 skips uniqueness checks for secondary indexes during a load |
foreign_key_checks | MySQL session variable; 0 skips foreign key checks during a load |
innodb_autoinc_lock_mode | InnoDB auto-increment locking mode; 2 (interleaved) is best for bulk inserts |
bulk_insert_buffer_size | MySQL buffer for bulk inserts into a non-empty MyISAM table |
pg_stat_replication | View with write_lag, flush_lag, replay_lag per standby |
| replication lag | How far a replica is behind its primary |
| read replica | Replica used for read-only queries, including analytics |
| row width | Average bytes per row including header and padding |
pg_total_relation_size | Heap plus TOAST plus indexes, in bytes |
pgsqlCopyFromFile | PHP PDO method that runs COPY FROM for PostgreSQL |
| DROP PARTITION | Removes a partition (and its data) instantly; MySQL ALTER TABLE ... DROP PARTITION, PostgreSQL DROP TABLE |
enable_partition_pruning | Planner setting (default on) that allows pruning |
pg_stat_progress_copy | Progress view for running COPY commands |
pg_stat_progress_vacuum | Progress view for VACUUM and autovacuum |
pg_stat_progress_create_index | Progress view for CREATE INDEX and REINDEX |
References
- PostgreSQL documentation: Populating a Database, COPY, BRIN Indexes, TOAST, Resource Consumption, Write Ahead Log settings, Vacuuming settings, Routine Vacuuming, Table Partitioning, CREATE INDEX, REINDEX, CREATE TABLE, ALTER TABLE, TRUNCATE, ANALYZE, VACUUM, Statistics Used by the Planner, Partial Indexes, Progress Reporting, Cumulative Statistics (pg_stat_io), How Parallel Query Works, System Administration Functions
- PHP manual: PDO::pgsqlCopyFromFile (alias of
Pdo\Pgsql::copyFromFile()) - MySQL 8.4 Reference Manual: Optimizing INSERT Statements, LOAD DATA, Bulk Data Loading for InnoDB Tables, Online DDL Space Requirements, Configuring InnoDB Buffer Pool Size, Purge Configuration
- Engineering posts: Notion, Herding elephants: Lessons learned from sharding Postgres at Notion, Figma, How Figma's databases team lived to tell the scale
- Go: pgx v5 (
CopyFrom,CopyFromSource) - Laravel 13 documentation: Database: Query Builder (
chunkById,lazyById), Database: Getting Started (DB::unprepared)