State and background work
Defer small work with waitUntil
Keep a request response fast while allowing a short non-critical promise to continue through the execution context.
8 minute lesson
Some work should not delay the response, such as writing non-critical analytics or invalidating a cache after a successful authoritative write.
ctx.waitUntil() extends the lifetime of the request event for a promise. It is not a durable job queue and does not turn long or critical workflows into reliable background processing. Await work required for a correct response.
Pass the promise itself to waitUntil; merely starting an async function leaves its lifecycle untracked. Handle and log rejection with a request ID, because the client has already received a response and cannot be told that the follow-up failed.
The decision test is simple: if losing the work would make accepted data incorrect, create financial or user-visible inconsistency, or require retries, use a durable workflow such as a Queue. Cache invalidation and optional analytics can tolerate best-effort execution. Store the D1 row first, schedule invalidation second, and make stale cache data harmless if invalidation never completes.
Invalidate the recent-links cache with waitUntil only after D1 successfully creates a link.
Lesson completed