Skip to content

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 forGo to
The one-page summary of what changes at a billion rowsEverything in one minute
Why "just run it" stops workingWhy big tables behave differently
How big will it be, and what does it cost?Estimating size and capacity
Fast initial or recurring loadsBulk loading
ANALYZE, default_statistics_target, estimated countsStatistics and counting
BRIN, partial indexes, parallel index buildsIndexes that stay affordable
Changing every row without a lock or WAL stormBatched backfills and updates
Autovacuum thresholds, freeze, wraparound riskVacuum on huge tables
Removing old dataDeleting, dropping and archiving
Replicas, analytics offload, columnarReplication lag and read offload
Progress views, pg_stat_ioMonitoring long operations
WAL flow, HOT updates, parallel query, error codesMechanics
InnoDB LOAD DATA, buffer pool, online DDL, history listMySQL and InnoDB at scale
Code in Go and LaravelSolving the classic problems
Which technique for which jobChoosing a technique
Monolith to shardedIn architecture
Reproduce with 50 million rowsLab

Everything in one minute ​

What breaks first as a table grows.

OperationAt a million rowsAt a billion rowsDo this instead
SELECT count(*)InstantMinutes of sequential I/OEstimate from pg_class.reltuples, or keep a counter
UPDATE t SET x = ... (all rows)SecondsHours, one transaction, huge WAL, bloat doubledBatched backfill by key range
CREATE INDEXSecondsHours, big temp sortParallel build, large maintenance_work_mem, CONCURRENTLY on live tables
DELETE old rowsSecondsWAL storm, dead tuples, long VACUUMDROP/DETACH PARTITION
AutovacuumRarely noticedFires late (20% of a billion would be 200 million dead tuples; the default cap is 100 million) or runs for daysPer-table thresholds, absolute limits
Row-by-row INSERTFineDaysCOPY, LOAD DATA
ALTER TABLE ... ADD COLUMN with rewriteSecondsTable rewrite, long lockOnline DDL, gh-ost, ADD COLUMN without rewrite
Wraparound safetyInvisibleA real operational riskWatch age(relfrozenxid)

The four rules.

RuleIn plain wordsTool
Estimate before you runSize, WAL volume and duration are arithmetic, not surprisespg_total_relation_size, row width, throughput benchmark on a slice
Bulk in, slices outLoad in one big stream; change in small committed slicesCOPY, key-range batches
Remove data by dropping containersNever DELETE a month; drop its partitionPartitioning
Watch it while it runsEvery long operation reports progresspg_stat_progress_*, pg_stat_io

Defaults you will meet (PostgreSQL 19 manual, MySQL 8.4 manual).

KnobDefaultWhy it matters at scale
maintenance_work_mem64MBIndex builds and VACUUM are slow with a tiny sort/dead-tuple budget
default_statistics_target100Skewed columns on huge tables may need more
autovacuum_vacuum_scale_factor0.220% of a billion rows would be 200 million dead tuples; the default cap below lowers it to 100 million
autovacuum_vacuum_max_threshold100,000,000Caps the trigger; check the docs for your version
autovacuum_vacuum_cost_delay2 msThrottles autovacuum I/O
vacuum_cost_limit200Work allowed between sleeps
autovacuum_freeze_max_age200 millionForces an anti-wraparound vacuum
BRIN pages_per_range128Range granularity of a BRIN index
innodb_buffer_pool_size (MySQL)See manualOn 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 instinctBillion-row reality
One transaction is simplestOne transaction holds locks and a snapshot for hours, blocks vacuum everywhere
Add an index, it is quickA 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 itDefaults are proportional; you tune per table
The replica is a copyThe 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 ​

  1. "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.
  2. "DELETE is how you remove data." On a huge table DELETE is the most expensive way: it logs every row, leaves dead tuples and needs a vacuum afterwards. Dropping a partition does none of that.
  3. "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).

text
 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% sample

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

