Scrivio Interview library
ScenarioIntermediate6 min read · updated 12 November 2026

After a nightly job inserts 20 million rows into an events table, the first morning reports are very slow and become fast again by noon. What is happening and how would you fix it?

Right after the nightly job inserts 20 million rows, the table's statistics still describe yesterday's data, so the planner badly misestimates queries on the new rows and picks poor plans until autovacuum's auto-analyze eventually runs, which on a busy system can take hours. That is why reports recover by noon. The fix is to run ANALYZE events explicitly as the last step of the load job, tune autovacuum_analyze_scale_factor for this large append-heavy table, and remember that partitioned parents need manual ANALYZE because autovacuum does not maintain their statistics.

Why this question is asked

A problem that appears every morning and fixes itself by noon is a strong hint that something time-based is catching up, and in PostgreSQL that is very often statistics. Interviewers like this scenario because it tests whether we connect a symptom pattern to the planner's statistics and to how autovacuum schedules its work. In this answer, we will recap what statistics are and how auto-analyze decides when to run, see why freshly loaded data is misestimated, reproduce the problem, and then fix it in the load job, in the autovacuum settings and for partitioned tables.

1A Quick Recap of Statistics and Auto-Analyze

The planner chooses plans from statistics that ANALYZE collects by sampling a table: row counts, most common values, histograms of value ranges, and n_distinct per column. They are a snapshot taken at the moment ANALYZE ran. Autovacuum, PostgreSQL's background maintenance process, runs ANALYZE automatically on a table once enough rows have changed since the last analyze.

The rule is that a table is analyzed when the number of changed rows exceeds autovacuum_analyze_threshold plus autovacuum_analyze_scale_factor times the number of rows. With the defaults of 50 and 0.1, a 200 million row table needs 50 + 0.1 x 200,000,000 = about 20 million changed rows. Our nightly load of 20 million rows is right at that edge, so depending on the table's size, it may not even trigger auto-analyze.

2Why Fresh Rows Are Misestimated

Imagine the morning report asks for yesterday's events: WHERE created_at >= '2026-11-04'. The histogram of created_at was built before the load, so its last bucket ends at the previous day. To the planner, yesterday's date lies at or beyond the edge of what it knows, and its estimate for that range can be tiny, sometimes just a handful of rows. PostgreSQL can sometimes look up the real current maximum from an index to soften this, but the counts and frequencies are still those of the old data; check your version for the details.

The same happens for other columns: a new event_type that appeared in the load is not in the most common values list, and a new tenant's share is unknown. With an estimate of 50 rows for what is really 20 million, the planner chooses an index scan with a nested loop join, sized for 50 rows. That plan runs for minutes.

SQL
-- 07:00, just after the load
EXPLAIN ANALYZE SELECT event_type, count(*) FROM events
WHERE created_at >= '2026-11-04' GROUP BY event_type;
-- Index Scan using events_created_at_idx (rows=48) (actual rows=20000000 loops=1)
SELECT last_analyze, last_autoanalyze, n_mod_since_analyze
FROM pg_stat_user_tables WHERE relname = 'events';
-- null | 2026-11-04 11:42 | 20000000

The last line confirms it: 20 million rows have been modified since the last analyze, which happened yesterday before noon.

3Why It Becomes Fast by Noon

Even when the threshold is crossed, auto-analyze does not run instantly. Autovacuum has a limited number of workers, three by default, and they work through tables that need vacuuming or analyzing one at a time. On a busy system with many tables, and with the cost-based delay that throttles autovacuum to protect foreground work, it can take hours before a worker reaches the events table. When it finally does, the statistics include the new rows, the planner estimates 20 million rows correctly, and the reports switch to a sequential scan or a parallel plan that finishes in seconds. Cache warming adds to the effect: by noon the new data has also been read into memory once.

Step throughA night and a morning on the events table
Load jobevents tableAutovacuumReports
02:00 insert 20M rows
03:30 job finishes, no ANALYZE
07:00 query uses old statistics
bad plan, minutes per report
11:40 auto-analyze finally runs
12:00 query uses fresh statistics
good plan, seconds

7 messages in order. Play them, or step through them one at a time.

The gap between the end of the load and the auto-analyze is when reports are slow.

4Fix 1: Analyze at the End of the Load

The direct fix is to make the load job finish the work it started. Whoever changes 20 million rows knows the statistics are now stale, so the job should refresh them before reports run.

