Skip to main content

Pick First Pattern

View Markdown

Overview​

The Pick First pattern executes multiple Activities in parallel and returns the result of whichever completes first, then cancels the remaining Activities. It is suitable for racing multiple approaches to the same task, implementing timeout alternatives, or optimizing for fastest response when multiple options are available.

Problem​

In distributed systems, you often need Workflows that execute multiple Activities that can accomplish the same goal, return as soon as any one succeeds (fastest wins), cancel remaining Activities to avoid wasted resources, and handle scenarios where speed matters more than trying all options.

Without the Pick First pattern, you must wait for all Activities to complete even when only one result is needed, manually track which Activity finished first, implement complex cancellation logic for remaining Activities, and waste compute resources on Activities whose results will not be used.

Solution​

The Pick First pattern races multiple Activities simultaneously, captures the first result, then cancels remaining Activities using a cancellation mechanism provided by each SDK.

The following describes each step in the diagram:

  1. The Workflow starts three Activities in parallel using a shared cancellable context.
  2. The Workflow waits for the first Activity to complete.
  3. Activity 2 completes first. The Workflow captures its result.
  4. The Workflow cancels the shared context, which cancels Activities 1 and 3.

The following implementation shows the core pattern. The Workflow creates a cancellable context, starts two Activities, and captures the first result:

# workflows.py
import asyncio
from datetime import timedelta
from temporalio import workflow

with workflow.unsafe.imports_passed_through():
from activities import sample_activity

@workflow.defn
class PickFirstWorkflow:
@workflow.run
async def run(