Wait until
waitUntil runs async work after your handler has returned. Use it for work the caller doesn't need to wait for: logging, analytics, cache invalidation, notifications.
Usage
import { waitUntil } from "@alienplatform/sdk"
app.post("/api/checkout", async c => {
const order = await processOrder(c.req)
waitUntil(
(async () => {
await analytics.track("order.completed", { orderId: order.id })
await cache.invalidate(`user:${order.userId}:orders`)
})(),
)
return c.json({ orderId: order.id, status: "confirmed" })
})The response returns right away. The task runs in the same process.
API
function waitUntil(promise: Promise<unknown>): voidPass a promise that has already started. Rejections are logged to stderr and never reach the caller, because the response has already been sent.
You can call it several times per request. Tasks are independent; one failing doesn't cancel the others.
Lifecycle
- Your handler calls
waitUntil. The task starts and the runtime counts it. - The response goes to the caller.
- The task keeps running while the instance is alive.
- On graceful shutdown, such as scale-down or a new version, the runtime asks the app to drain and waits up to 15 seconds for pending tasks before it stops.
How long an instance stays alive after a response depends on the cloud. Lambda can freeze the environment between invocations, and Cloud Run throttles CPU between requests. A task that is still running when the instance freezes continues when it thaws, or is lost if the instance is stopped.
When to use it
Good fit: logs, metrics, cache invalidation, notifications, audit entries that can be retried.
Not a fit: work that must finish before the caller sees a result, such as charging a card or writing a record the next request reads. Do that before you respond, or send it to a Queue.