Uniform Random Sampling Over a 110M-Row PostgreSQL Table
Why ORDER BY random() strands jobs at 77% selectivity, why TABLESAMPLE SYSTEM introduced 0.53 total-variation distance bias on a clustered heap, and how generate_series random-PK probing with adaptive overdraw fixed it in ~17s.
Drawing N uniformly random rows from a 110-million-row PostgreSQL audience table sounds straightforward until the filter matches 77% of the table (~85M rows) and the standard answers either time out or bias the sample.
Why ORDER BY random() LIMIT N strands jobs
When a filter matches ~85M out of 110M rows (~77% selectivity), PostgreSQL rightly ignores secondary indexes and chooses a sequential scan. Adding ORDER BY random() LIMIT 10000 forces a full-pool top-K heap sort across all 85 million qualifying rows.
In production, that query ran over 270 seconds on top of a 174-second pre-send .count() check. Combined with statement_timeout = 0 and claiming the job APPROVED -> RUNNING before materializing the audience, workers stranded campaigns indefinitely.
Adding more indexes does not help: at 77% selectivity, an index scan is slower than a sequential scan, and PostgreSQL still has to evaluate random() across every matching row.
Why TABLESAMPLE SYSTEM is fast and wrong on clustered heaps
The standard PostgreSQL advice for large-table sampling is TABLESAMPLE SYSTEM (p), which samples random 8 KB heap pages instead of scanning every row. It returned in ~0.5 seconds, but it broke statistical uniformity.
Because the contact table had been bulk-loaded and appended over time by source batch, physical heap pages were heavily clustered by telecom carrier prefix. Sampling whole 8 KB pages pulled entire blocks of one carrier at a time. Measured against a true uniform sample, TABLESAMPLE SYSTEM produced a total-variation distance (TVD) of 0.53, with one carrier prefix over-sampled more than 3x (13.8% vs. 4.4% uniform).
TABLESAMPLE BERNOULLI avoids block clustering, but reads every page of the 110M-row table, putting us back on a full sequential scan.
Fix: generate_series random-PK probing with adaptive overdraw
To get row-level uniformity in seconds without a schema migration or auxiliary sampling index, we switched to random primary-key probing inside PostgreSQL (_sample_by_random_pk):
- Read
(MIN(id), MAX(id))in O(1) using the primary-key B-tree index. Ifspan < 4 * count, skip the fast path immediately because the table or range is small enough that exact sorting is already cheap. - Generate
kuniform random candidate IDs inside PostgreSQL viagenerate_series(1, k)and feed them directly into an index semi-join withLIMIT:
SELECT id, phone
FROM contacts
WHERE <audience predicates>
AND id IN (
SELECT (FLOOR(RANDOM() * %s) + %s)::bigint
FROM generate_series(1, %s)
)
LIMIT %s;
Because RANDOM() is VOLATILE, PostgreSQL evaluates it once per generated row. The planner turns this into a PK index probe / semi-join that short-circuits as soon as LIMIT matching rows are found, with no large ID list serialized over the wire from the application.
- Use adaptive overdraw with a hard draw budget. Round 1 probes
k = ceil(need * 1.5)candidate IDs. If fewer thanneedrows match (because of PK gaps or filter selectivity), subsequent rounds estimate the empirical match rate and drawceil(remaining / observed_rate * 1.3), capped at 40,000 candidates per query and 150,000 total draws. - Fall back to exact
COUNT(*) + ORDER BY random()if a narrow or sparse audience exhausts the 150k draw budget. Any audience sparse enough to exhaust 150k uniform probes is small enough that the exact fallback is cheap, and it provides the exactavailablecount needed to raise an accurate insufficient-audience error. - Shuffle the deduplicated result set in memory before slicing to
countso PK/probe ordering does not introduce positional bias.
Production result
- 10,000 distinct uniform rows in 1 query (~17 seconds) vs. >270s timeout plus 174s
.count(). - Row-level uniformity across carrier prefixes with no heap-clustering bias.
- Zero schema changes, zero extra indexes, and bounded fallback cost on sparse filters.
Comments