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.

Prerequisites

- Deployed Edge Worker function on Supabase.com
- pg_cron extension enabled in your Supabase project
- Your project’s ANON key (from Supabase Dashboard → Settings → API)

## The Problem

Section titled “The Problem”

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.

## Smart Safety Net Solution

Section titled “Smart Safety Net Solution”

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;  $$);

## Cron Frequency Options

Section titled “Cron Frequency Options”

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

Frequency Trade-offs

More frequent checks mean faster worker recovery but consume more HTTP requests and egress quota. Less frequent checks save quota but workers may stay down longer if they fail.

## Stopping the Safety Net

Section titled “Stopping the Safety Net”

To disable the safety net:

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