MeasurePostgreSQLMySQL InnoDB
Row header23 bytes + padding, 4-byte pointerVariable record header, hidden DB_TRX_ID and DB_ROLL_PTR
Page size8 kB16 KB
Table size functionpg_table_size, pg_total_relation_sizeinformation_schema.TABLES (DATA_LENGTH, INDEX_LENGTH)
Value size functionpg_column_size(col)LENGTH() / OCTET_LENGTH()
Secondary index carriesctid (heap pointer)The primary key
sql
-- 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.

text
 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 pointer

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

SituationEffectAction
SELECT * on wide rowsDetoasts every large valueSelect needed columns only
Updating a TOASTed columnWrites the new value to TOAST, old chunks deadAvoid frequent updates of big blobs
Updating a narrow column of a wide rowHeap tuple is new; TOAST untouchedCheap relative to row size
Size reportingpg_relation_size hides TOASTpg_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).

text
 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
ResourceWhat consumes itCheck
DiskNew indexes, rewrites (VACUUM FULL, ALTER TYPE), temp files, WAL not yet archiveddf, pg_wal size, replication slots
WALBulk updates, index builds, full-page writes after checkpointpg_stat_wal, pg_current_wal_lsn() delta
I/OScans, builds, vacuum, replica catch-uppg_stat_io, cloud IOPS graphs
Memorymaintenance_work_mem, shared buffers hit ratiopg_stat_io, buffer cache hit
TimeEverything above divided by throughputA trial on a slice

Bulk loading ​

Bulk-load pipeline (PostgreSQL; MySQL: LOAD DATA, then ADD INDEX)1. StageCSV or binarysorted by key2. COPYbare tableparallel slices3. IndexCREATE INDEXparallel build4. ConstrainADD FOREIGN KEYthen VALIDATE5. ANALYZEfresh statisticsVACUUM FREEZE?Before the load (temporary)UNLOGGED or wal_level=minimallarge max_wal_sizeDuring the loadWAL volume, checkpointsreplica lag, free diskAfter the load (restore)LOGGED, wal_level, autovacuumfresh base backup if WAL skippedIndexes built once from sorted data are faster and smaller than updated row by row.Watch: pg_stat_progress_copy, pg_stat_progress_create_index, pg_stat_io

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.

text
 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
MethodPer-row costNotes
Autocommit single-row INSERTA WAL flush per rowSlowest by a wide margin
Multi-row INSERT ... VALUES (...), (...) in one transactionParse once per statementTypical batch sizes 500-5,000 rows; bounded by the 65,535 bind-parameter limit in PostgreSQL's protocol
INSERT ... SELECT / CREATE TABLE ASNo client round tripBest when data is already in the database
COPY FROM (PostgreSQL), text/CSVOne commandNeeds file access or STDIN
COPY ... (FORMAT binary)No text parsingUsed by pgx CopyFrom
LOAD DATA [LOCAL] INFILE (MySQL)One statementLOCAL needs local_infile; server-side files need secure_file_priv rules
pg_restore -jParallel per table / indexFor dumps
sql
-- 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".

text
 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
StepWhy this orderRisk if reversed
Load before indexesIndex built oncePer-row index maintenance multiplies load time
Foreign keys after loadChecked in bulkPending trigger queue can exhaust memory: the manual says it "may be necessary, not just desirable, to drop and re-apply foreign keys"
ANALYZE lastPlanner needs true distributionBad plans on first queries
COPY ... FREEZE on a new/truncated tableRows written already frozenNot 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.

EngineSettingEffect during bulk load
PostgreSQLmax_wal_size upFewer checkpoints
PostgreSQLsynchronous_commit = off (session)No wait for flush; a crash loses the last moments, never corrupts
MySQLautocommit = 0"performs a log flush to disk for every insert" otherwise
MySQLinnodb_autoinc_lock_mode = 2Interleaved lock mode for bulk inserts with AUTO_INCREMENT
MySQLbulk_insert_buffer_sizeLarger buffer for bulk inserts into a non-empty table (a MyISAM setting; InnoDB ignores it)
MySQLInsert in PRIMARY KEY orderClustered 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".

text
 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
