Sub topic 8
Running Refreshes on a Schedule
This chapter assumes that you know basic SQL, PostgreSQL indexes, and how to create a materialized view. It also assumes that you have permission to refresh the view and access to either a system scheduler or the pg_cron extension.
A materialized view keeps the result of its defining query until you refresh it. Scheduling a refresh turns that manual operation into a repeatable process.
Choose a scheduler
PostgreSQL does not include a general-purpose built-in job scheduler. You can run refreshes from an external scheduler, such as cron, a systemd timer, or an orchestration platform. You can also use the PostgreSQL extension pg_cron.
| Option | Runs from | Best fit |
|---|---|---|
| System scheduler | Operating system or container | Simple jobs managed outside PostgreSQL |
| `pg_cron` | PostgreSQL server | Jobs that belong with database operations |
| Orchestrator | Deployment platform | Jobs needing retries, monitoring, and dependencies |
The scheduler should run a command that connects to the correct database and executes REFRESH MATERIALIZED VIEW.
Schedule a refresh with pg_cron
pg_cron is an extension that stores schedules in PostgreSQL and starts database sessions to run them. It must be installed by a database administrator, and the server usually needs pg_cron in shared_preload_libraries before the extension can be created.
After the administrator has configured the extension, create it in the database where the schedule should run:
CREATE EXTENSION IF NOT EXISTS pg_cron;The following job refreshes sales_daily every 15 minutes:
SELECT cron.schedule(
'refresh-sales-daily',
'*/15 * * * *',
'REFRESH MATERIALIZED VIEW CONCURRENTLY sales_daily'
);The five-part schedule uses this order:
- Minute
- Hour
- Day of the month
- Month
- Day of the week
The expression */15 * * * * means every 15 minutes. The command runs in the database configured for pg_cron. If the materialized view is in another database, configure the job's database explicitly or create the schedule in the appropriate database, depending on the pg_cron version and server setup.
CONCURRENTLY allows normal readers to continue using the existing contents while PostgreSQL builds the replacement contents. It requires a qualifying unique index on the materialized view:
CREATE UNIQUE INDEX sales_daily_day_idx
ON sales_daily (day);The indexed columns must uniquely identify every row. An index on day works here because the query produces one row per day.
Use an external scheduler
An operating-system scheduler can call psql. Store connection details in a secure environment, a password file, or a secret manager rather than placing a password in the command line.
For example, a shell script can run one refresh:
#!/usr/bin/env bash
set -euo pipefail
psql --dbname=reporting \
--command='REFRESH MATERIALIZED VIEW CONCURRENTLY sales_daily'A cron entry can run that script at five minutes past every hour:
5 * * * * /usr/local/bin/refresh-sales-dailyThe script exits with a failure status if psql fails. Configure the scheduler to capture standard error and alert on failures. Also record the refresh duration so that a job that once took two minutes does not silently grow beyond its schedule interval.
Avoid overlapping jobs
A refresh can take longer than the interval between scheduled starts. Overlapping refreshes waste resources and may fail because concurrent refreshes of the same materialized view cannot run at the same time.
Use one or more of these controls:
- Choose an interval longer than the normal refresh duration.
- Configure the scheduler to prevent overlapping runs.
- Use an advisory lock in a wrapper function or script.
- Monitor refresh duration and adjust the schedule as data volume grows.
A failed refresh should produce an alert. Until a successful refresh completes, readers continue to see the previous populated contents. This behavior makes a materialized view useful for reporting, but it also means the data can become stale without monitoring.
Exercise
A materialized view refresh normally takes 22 minutes. The current job runs every 15 minutes. What should you investigate or change?
Show answer
Prevent overlapping runs and choose a schedule that allows the refresh to finish. Also check whether the query, indexes, or refresh strategy can reduce the 22-minute duration.