CtrlK
BlogDocsLog inGet started
Tessl Logo
PluginPublic

g14wxz/edge-function-background-orchestration

Orchestrates long-running Edge Function work via waitUntil, pg_cron, and pgmq patterns.

Quality

97%

Does it follow best practices?

Run evals on this skill

Adds up to 20 points to the overall score

View guide
SecuritybySnyk

Passed

No findings from the security scan

Overview
Quality
Evals
Security
Files

SKILL.mdskills/edge-function-background-orchestration/

name:
edge-function-background-orchestration
description:
Configures Edge Functions to use EdgeRuntime.waitUntil for background work while returning immediate 200 OK. Routes massive async workloads through pg_cron discovery and pgmq task queuing. Use when building background processing, async third-party calls, long-running edge function tasks, or webhook-driven pipelines.

Pre-Conditions

  • supabase-mcp-verification tile MUST be installed and passing.
  • The Supabase project MUST have Edge Functions enabled.
  • For massive-workload phases: the pgmq and pg_cron extensions MUST be enabled in the database.
  • The agent MUST have confirmed Deno deploy target is accessible via MCP.

Workload Decision Gate

Workload TypeCriteriaImplementation Path
Light background< 30 seconds, single external callPhase 2 — EdgeRuntime.waitUntil
Massive asyncBatch processing, fan-out, multi-step pipelinePhase 3 — pg_cron + pgmq

Execution Phases

Phase 1 -- Classify Workload

  1. Determine if the task is light background (< 30 seconds, single external call) or massive async (batch processing, fan-out, multi-step pipeline).
  2. Light background work MUST use EdgeRuntime.waitUntil → proceed to Phase 2.
  3. Massive async work MUST use pg_cron + pgmq → proceed to Phase 3. NEVER attempt massive workloads inside a single Edge Function invocation.

Phase 2 -- Implement waitUntil Pattern (Light Background)

  1. Structure the Edge Function to:
    • Parse and validate the request.
    • Spawn background work via EdgeRuntime.waitUntil(promise).
    • Return new Response(JSON.stringify({ status: "accepted" }), { status: 200 }) immediately.
  2. The background promise MUST include error handling with structured logging (console.error).
  3. NEVER await the background promise before returning the response.
  4. When complete → proceed to Phase 4 (Verification).

Complete example:

Deno.serve(async (req: Request): Promise<Response> => {
  const payload = await req.json();

  // Validate input before spawning background work
  if (!payload?.id) {
    return new Response(JSON.stringify({ error: "missing id" }), { status: 400 });
  }

  const backgroundWork = async () => {
    try {
      await fetch("https://example.com/api", {
        method: "POST",
        body: JSON.stringify(payload),
        headers: { "Content-Type": "application/json" },
      });
    } catch (err) {
      console.error("Background task failed", { id: payload.id, error: err });
    }
  };

  // Spawn without awaiting — response returns immediately
  EdgeRuntime.waitUntil(backgroundWork());

  return new Response(JSON.stringify({ status: "accepted" }), {
    status: 200,
    headers: { "Content-Type": "application/json" },
  });
});

Phase 3 -- Implement pg_cron + pgmq Pattern (Massive Async)

  1. Create a pgmq queue: SELECT pgmq.create('task_queue_name').
  2. Create an Edge Function (or database trigger) that sends messages to the queue: SELECT pgmq.send('task_queue_name', payload::jsonb).
  3. Create a pg_cron job that reads from the queue at a defined interval:
    • Use pgmq.read('task_queue_name', vt, qty) to claim messages.
    • Process each message and call pgmq.delete on success or pgmq.archive for audit.
  4. NEVER set pg_cron interval below 10 seconds for queue polling.
  5. When complete → proceed to Phase 4 (Verification).

Complete SQL example:

-- 1. Create the queue
SELECT pgmq.create('task_queue_name');

-- 2. Enqueue a message (from a trigger or Edge Function)
SELECT pgmq.send('task_queue_name', '{"id": 42, "action": "process"}'::jsonb);

-- 3. Schedule a pg_cron job to poll and process the queue every 30 seconds
SELECT cron.schedule(
  'poll-task-queue',        -- job name
  '30 seconds',             -- interval (minimum 10 seconds)
  $$
    DO $$
    DECLARE
      msg pgmq.message_record;
    BEGIN
      FOR msg IN
        SELECT * FROM pgmq.read('task_queue_name', 30, 10)
      LOOP
        RAISE NOTICE 'Processing message id=%', msg.msg_id;

        -- Delete on success; use pgmq.archive for audit trail
        PERFORM pgmq.delete('task_queue_name', msg.msg_id);
      END LOOP;
    END;
    $$ LANGUAGE plpgsql;
  $$
);

Phase 4 -- Verification Report

  1. Invoke the Edge Function and confirm a 200 OK is returned within 1 second.
  2. Confirm background work completes (check logs or database side-effects).
  3. For pgmq pattern: send a test message, wait for the cron cycle, confirm the message is consumed.
  4. Report pass/fail for each check. HALT if any check fails.

skills

edge-function-background-orchestration

tile.json