ApproachCrash-safeReplicatedBackup/PITRWhen
Normal table, wal_level = replicaYesYesYesDefault; production tables
UNLOGGED tableNo (truncated after crash)NoNot in WALStaging area, derived data you can rebuild
wal_level = minimal + same-transaction COPYYesStandbys impossible while setBreaks PITR for the windowOne-time migration into an empty system
SET LOGGED after loading unloggedYes after the rewriteYesYesLoad 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.

KnobSafe?Revert
SET autocommit=0; ... COMMIT;YesCommit
SET unique_checks=0Only if data is known uniqueSET unique_checks=1
SET foreign_key_checks=0Only if data is known consistentSET foreign_key_checks=1
LOAD DATA LOCALNeeds local_infile enabled; a security trade-offDisable 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.

text
 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
SymptomLikely causeAction
Estimate off by 100x after a bulk loadNo ANALYZE yetANALYZE events ("strongly recommended" after bulk load)
Good plan for most tenants, terrible for the biggestSkew not captured at target 100SET STATISTICS 1000 on the column
Correlated columns underestimatedIndependence assumptionCREATE STATISTICS ... (dependencies, mcv)
ANALYZE slow on a huge tableHigh targetRaise only on columns that need it; autovacuum analyses in background
Partitioned table never analysedAutovacuum does not analyse the parentRun ANALYZE parent manually or on a schedule
sql
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.

text
 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
NeedTechniqueAccuracyCost
Table size for UIpg_class.reltuplesApproximateInstant
Rows matching a filter (estimate)EXPLAIN row estimatePlanner-qualityInstant
Exact total, rarelycount(*) (parallel seq scan)ExactFull scan
Exact total, oftenCounter table updated in the same transaction, or a trigger-maintained rollupExactWrite contention on one row; shard the counter
Distinct count at scaleHyperLogLog (postgresql-hll), see Bloom Filters & Probabilistic Structures~1-2%Small
Redis style countersINCR in RedisExact, outside the DBExtra system
sql
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.

text
 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

IndexSize on 1 billion timestamps (indicative)Finds one rowRange queryNeeds physical order
B-treeTens of GBYes, fastYesNo
BRIN (pages_per_range 128)MegabytesNoYes, if correlatedYes
BRIN (pages_per_range 32)Larger, still smallNoFiner pruningYes
Partitioning by rangeMetadata onlyn/aPrunes whole partitionsData lands in right partition
sql
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 good

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

text
 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
PatternIndexSaves
Queue of unprocessed rowsWHERE processed_at IS NULL99% of entries
Soft deletesWHERE deleted_at IS NULLDead rows
Hot recent dataWHERE created_at >= date (rotate)Old entries; prefer partitioning
Rare flagWHERE is_flaggedNearly everything
MySQL equivalentNone (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.

text
 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 filterPartitions touchedNote
Constant range on the keyOnly matching onesBest case
Parameter / prepared statementPruned at executor startEXPLAIN shows removed subplans
Function wrapped around the key (date_trunc('month', created_at))Often allCompare the raw column to constants
No key in WHEREAllAdd the key or a covering index per partition
MySQL (PARTITION BY RANGE)Pruning by the same ideaEXPLAIN 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.

text
 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
KnobEffectCaution
maintenance_work_memBigger sort in memory, fewer spill passesAutovacuum workers can each use up to this unless autovacuum_work_mem is set
max_parallel_maintenance_workersMore workers on B-tree, GIN, BRIN builds and plain VACUUMLimited by max_parallel_workers and max_worker_processes
ALTER TABLE ... SET (parallel_workers = n)Forces worker countReset afterwards: affects query plans too
CONCURRENTLYWrites continueTwice the scans; check pg_stat_progress_create_index
effective_io_concurrency / maintenance_io_concurrencyPrefetch depthStorage-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).

TaskCommandLockingTime driver
Rebuild one indexREINDEX INDEX CONCURRENTLY idxReduced; waits on long transactionsTable scan x2 + sort
Rebuild all indexes of a tableREINDEX TABLE CONCURRENTLY tPer indexSum of indexes
Rebuild everything faster, offlineREINDEX TABLE tACCESS EXCLUSIVE on the tableSingle pass
New index, never builtCREATE INDEX CONCURRENTLYReducedAs above
MySQLALTER TABLE ... ENGINE=InnoDB / OPTIMIZE TABLE (online DDL)Mostly onlineRebuild of clustered index

