Sub topic 8
Running refreshes on a schedule
A materialized view only changes when you run REFRESH MATERIALIZED VIEW. PostgreSQL has no built-in way to do that on a timer, so something outside the view has to issue the command. This chapter covers the options for that, using pg_cron as the main example, and the problems a scheduled refresh runs into in production.
It assumes you know how to create, index, and refresh a materialized view, including CONCURRENTLY. It uses the sales_daily view from earlier chapters.
What a scheduler has to do
A scheduled refresh is a recurring SQL statement. The scheduler therefore needs to do four things:
- Connect to the right database as a role that owns the materialized view.
- Run
REFRESH MATERIALIZED VIEW CONCURRENTLY sales_dailyat a chosen interval. - Avoid piling up runs when one takes longer than the interval.
- Leave a record of success or failure.
PostgreSQL itself does none of this. Any tool that can run a statement on a timer can do the job. The usual choices are compared below.
| Scheduler | Runs where | Strengths | Weaknesses |
|---|---|---|---|
| `pg_cron` extension | Inside the database server | Schedule is stored in the database. No extra host. Run history is queryable with SQL. | Needs `shared_preload_libraries` and a restart. Not available on every host. |
| OS `cron` or systemd timer with `psql` | On a separate host or the DB host | Needs no extension. Familiar tooling. | Credentials live on the scheduler host. Schedule is outside the database and easy to lose in a migration. |
| Kubernetes CronJob or a workflow tool | In your platform | Fits existing alerting and retries. | More moving parts for a single statement. |
| Application scheduler | In your app | Can refresh right after a known data load. | Every app instance must agree on who runs the job. |
If your data arrives in batches, such as a nightly load, consider triggering the refresh at the end of the load job instead of on a clock. A clock-based refresh can run before the load finishes, or long after it did.
Scheduling with pg_cron
pg_cron runs a background worker that reads job definitions from a table and executes them as SQL. Two setup steps matter.
First, the library must be preloaded. In postgresql.conf:
shared_preload_libraries = 'pg_cron'
cron.database_name = 'postgres'Changing shared_preload_libraries requires a server restart. On managed services such as Amazon RDS, you set the same parameters through the parameter group instead.
Second, create the extension in the database named by cron.database_name. This is postgres by default, not necessarily the database that holds your views.
CREATE EXTENSION IF NOT EXISTS pg_cron;Now schedule the refresh:
SELECT cron.schedule(
'refresh-sales-daily',
'*/15 * * * *',
'REFRESH MATERIALIZED VIEW CONCURRENTLY sales_daily'
);The call returns a job id. The three arguments are:
- Job name. Scheduling again with the same name updates the existing job instead of creating a duplicate, so the call is safe to keep in a migration script.
- Schedule. Standard five-field cron syntax: minute, hour, day of month, month, day of week.
*/15 * * * *means every 15 minutes. Recent versions also accept an interval such as'30 seconds'. - Command. The SQL to run.
Schedule examples
| Expression | Meaning |
|---|---|
| `*/15 * * * *` | Every 15 minutes |
| `0 * * * *` | At the top of every hour |
| `30 2 * * *` | Daily at 02:30 |
| `0 6 * * 1-5` | 06:00 on weekdays |
By default pg_cron interprets schedules in GMT. Recent versions add a cron.timezone setting. If "02:30" must mean local time, check which version you have before you rely on it.
Refreshing a view in another database
The extension lives in one database, but your view may live in another. Use cron.schedule_in_database:
SELECT cron.schedule_in_database(
'refresh-sales-daily',
'*/15 * * * *',
'REFRESH MATERIALIZED VIEW CONCURRENTLY sales_daily',
'reporting'
);Who runs the job
The job runs as the role that scheduled it. That role must own the materialized view, because REFRESH is an owner-only operation (superusers can also do it). A common failure is scheduling the job as an admin account and later dropping that account, or scheduling it as a role that can read the view but doesn't own it.
A safer command: wrap the refresh in a function
A bare REFRESH statement works, but a function gives you a place for timeouts and bookkeeping. PostgreSQL does not record when a materialized view was last refreshed, and pg_matviews has no such column. A small log table fills the gap.
CREATE TABLE IF NOT EXISTS matview_refresh_log (
id bigserial PRIMARY KEY,
matview text NOT NULL,
started_at timestamptz NOT NULL,
finished_at timestamptz NOT NULL
);
CREATE OR REPLACE FUNCTION refresh_sales_daily() RETURNS void
LANGUAGE plpgsql AS $$
DECLARE
t0 timestamptz := clock_timestamp();
BEGIN
SET LOCAL lock_timeout = '10s';
REFRESH MATERIALIZED VIEW CONCURRENTLY sales_daily;
INSERT INTO matview_refresh_log (matview, started_at, finished_at)
VALUES ('sales_daily', t0, clock_timestamp());
END;
$$;
SELECT cron.schedule(
'refresh-sales-daily',
'*/15 * * * *',
'SELECT refresh_sales_daily()'
);Two details are worth noting.
SET LOCAL lock_timeoutmakes the refresh fail after 10 seconds instead of waiting indefinitely for a lock. Without it, a refresh stuck behind a long transaction can queue up and block other work. A failed run is visible in the run history, and the next run tries again.- The log row is written in the same transaction as the refresh. If the refresh fails, no row is written, so the newest
finished_atalways reflects the last successful refresh. A dashboard or alert can compare it againstnow().
Overlapping runs
Suppose a refresh takes 20 minutes and the schedule is every 15. pg_cron runs at most one instance of a given job at a time. If the next start time arrives while the previous run is still going, the new run is queued and starts when the first one finishes. Runs therefore don't pile up in parallel, but they can run back to back and keep the server busy.
Two consequences follow:
- Choose an interval comfortably longer than the worst-case refresh time, not the average.
- If runs regularly overlap, the problem is the refresh cost, not the schedule. See the earlier chapter on freshness trade-offs.
The diagram shows a normal cycle with a CONCURRENTLY refresh while readers keep querying.
Choose CONCURRENTLY for scheduled jobs
A plain REFRESH MATERIALIZED VIEW takes an ACCESS EXCLUSIVE lock, so every reader waits until it finishes. With a schedule, that stall repeats every cycle. CONCURRENTLY lets readers continue, at the cost of three conditions:
- The view needs at least one unique index on plain columns that covers all rows.
- The view must already be populated. On a
WITH NO DATAview, run one plainREFRESHfirst, then switch the schedule toCONCURRENTLY. - It is usually slower than a plain refresh, because it builds the new result in a temporary table and applies the differences.
The scheduled command in the previous section always uses CONCURRENTLY. If you schedule a concurrent refresh before the unique index exists, or before the first population, the job fails every cycle until you fix it.
Monitoring runs
pg_cron records each execution in cron.job_run_details:
SELECT j.jobname,
d.status,
d.return_message,
d.start_time,
d.end_time - d.start_time AS duration
FROM cron.job_run_details d
JOIN cron.job j USING (jobid)
WHERE j.jobname = 'refresh-sales-daily'
ORDER BY d.start_time DESC
LIMIT 10;Look for status = 'failed' and read return_message. Typical messages are a lock timeout, a missing unique index, or a permission error.
Run history grows without limit. Either set cron.log_run = off for jobs you don't want logged, or schedule a cleanup job such as:
SELECT cron.schedule(
'purge-cron-history',
'0 3 * * *',
$$DELETE FROM cron.job_run_details WHERE end_time < now() - interval '7 days'$$
);To stop a schedule, use SELECT cron.unschedule('refresh-sales-daily');.
Scheduling from outside the database
When pg_cron is not an option, an OS scheduler works with psql. This crontab line uses flock so a slow run cannot overlap the next one, and ON_ERROR_STOP so psql exits with a nonzero status on failure:
*/15 * * * * flock -n /tmp/refresh_sales_daily.lock psql "service=reporting" -v ON_ERROR_STOP=1 -c "SELECT refresh_sales_daily()" >> /var/log/refresh_sales_daily.log 2>&1The service=reporting part reads connection details from pg_service.conf and ~/.pgpass, so no password appears in the command. Without flock, overlapping runs from OS cron would both start. The second one would wait on the first's lock, which is the stall you were trying to avoid. Exit codes also let a wrapper such as a systemd unit or a monitoring agent alert on failure.
Common problems
- Job never runs. The extension was created in a database other than
cron.database_name, or the server was not restarted after changingshared_preload_libraries. - Job fails with "permission denied". The scheduling role does not own the view.
- Job fails with "cannot refresh materialized view concurrently". The view lacks a qualifying unique index, or has never been populated.
- Data is staler than the interval suggests. Runs are failing silently. Check
cron.job_run_detailsor your log table. - Refreshes happen at the wrong hour. The schedule is being read in GMT.
- Readers stall every cycle. The job uses a plain
REFRESH.
Exercises
Exercise
A materialized view refresh takes 6 minutes on average and 25 minutes at month end. You schedule it with */15 * * * * using pg_cron. What happens at month end, and what would you change?
Show answer
pg_cron runs at most one instance of a job at a time, so runs that come due while the 25-minute refresh is still going are queued and start after it finishes. The server stays busy with back-to-back refreshes for a while. Pick an interval longer than the worst case (for example every 30 or 60 minutes), or reduce the refresh cost. Using CONCURRENTLY keeps readers unblocked while the long run goes on.
Exercise
Your pgcron job refresh-sales-daily runs `REFRESH MATERIALIZED VIEW CONCURRENTLY salesdaily and cron.jobrundetails shows status = failed` on every run since a migration. Name two likely causes and how to check each.
Show answer
First, the unique index on the view may be missing, because the migration recreated the view without it. Check with \d sales_daily in psql or query pg_indexes, then recreate the index. Second, the view may now be owned by a different role than the one that scheduled the job. Check the owner in pg_matviews (matviewowner) against cron.job.username, then reschedule as the owner or change the owner. The return_message column in cron.job_run_details shows which error occurred.