Skip to content

Keep Workers Up

Set up a pg_cron safety net that checks worker status and only starts new workers when needed, making workers spawning more predictable.

Edge Workers normally auto-respawn by sending their own HTTP requests. In rare cases during high load, workers may fail to respawn if they hit execution time limits before sending restart requests. Basic safety nets can cause Supabase’s Edge Runtime to spawn multiple workers simultaneously, leading to unpredictable costs.

This approach checks existing worker counts before spawning new ones:

  1. Create the safety net cron job

    Remember to change <your-worker-name> to name of your worker’s Edge Function and <YOUR_ANON_KEY> to match your project’s ANON key.

    SELECT cron.schedule(
    'watchdog--<your-worker-name>',
    '10 seconds',
    $$
    SELECT net.http_post(
    url := 'https://your-project.supabase.co/functions/v1/<your-worker-name>',
    headers := jsonb_build_object('Authorization', 'Bearer <YOUR_ANON_KEY>')
    ) AS request_id
    WHERE (
    SELECT COUNT(DISTINCT worker_id) FROM pgflow.workers
    WHERE function_name = '<your-worker-name>'
    AND last_heartbeat_at > NOW() - make_interval(secs => 6)
    ) < 1;
    $$
    );

Adjust the check interval based on your priorities:

'10 seconds' -- Fast recovery, higher quota usage
'30 seconds' -- Good balance (recommended)
'60 seconds' -- Slower recovery, minimal quota usage

To disable the safety net:

SELECT cron.unschedule('watchdog--<your-worker-name>');