Batched backfills and updates ​

One big UPDATE vs batched backfill by key range (time runs left to right)Single UPDATEone transaction: every row locked, WAL burst, bloat, replica lag spikeBEGINCOMMIT (hours later)Batched slicesid 0kid 10kid 20kid 30kid 40kid 50kid 60kid 70keach slice: UPDATE ... WHERE id >= a AND id < b AND col IS NULL; COMMITdashed gap = sleep, replica-lag check, autovacuum catches upResume after crashrestart at MIN(id)WHERE col IS NULLThrottlesleep between slicespause while lag is highIndex the new columnonly after thebackfill is done

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.

text
 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
ConsequenceMechanismVisible as
Lock waitsRow locks held until commitpg_stat_activity wait_event_type = Lock
WAL stormEvery new tuple loggedDisk full in pg_wal; pg_stat_wal
BloatDead old versionsTable twice as large; slower scans
Replica lagStandby replays one huge transactionpg_stat_replication.replay_lag
Long snapshotOldest xmin pinnedVacuum cannot remove anything newer
InnoDBUndo log grows, history list length risesPurge 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.

text
 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
ParameterTypical startTune by
Slice size5,000-20,000 rowsAim for each statement under about 100 ms
Sleep100-500 msReplica lag, autovacuum keeping up, p99 latency of the app
IsolationRead Committed defaultSlices are independent
Lock waitSET lock_timeout = '2s'Retry on timeout instead of queueing behind a long app transaction
Index on the new columnAdd after the backfillOtherwise every update also maintains it
sql
-- 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.

ChangePostgreSQLMySQL InnoDB
Add nullable columnCatalog onlyInstant (8.0+ ALGORITHM=INSTANT)
Add column with constant defaultCatalog only (11+)Instant
Change column typeUsually rewritesRebuilds table
Add NOT NULLScan, or CHECK ... NOT VALID + VALIDATERebuild (online)
Large rebuild onlinepg_repack, logical replication swapgh-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.

text
 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
ParameterDefaultLarge-table setting
autovacuum_vacuum_scale_factor0.20.01 or 0 with absolute threshold
autovacuum_vacuum_threshold5010,000-1,000,000
autovacuum_vacuum_max_threshold100,000,000Lower per table
autovacuum_analyze_scale_factor0.10.005-0.01
autovacuum_vacuum_cost_limit-1 (uses vacuum_cost_limit 200)1,000-10,000 on fast storage
autovacuum_vacuum_cost_delay2 ms0-2 ms
autovacuum_max_workers3Raise if several giants; total cost limit is shared
maintenance_work_mem / autovacuum_work_mem64MBLarger dead-item memory = fewer index passes
sql
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.

SymptomCauseAction
Autovacuum runs for daysCost throttling plus index passesRaise autovacuum_vacuum_cost_limit for that table, more maintenance_work_mem
Vacuum starts again immediatelyThreshold too low or too slow to finishCheck n_dead_tup, last_autovacuum
Many index scans per vacuumDead-item memory too smallRaise maintenance_work_mem
I/O saturated by vacuumLimit too highLower, 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.

text
 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
ToolUseWatch
age(relfrozenxid) per tableDistance to wraparoundSELECT relname, age(relfrozenxid) FROM pg_class ORDER BY 2 DESC LIMIT 10
pg_stat_progress_vacuumPhases and heap blocks scannedheap_blks_scanned / heap_blks_total
COPY ... FREEZEFrozen at loadNot allowed on partitioned or foreign tables
vacuum_freeze_table_age, autovacuum_freeze_max_ageWhen aggressive vacuums happenKeep a gap
VACUUM (FREEZE, PARALLEL n)Manual catch-upParallel applies to index vacuuming
MySQLn/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

text
 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