SQL
-- last step of the nightly load
ANALYZE events; -- samples the table, does not scan it all
ANALYZE events (created_at, event_type); -- or only the columns the reports filter on

ANALYZE reads a sample, by default 300 x the statistics target = 30,000 rows, so it takes seconds even on a large table and does not block reads or writes. This one line usually removes the morning problem completely.

5Fix 2: Tune Auto-Analyze for This Table

As a safety net, we make autovacuum react sooner for this large, append-heavy table. A scale factor of 0.1 means waiting for 10% of the table to change, which for very large tables is far too late. We can lower it for one table, or switch to a fixed threshold.

SQL
ALTER TABLE events SET (
autovacuum_analyze_scale_factor = 0.0,
autovacuum_analyze_threshold = 1000000 -- analyze after every million changed rows
);

This does not guarantee timing, because workers may still be busy, which is why Fix 1 stays the main fix. But it means the table is queued for analyze soon after any large change, including loads outside the nightly job.

6Fix 3: Partitioned Tables Need Manual ANALYZE

If events is a partitioned table, there is a trap. Autovacuum analyzes each partition, the child tables that hold the rows, but it does not analyze the partitioned parent itself, because the parent holds no rows of its own. Queries that span several partitions, and joins against the parent, use the parent's statistics, which then stay stale or empty forever unless someone runs ANALYZE on the parent.

Java
ANALYZE events; -- on a partitioned table: analyzes the parent and its partitions
ANALYZE events_2026_11_04; -- a single new partition, when only that one changed

So for partitioned tables, the load job should analyze the new partition and, at a sensible interval, the parent too. Check your version, since the details of partitioned-table statistics have evolved between releases.

7Follow-up questions

How do I confirm stale statistics are the cause and not something else?

Run the slow report with EXPLAIN ANALYZE right after the load and compare estimated and actual rows on the scans of events; a huge underestimate is the sign. Then check pg_stat_user_tables for n_mod_since_analyze and the time of last_autoanalyze. If running ANALYZE events by hand makes the same query fast immediately, the cause is confirmed.

Would VACUUM help as well?

VACUUM is about dead rows and the visibility map, not planner statistics, although VACUUM ANALYZE does both. For an insert-only table, vacuum matters for index-only scans and freezing, and PostgreSQL 13 and later trigger autovacuum on inserts too, but the morning problem here is the statistics, so ANALYZE is the step that matters.

Could a scheduled ANALYZE at 06:00 replace the step in the job?

It works until the load runs late one night and finishes at 06:30. Analyzing as the last step of the job ties the refresh to the change itself, so it is always correct, whatever the timing.

8Conclusion

In this answer, we traced slow morning reports to statistics that still describe the table as it was before 20 million new rows arrived, so the planner misestimates queries on the new data and picks plans sized for a few rows. Auto-analyze only triggers after the threshold plus scale factor times rows have changed and runs when a worker reaches the table, which can take hours, so the reports recover by noon. We fixed it by running ANALYZE at the end of the load, tuning per-table analyze settings, and analyzing partitioned parents manually.

What to say in the interviewAbout 90 seconds aloud

Open with

This looks like stale statistics. The nightly job adds 20 million rows, but the planner's statistics were collected before that, so for queries on yesterday's data the histogram and the most common values describe the old table.

Then, if they want more

A filter on yesterday's dates can be estimated at a few dozen rows when it really matches 20 million, so the planner picks something like an index scan with a nested loop, and the report takes minutes. It becomes fast by noon because autovacuum's auto-analyze eventually runs.

It only triggers after the threshold plus the scale factor times the row count have changed, 10% of the table by default, and then a worker has to get to the table, which on a busy system with three workers and throttling can take hours. I would confirm it with EXPLAIN ANALYZE right after the load and n_mod_since_analyze in pg_stat_user_tables.

The main fix is simple: the load job runs ANALYZE events as its last step. It only samples the table, so it takes seconds. As a safety net I would lower autovacuum_analyze_scale_factor for this table, or set a fixed threshold like a million rows.

And if events is partitioned, I would remember that autovacuum analyzes the partitions but not the partitioned parent, so the job should analyze the new partition and the parent explicitly.

About this answer

Last updated
12 November 2026
Versions it names
PostgreSQL 13
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "After a nightly job inserts 20 million rows into an events table, the first morning...": https://scrivio-interview-library.netlify.app/databases/query-optimization/b6a21ae222/