Background Tasks
How to run background tasks in an Edge Function outside of the request handler
Edge Function instances can process background tasks outside of the request handler. Background tasks are useful for asynchronous operations like uploading a file to Storage, updating a database, or sending events to a logging service. You can respond to the request immediately and leave the task running in the background.
How long a background task can run
A background task can run until the Edge Function instance hits its wall-clock limit or reaches CPU/Memory limit. Check limits for current caps.
Example
Here's an example of defining a background task using a custom event.
_22// Define a custom event type for the background task._22class MyBackgroundTaskEvent extends Event {_22 readonly taskPromise: Promise<Response>_22_22 constructor(taskPromise: Promise<Response>) {_22 super('myBackgroundTask')_22 this.taskPromise = taskPromise_22 }_22}_22_22globalThis.addEventListener('myBackgroundTask', async (event) => {_22 const res = await (event as MyBackgroundTaskEvent).taskPromise_22 console.log(await res.json())_22})_22_22Deno.serve(async (req) => {_22 const fetchPromise = fetch('https://httpbin.org/json')_22 const event = new MyBackgroundTaskEvent(fetchPromise)_22 globalThis.dispatchEvent(event)_22_22 return new Response('ok')_22})
Testing background tasks locally
When testing Edge Functions locally with Supabase CLI, the instances are terminated automatically after a request is completed. This will prevent background tasks from running to completion.
To prevent that, you can update the supabase/config.toml
with the following settings:
_10[edge_runtime]_10policy = "per_worker"
When running with per_worker
policy, Function won't auto-reload on edits. You will need to manually restart it by running supabase functions serve
.