MethodSpeedWALDead tuplesLocks
DELETE one statementSlowEvery rowYesRow locks for the duration
DELETE in key-range batchesSlow but throttledEvery rowYes (vacuum needed)Short row locks
DROP TABLE partitionInstantTiny (catalog)NoneACCESS EXCLUSIVE on the partition (and brief on parent)
DETACH PARTITION CONCURRENTLYInstantTinyNoneSHARE UPDATE EXCLUSIVE then waits
TRUNCATEInstantMinimalNoneACCESS EXCLUSIVE; not MVCC-safe
MySQL ALTER TABLE ... DROP PARTITIONInstantSmallNoneMetadata 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.

AspectDELETETRUNCATEDROP PARTITION
Row triggersFireDo not fireNot applicable
Foreign keysCheckedNeeds CASCADE or no referencing tablesSame as drop
Transaction-safeYesYes (rolls back) but not MVCC-safe for old snapshotsYes
Space returnedAfter vacuum rewriteImmediatelyImmediately

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.

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

TierStorageLatencyCostTypical content
HotPrimary heap, NVMemsHighestLast 30-90 days
WarmReplica or slower tablespacetens of msMedium1-2 years
ColdObject storage, ParquetsecondsLowestHistory, audits
RollupAggregated tablemsSmallCounts 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.

text
 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
EngineWhere to lookThrottle by
PostgreSQL streamingpg_stat_replication.replay_lagBackfill sleeps
PostgreSQL logicalpg_replication_slots confirmed_flush_lsnReduce write volume
MySQLSeconds_Behind_Source, replication lag in performance schemaSmaller transactions; one big transaction is replayed as one
Cloud (RDS/Aurora)CloudWatch ReplicaLagSame

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.

OptionIsolation from OLTPFreshnessEffort
Read replica (same engine)Good (separate server)SecondsLow
Dedicated reporting replicaBetter; relaxed standby settingsMinutesLow
Logical replication to another PostgreSQLFullSecondsMedium
CDC to columnar storeFullSeconds-minutesHigh
Nightly export to ParquetFullA dayLow

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.

text
 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
ViewKey columnsReading
pg_stat_progress_vacuumphase, heap_blks_total, heap_blks_scanned, heap_blks_vacuumed, index_vacuum_countA high index_vacuum_count means dead-item memory is too small
pg_stat_progress_create_indexphase, blocks_done/blocks_total, tuples_done/tuples_totalPhase names show scan, sort, load, wait
pg_stat_progress_copybytes_processed, tuples_processedThroughput of a COPY
pg_stat_progress_analyzesample_blks_scannedTime to finish ANALYZE
pg_stat_ioreads, writes, extends, hits by backend_type and contextIs vacuum or a bulk write hogging I/O?
pg_stat_activitywait_event, state, xact_startLong transactions that hold back vacuum and index builds
pg_stat_user_tablesn_dead_tup, last_autovacuum, n_mod_since_analyzeIs autovacuum keeping up?
sql
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).

TopicMySQL InnoDBNote
Buffer poolinnodb_buffer_pool_size ~ 50-80% of RAM on a dedicated serverDump/load for warm restarts
Bulk loadLOAD DATA, autocommit=0, unique_checks=0, foreign_key_checks=0Verify data first
Large DELETEBatches with LIMIT; pt-archiverPurge lag if big
Table rebuildOPTIMIZE TABLE / ALTER TABLE ... ENGINE=InnoDBOnline but needs temp space
Partition dropALTER TABLE ... DROP PARTITIONInstant

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.

ToolMechanismThrottlingCaveat
InnoDB online DDLIn-place with a row loginnodb_online_alter_log_max_sizeLog overflow aborts
pt-online-schema-changeTriggers copy changes--max-lag, --chunk-timeTriggers add load, not usable with some triggers
gh-ostReads binlog, no triggersDynamic throttle, replica lag awareNeeds row-based binlog
PostgreSQL pg_repackTrigger plus table copyCooperative locksNeeds 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.

