How Wait for Event Works
When you usecontext.waitForEvent() in your workflow, Upstash Workflow automatically pauses execution and waits for an external notification to resume.
This happens without keeping your serverless function running, making it cost-effective and reliable for event-driven workflows.
Each waiter has a timeout duration to wait for the event and then fires automatically.
Wait for Event timeouts have limits based on your pricing plan:
- Free: Maximum timeout of 7 days
- Pay-as-you-go: Maximum timeout of 1 year
- Fixed pricing: Custom timeouts (no limit)
Race Condition Between Wait and Notify
A race condition can occur whennotify is called before waitForEvent is executed.
In this scenario, the notification will be sent but no workflow will be waiting to receive it, causing the event to be lost.
Solutions
There are three ways to handle race conditions:- Use lookback with
workflowRunId(Recommended for targeted notifications) - Use Webhooks (Recommended for general use)
- Check and retry (Manual approach)
Option 1: Lookback with workflowRunId
When you know which specific workflow run should receive the notification, you can provide aworkflowRunId to enable lookback. The notification will be stored and delivered even if sent before waitForEvent:
Option 2: Use Webhooks
Webhooks have built-in lookback and are safer against timing issues for general event handling.Option 3: Check and Retry
Alternatively, you can check the response of thenotify operation and retry if needed:
Selecting an Event ID
When a workflow run waits on an event ID, it’s appended to a list of waiters for the event ID. When a notify request is sent, all workflow runs waiting for that event are notified sequentially. To avoid heavy notify operations, it’s recommended to use unique event IDs instead of generic ones. For example, instead of waiting onuser-sent-verification, wait the workflow on user-{userId}-sent-verification event.