Scheduled Background Tasks with pg_cron & pgmq

Scheduled Background Tasks with pg_cron & pgmq in Supabase: Enterprise backends frequently require recurring maintenance tasks (e.g., purging expired sessions,…

Enterprise backends frequently require recurring maintenance tasks (e.g., purging expired sessions, recalculating analytics rollups, sending scheduled notifications). Rather than configuring external cron servers, Supabase integrates pg_cron and pgmq directly into PostgreSQL.


Scheduling SQL Jobs with pg_cron

pg_cron is an extension that runs cron jobs directly inside PostgreSQL using standard cron syntax:

-- Enable the extension
CREATE EXTENSION IF NOT EXISTS pg_cron;

-- Schedule a daily database cleanup at 03:00 AM UTC
SELECT cron.schedule(
    'purge-expired-sessions',
    '0 3 * * *', -- Standard 5-field cron syntax
    $$
        DELETE FROM user_sessions 
        WHERE expires_at < NOW() - INTERVAL '7 days';
    $$
);

-- Schedule an hourly analytics aggregation
SELECT cron.schedule(
    'rollup-hourly-metrics',
    '0 * * * *',
    $$
        INSERT INTO hourly_page_views (hour_bucket, view_count)
        SELECT 
            date_trunc('hour', viewed_at) AS hour_bucket,
            COUNT(*) AS view_count
        FROM telemetry_logs
        WHERE viewed_at >= NOW() - INTERVAL '1 hour'
        GROUP BY 1;
    $$
);

-- Inspect scheduled jobs and historical execution logs
SELECT * FROM cron.job;
SELECT * FROM cron.job_run_details ORDER BY start_time DESC LIMIT 10;

Asynchronous Message Queues with pgmq

pgmq provides lightweight, reliable message queues inside Postgres, eliminating the need for external tools like RabbitMQ or AWS SQS for simple task offloading:

-- Enable pgmq
CREATE EXTENSION IF NOT EXISTS pgmq;

-- 1. Create a queue
SELECT pgmq.create('email_delivery_queue');

-- 2. Enqueue a job payload
SELECT pgmq.send(
    queue_name => 'email_delivery_queue',
    msg => '{"to": "user@example.com", "template": "welcome", "user_id": 401}'::jsonb
);

-- 3. Read and lock messages for processing (with a 30-second visibility timeout)
SELECT * FROM pgmq.read(
    queue_name => 'email_delivery_queue',
    vt => 30, -- Visibility timeout: hidden from other workers for 30s
    qty => 10 -- Read up to 10 messages in batch
);

-- 4. Delete message after successful processing
SELECT pgmq.delete('email_delivery_queue', 1);

Exercises

  1. Schedule a pg_cron job that runs every Sunday at midnight to vacuum and re-index an active transactions table.
  2. Build an asynchronous email queue worker pattern utilizing pgmq and a Supabase Edge Function.
  3. Compare the resilience of database-backed queues against in-memory queues (like Redis) during server crashes.