PostgreSQLInnoDB
Dead tuples wait for VACUUMUndo pages wait for purge
Old snapshot pins xmin horizonOld read view lengthens history list
Autovacuum thresholdsinnodb_purge_threads, purge lag
Table bloatUndo tablespace growth

Mechanics ​

What happens underneath, with the knobs and error codes you will actually see.

Where the time and the WAL go ​

text
 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
PhaseKnobLarge-table effect
Heap writefillfactor (table storage parameter)Lower fillfactor leaves room for HOT updates, but makes the table larger
WAL volumewal_compression, full_page_writesCompression shrinks full-page images; never turn full_page_writes off without understanding the risk
Checkpointsmax_wal_size, checkpoint_timeoutRaise for loads; frequent checkpoints = more full-page images
Flushsynchronous_commitoff per session for loads you can redo
Replicationmax_wal_senders, slotsRetained WAL fills disk if a standby is stuck
Replayone startup processReplay 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 / messageEngineMeaningAction
53100 disk_fullPostgreSQLWAL or temp files filled the diskThrottle or free space; check slots
55P03 lock_not_availablePostgreSQLlock_timeout hitRetry the slice later
57014 query_canceledPostgreSQLstatement_timeout or user cancelReduce slice size
40001 serialization_failurePostgreSQLConcurrent update at higher isolationRetry the slice
ERROR: out of memory on huge COPY with FKsPostgreSQLPending trigger events exhausted memoryDrop FKs, reload, re-add
could not resize shared memory segmentPostgreSQLParallel query shm exhaustedLower parallelism
1206 (ER_LOCK_TABLE_FULL)MySQLToo many row locks in one transactionSmaller batches
1205 (ER_LOCK_WAIT_TIMEOUT)MySQLinnodb_lock_wait_timeoutRetry
DB_ONLINE_LOG_TOO_BIGMySQLOnline DDL log exceeded innodb_online_alter_log_max_sizeRaise or run during quiet time
1114 (ER_RECORD_FILE_FULL)MySQLDisk fullFree space

Solving the classic problems ​

ProblemSolutionHowAdvantageCost / limitation
Load 500M rows fastParallel COPY by id sliceOne connection per worker, binary CopyFromNear disk speedNeeds bare table and a sorted source
Add and fill a columnAdd nullable, key-range backfill, then NOT NULL via NOT VALID + VALIDATEUPDATE ... WHERE id BETWEEN with sleepNo long lockTakes long wall time
Keep indexes smallBRIN or partial indexUSING brin, WHERE status <> 'done'100-1000x smallerRequires correlation / predicate match
RetentionRange partitions + DETACH + DROPScheduled job (pg_partman or cron)Instant, no vacuumPartition key must match filters
Dashboard countreltuples estimate or counterpg_class or rollup tableInstantApproximate or write contention
Autovacuum never finishesPer-table settings, bigger memoryALTER TABLE SET (autovacuum_*)Predictable cadenceNeeds I/O headroom
Analytics hurting OLTPReplica / columnar storeStreaming replica, CDC to ClickHouseIsolationStaleness, extra system

Go: parallel COPY loader with pgx ​

Setup in a fresh module (go.mod pins go 1.24; pgx/v5 v5.7.2):

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

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

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

ErrorMeaningRetry?
55P03 lock timeoutA slice waited too long for a row lockYes, with backoff; the slice is idempotent
40001 / 40P01Serialization failure / deadlockYes, retry the slice
Connection reset during COPYSlice transaction rolled backYes, re-run that slice (transaction was atomic)
53100 disk fullCapacityNo: stop, free space, then resume
Constraint violation in COPYBad data in the streamNo: 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 ​

