SkillByAIOpen interactive version →

Lesson 17 / 25

Triggers, Webhooks and Cron

React to changes and run scheduled jobs.

Work that happens inside Postgres

Triggers run a function when rows change; a classic Supabase example creates a profiles row whenever a user appears in auth.users. Database Webhooks send an HTTP request on insert, update or delete (built on the pg_net extension), handy for calling an edge function. pg_cron schedules SQL jobs with cron syntax, such as nightly cleanup. Keep trigger functions short, because they run inside the writing transaction.

Profile on sign-up and a nightly job

SQL.

create or replace function public.handle_new_user()
returns trigger
language plpgsql
security definer
set search_path = ''
as $$
begin
  insert into public.profiles (id, display_name)
  values (new.id, new.raw_user_meta_data ->> 'full_name');
  return new;
end;
$$;

create trigger on_auth_user_created
  after insert on auth.users
  for each row execute function public.handle_new_user();

-- requires the pg_cron extension to be enabled
select cron.schedule(
  'purge-old-sessions',
  '0 3 * * *',
  $$ delete from public.app_sessions where expires_at < now() - interval '7 days' $$
);

Doorbells and alarm clocks

Triggers and webhooks are doorbells that ring when something arrives; pg_cron is an alarm clock that rings at fixed times.

Quick check: Which extension schedules recurring SQL jobs?

  • PostgREST
  • pgvector
  • pg_cron
  • pg_trgm
Answer

pg_cron — cron.schedule takes a cron expression and SQL.