ProductBulk loadRetention and notes
PostgreSQLCOPY, pg_restore -jPartition drop, UNLOGGED, BRIN
MySQL InnoDBLOAD DATA, multi-row INSERT, pt-archiverPartition drop, gh-ost for DDL
SQL ServerBULK INSERT, bcp, INSERT ... SELECT with minimal logging in bulk-logged/simple recoveryPartition switching (SWITCH PARTITION) and sliding window
OracleDirect-path INSERT /*+ APPEND */, SQL*Loader, external tablesEXCHANGE PARTITION, DROP PARTITION
SQLiteOne big transaction, PRAGMA journal_mode=WAL, .importWhole-file size limit; not for billions of rows on one writer
MongoDBinsertMany unordered, bulkWrite, mongoimportTTL index for expiry; sharding for scale
CockroachDBIMPORT/COPY, batch inserts of a few thousand rowsRow-level TTL, range splits
Redisredis-cli --pipe, pipeliningEviction/expiry; not a table store at this size

Choosing a technique ​

SituationRecommendedExtra techniqueReason
One-time initial load into an empty tableCOPY into bare table, then indexeswal_level=minimal, COPY FREEZE, big maintenance_work_memFewest writes, tight indexes
Recurring bulk load into a live tableCOPY into staging table, then INSERT ... SELECT or partition attachKeep indexes, batch by partitionKeeps production indexes valid
Append-only time seriesRange partition + BRINautovacuum_vacuum_insert_*, freeze earlyCheap index, instant retention
Fill a new column on all rowsKey-range backfillAdd index after, lock_timeoutNo lock or WAL storm
Skewed multi-tenant dataHigher statistics target, partial indexesPartition by tenant hashPlanner sees skew
Need exact count oftenCounter tableEstimate for UIcount(*) is a scan
Remove old rowsDETACH/DROP PARTITIONArchive firstNo vacuum
Autovacuum lags on a giant tablePer-table thresholdsRaise cost limit and memoryPredictable cadence
Analytics on huge historyReplica or columnar offloadRollupsIsolate OLTP
MySQL schema change on 1B rowsgh-ost / pt-online-schema-changeThrottle on replica lagOnline 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 ​

ScaleRowsWhat worksWhat stops working
1xup to ~100MOne table, normal indexes, defaultsNothing yet
10x~1BPartitioning by time, BRIN/partial indexes, per-table autovacuum, batched backfillscount(*), whole-table UPDATE, DELETE retention
100x10B+ / multi-TBSharding or distributed SQL, columnar offload, tiering, rollupsSingle-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.

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

Setup.

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

Experiment 1: load 50 million rows with and without indexes.

text
 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_size

Experiment 2: BRIN versus B-tree size.

text
 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 scan

Experiment 3: single UPDATE versus batched UPDATE (lock duration).

text
     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 case

Experiment 4: watch progress while it runs.

text
 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 load

Experiment 5: partition drop versus DELETE.

text
 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;  -- instant

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

BeliefReality
"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 ​

TopicWhat to remember
Sizingpg_total_relation_size, 24+4 bytes per row overhead, sample with TABLESAMPLE
LoadCOPY bare table, then indexes, then constraints, then ANALYZE
wal_level=minimalNeeds restart, no standbys/PITR; same-transaction TRUNCATE + COPY skips WAL
UNLOGGEDFast but truncated after a crash and not replicated
MySQL loadLOAD DATA, autocommit=0, unique_checks=0, foreign_key_checks=0, PK order
Statisticsdefault_statistics_target 100; per column SET STATISTICS; ANALYZE after load
Countingpg_class.reltuples estimate; counter for exact
BRINpages_per_range 128; needs correlation; tiny index
Partial indexIndex only the rows queried; predicate must imply
BackfillKey-range slices, idempotent predicate, lock_timeout, sleep, resumable
AutovacuumPer-table scale factor and threshold; raise vacuum_cost_limit; maintenance_work_mem
FreezeWatch age(relfrozenxid); autovacuum_freeze_max_age 200M; COPY FREEZE at load
RetentionDETACH PARTITION CONCURRENTLY then DROP; never mass DELETE
Monitoringpg_stat_progress_vacuum/create_index/copy, pg_stat_io, pg_stat_replication
InnoDBBuffer pool ~80% on dedicated servers; watch history list length; gh-ost for DDL

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — Why 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 ​

TermMeaning
BackfillFilling a new column or table from existing data after a schema change
BRINBlock Range Index: min/max summaries per group of adjacent pages
pages_per_rangeBRIN storage parameter, default 128
Bulk loadLoading many rows at once, usually COPY/LOAD DATA
COPYPostgreSQL command that streams rows into or out of a table
COPY ... FREEZELoads rows already frozen into a new/truncated table
LOAD DATAMySQL statement that loads rows from a text file
UNLOGGEDTable that skips WAL; not crash-safe, not replicated
wal_levelHow much information is written to WAL (minimal, replica, logical)
TOASTPostgreSQL's out-of-line storage for large values
reltuplespg_class estimate of the number of rows
default_statistics_targetDefault number of statistics entries per column (100)
ANALYZESamples a table to refresh planner statistics
Partial indexIndex with a WHERE predicate
Partition pruningPlanner skipping partitions that cannot match
DETACH PARTITIONTurns a partition into a standalone table
Autovacuum scale factorFraction of the table that must change before vacuum starts
vacuum_cost_limitCost accumulated before vacuum sleeps (default 200)
FreezeMarking old rows as visible to everyone to avoid xid wraparound
Anti-wraparound vacuumAggressive vacuum forced by autovacuum_freeze_max_age
maintenance_work_memMemory for vacuum, index builds, FK adds (default 64MB)
max_parallel_maintenance_workersCap on workers for parallel index builds and vacuum
REINDEX CONCURRENTLYRebuilds an index without blocking writes
pg_stat_progress_*Views that report progress of long commands
pg_stat_ioCluster-wide I/O statistics by backend type and context
History list lengthInnoDB count of undo pages awaiting purge
innodb_buffer_pool_sizeInnoDB cache size; ~80% of RAM on a dedicated server per the manual
innodb_online_alter_log_max_sizeLimit of the online DDL DML log
gh-ostTriggerless online schema change tool for MySQL
pt-online-schema-changePercona's trigger-based online schema change
Cold storage / tieringMoving old data to cheaper storage
Columnar offloadCopying data to a column store for analytics
fillfactorTable storage parameter: how full INSERT packs a page (default 100); lower leaves room for HOT updates
lock_timeoutSession setting: give up with 55P03 instead of waiting for a lock
max_wal_sizeSoft limit of WAL between checkpoints; raise it during loads
CopyFrompgx method that streams rows with the COPY protocol
chunkByIdLaravel query-builder method that pages by primary key, safe while updating
HOTHeap-only tuple: an update that needs no new index entries
TABLESAMPLESQL clause that reads a random sample of a table
batch INSERTSeveral rows per INSERT ... VALUES statement or per transaction
key rangeA slice id >= a AND id < b of the primary key used to walk a table in batches
vacuum_failsafe_ageTable age at which vacuum drops cost delay and index vacuuming to avoid wraparound
autovacuum_vacuum_max_thresholdCap on dead tuples that trigger autovacuum (default 100,000,000)
unique_checksMySQL session variable; 0 skips uniqueness checks for secondary indexes during a load
foreign_key_checksMySQL session variable; 0 skips foreign key checks during a load
innodb_autoinc_lock_modeInnoDB auto-increment locking mode; 2 (interleaved) is best for bulk inserts
bulk_insert_buffer_sizeMySQL buffer for bulk inserts into a non-empty MyISAM table
pg_stat_replicationView with write_lag, flush_lag, replay_lag per standby
replication lagHow far a replica is behind its primary
read replicaReplica used for read-only queries, including analytics
row widthAverage bytes per row including header and padding
pg_total_relation_sizeHeap plus TOAST plus indexes, in bytes
pgsqlCopyFromFilePHP PDO method that runs COPY FROM for PostgreSQL
DROP PARTITIONRemoves a partition (and its data) instantly; MySQL ALTER TABLE ... DROP PARTITION, PostgreSQL DROP TABLE
enable_partition_pruningPlanner setting (default on) that allows pruning
pg_stat_progress_copyProgress view for running COPY commands
pg_stat_progress_vacuumProgress view for VACUUM and autovacuum
pg_stat_progress_create_indexProgress view for CREATE INDEX and REINDEX

References ​

Built by Morteza Negahi