Introducing a new way to review your PRs.

Read the announcement

reflex-dev / reflex

🕸️ Web apps in pure Python 🐍

View on GitHub

30 documents · Updated Nov 23, 2026

docs / workflow-orchestration

Workflow orchestration

Workflow orchestration gives a Reflex application durable control over work that must run later or react to an outside event. It stores each run in PostgreSQL, lets application code describe the next action, and uses workers to resume that action after a delay, a retry, a restart, or a process failure. The package requires Python 3.11 or newer.

Workflow model

Durable workflow runs

A workflow run is one application-owned SQLAlchemy row. The row holds business state and the workflow state that tells the engine whether the run is ready, delayed, waiting for an event, joining child runs, or finished. This keeps progress in the database instead of in a worker process.

The Workflow mixin supplies the durable behavior. A normal model defines its own identity and business columns, while the mixin reserves its own workflow columns for progress, retry state, waits, leases, and child coordination. An application that uses SQLAlchemy dataclasses uses the matching reflex_workflow.dataclass.Workflow form without changing the workflow model.

References: packages/…/model.py• L786-832 packages/…/dataclass.py• L46-85 packages/…/README.md• L74-78

Step transitions

A step is an async unit of work that receives the run row and returns a transition. The transition says what the run should do next, so application code describes a durable process as a sequence of state changes rather than as one long-lived task.

The main transition types are:

  • Another step for immediate work.
  • A delayed step for a later time.
  • An event wait with an optional timeout.
  • A repeating schedule.
  • A fan-out that starts child runs and joins them later.
  • No transition, which finishes the run.

Step arguments cross the persistence boundary as JSON. The system checks the target step and its arguments when the transition is created or delivered, before a worker tries to run it.

References: packages/…/model.py• L132-157 packages/…/model.py• L204-257 packages/…/model.py• L260-304

Work initiation

Run registration

Run registration creates a durable row and schedules its first step. The application can use the row's normal unique constraints to prevent duplicate runs, or select one unique column as the identity of an outside event.

Without a selected key, any unique-constraint clash means that no new run starts. With key=, a clash on that column returns False, which identifies a repeated event such as a resent webhook. A clash on another unique constraint raises the public RunConflict error instead. The selected key must be one column that is unique on its own, and a nullable key lets other kinds of starts leave it empty.

References: packages/…/model.py• L113-129 packages/…/model.py• L860-884 packages/…/handles.py• L47-92 packages/…/handles.py• L115-207 packages/…/README.md• L52-61 packages/…/__init__.py• L11-31

Scheduled work

Scheduled work is represented by a run whose next step has a due time. The same model supports a fixed interval and a function that computes the next time, such as the standard Cron schedule. A schedule remains active only while its step keeps returning the schedule successfully.

The schedule is a durable part of the run. A process restart does not lose it, and missed interval occurrences collapse into one later execution instead of creating a burst of old executions. A unique application key can make startup registration safe to repeat.

Cron uses five standard fields and a named time zone. It rejects malformed expressions and expressions that cannot fire, then returns the next matching instant for the worker to store.

References: packages/…/model.py• L229-250 packages/…/cron.py• L103-143 packages/…/execute.py• L141-192 packages/…/ex02_weekly_update.py• L47-109 packages/…/README.md• L180-238

Event-driven work

Event-driven work parks a run without holding a process or worker. The waiting step names the event channel, and a caller delivers a step call with the event data. The engine applies the event to runs that are waiting, or holds one event while a run is moving toward that wait.

A wait ends once. The event wins before its deadline, and the timeout path wins after it. A delivery key can make retries from a webhook or message source idempotent. If another event arrives while the accepted event is running, the engine holds it for the next wait instead of losing it; a second event that is still waiting to be taken is refused. A finished run rejects later events unless the caller explicitly asks to restart it.

The application boundary is the run handle: a Reflex event handler, webhook, or other caller can select runs and deliver an event, advance a run immediately, cancel it, or read its state. These actions change durable state and notify workers rather than running step code in the caller.

References: packages/…/model.py• L220-227 packages/…/handles.py• L292-453 packages/…/handles.py• L455-541 packages/…/execute.py• L262-308 packages/…/ex13_conversation.py• L492-551 packages/…/README.md• L117-178

Coordination patterns

Fan-out and joins

A fan-out turns one step into a set of independent child runs. Each child has its own row, worker claim, retry history, and failure state. The parent releases its worker while the children run, then resumes its join step after all children finish or give up.

This model supports batch work without keeping a request or process open. Unique keys on child rows prevent a repeated fan-out from starting the same child twice, and the parent counts a cancelled or exhausted child as finished so one failed item cannot leave the batch waiting forever.

The following flow shows the durable relationship between a parent run and its children.

flowchart LR
    A[Parent step] --> B[Create child runs]
    B --> C1[Child run 1]
    B --> C2[Child run 2]
    B --> C3[Child run 3]
    C1 --> D{All children finished?}
    C2 --> D
    C3 --> D
    D -->|yes| E[Parent join step]

References: packages/…/model.py• L204-218 packages/…/model.py• L464-497 packages/…/execute.py• L320-389 packages/…/README.md• L240-275

Limits and worker lanes

Workflow coordination can protect shared resources at two levels. A workflow limit groups runs by an application column and caps concurrent starts or start rate across all workers. A lane assigns a step to a class of worker, which keeps work such as browser or media processing away from general workers.

These controls shape fairness without changing the workflow definition. Groups that have reached a limit wait while other groups continue, and a step in an unserved lane remains durable work until a matching worker is available. Rate limits require the application to provide the shared bucket table used by the engine.

References: packages/…/model.py• L161-201 packages/…/model.py• L268-289 packages/…/claim.py• L317-439 packages/…/runner.py• L55-99 packages/…/README.md• L277-360

Application boundary

Reflex integration

Reflex applications use the workflow package beside their normal rx.Model models. Workflow models use a separate SQLAlchemy declarative base so step methods remain ordinary model behavior, and that base must be registered with Reflex migrations so the workflow tables and columns are part of the application schema.

The workflow engine uses an async session factory built from Reflex's async database engine. A web process can enter connect_workflows to start runs, deliver events, and read state without executing steps. A worker process enters run_workflows to claim and execute steps against the same database.

References: packages/…/README.md• L389-438 packages/…/runner.py• L371-439 packages/…/runner.py• L570-599

Worker coordination

Workers repeatedly claim due runs, execute a bounded number of steps, and commit the resulting state. Multiple processes can work from the same tables because a database lease and version protect each claimed run; a step that loses its claim cannot overwrite newer state.

The worker sleeps until the database says that work is due. A transaction that makes work ready can also notify other workers, which reduces wake-up delay without changing correctness because polling remains the fallback. An idle callback and the wake entry point let a deployment that suspends when idle register its next wake time and resume the worker when that time arrives. The worker can run without a listener when the database itself suspends, because its stored timers remain the source of truth.

The main system path is:

sequenceDiagram
    participant App as Reflex application
    participant DB as PostgreSQL
    participant Worker as Workflow worker
    participant Step as Step code

    App->>DB: Start, advance, or deliver event
    DB-->>Worker: Durable row and optional notification
    Worker->>DB: Claim due run with lease
    Worker->>Step: Run current step
    Step-->>Worker: Return next transition
    Worker->>DB: Commit state and next wake condition
    DB-->>Worker: Wake for later work or another event

References: packages/…/claim.py• L54-139 packages/…/execute.py• L667-838 packages/…/runner.py• L171-297 packages/…/runtime.py• L12-73 packages/…/README.md• L448-546

The workflow engine has four focused areas. Use the related workflow engine page as the entry point for the detailed child guides:

  • Claim: how workers select due work and protect claims.
  • Execution: how steps produce transitions and commits.
  • Persistence: how runs, attempts, schedules, and event state survive process changes.
  • Runtime coordination: how workers, application processes, notifications, and idle deployments interact.

References: packages/…/__init__.py• L1-13 packages/…/__init__.py• L3-61

Lifecycle guarantees

Retry and recovery

The engine gives each claimed step a lease and renews it while the step runs. If a worker stops, another worker can claim the run after the lease ends. A failed step can retry with increasing delay, then records its final error and stops when its retry budget is used.

The delivery model is at-least-once. A step can run again after a worker failure or lease expiry, so external effects must use provider idempotency keys or application constraints when repetition would be unsafe. A failed step body or refused state commit does not leave partial workflow changes behind.

References: packages/…/model.py• L260-289 packages/…/claim.py• L461-498 packages/…/execute.py• L210-259 packages/…/execute.py• L667-838 packages/…/README.md• L619-636

Change checklist

When these files or sections are changed, remember to consider these:

  • When workflow-owned columns or indexes change, update the Reflex migration path and the dataclass model in parallel with the normal model.
  • When a step name or signature changes, review persisted next-step data plus every event producer and schedule that addresses the step.
  • When a lane changes, review the worker deployment that serves it; work in an unserved lane remains pending by design.
  • When a workflow adds a rate limit, map one RateBucket table and include it in the same schema migration.
  • When a workflow model is added to a Reflex app, register its declarative base and use the workflow session factory rather than the SQLModel session factory.
  • When a run can repeat an external action, preserve an idempotency key or a database uniqueness rule across retries and lease recovery.
  • When an outside event can start a run, choose a single-column unique key= that identifies that event and handle RunConflict for clashes on other business keys.
  • When event handling changes, preserve the one-event wait contract: an accepted event must be processed once, and an event received during that step must remain available for the next wait.
  • When the runtime wake path changes, keep timer-based polling as the fallback for work written without a notification and for workers that cannot listen.

Important failure modes

TriggerConsequenceGuard
No worker serves a step's laneThe run stays pending and does not execute.Deploy a worker with the matching lane.
A step argument is not JSON-serializableThe transition is rejected before durable scheduling.Pass JSON-safe values or store the value in the run's business state.
A scheduled run reaches its retry limitThe run stops and the schedule ends with an error.Give the step enough retries and re-arm the run when recovery is safe.
A rate-limited workflow has no mapped RateBucket tableClaims for that workflow cannot enforce the declared rate.Map the bucket mixin and migrate it with the workflow schema.
A keyed start uses a column that is not independently uniqueThe start request is rejected before it can identify duplicate events.Use a single-column primary key, unique constraint, or non-partial unique index.
A keyed start clashes on another unique business constraintstart raises RunConflict instead of treating the row as a duplicate event.Handle the conflict or change the event key and business data.
A worker fails after an external side effect but before commitThe step can run again after its lease expires.Make the external operation idempotent.
A Reflex workflow base is not registered for migrationsThe database can lack workflow tables or engine columns.Register the base before generating and applying migrations.
A row is written directly without the workflow start or notification pathA worker may not see new work until its idle wait ends.Start runs through the workflow API or wake the worker after the write.
The package runs under Python 3.10 or olderThe package cannot be installed or supported.Use Python 3.11 or newer.

Key files

FileWhy to read it
packages/…/README.mdProduct-level examples for runs, events, schedules, fan-out, workers, Reflex integration, and guarantees.
packages/…/__init__.pyPublic workflow concepts and the application-facing API, including RunConflict.
packages/…/model.pyDurable run model, step transitions, schedules, limits, workflow addressing, and run-start conflict behavior.
packages/…/cron.pyTime-zone-aware cron behavior used by repeating workflows.
packages/…/handles.pyApplication actions that start, advance, deliver to, read, and cancel runs.
packages/…/claim.pyWorker claim rules, leases, limits, rate control, and next-due decisions.
packages/…/execute.pyStep invocation, transition handling, retries, child completion, and commits.
packages/…/runner.pyWorker lifecycle, concurrency, lanes, idle waits, shutdown, and Reflex process modes.
packages/…/runtime.pyShared worker state and the signal used by applications to wait for a worker pass.
packages/…/notify.pyCross-process wake-up behavior through PostgreSQL notifications.
packages/…/dataclass.pyWorkflow mixins for SQLAlchemy models that are dataclasses.
packages/…/ex02_weekly_update.pyA recurring report that shows durable schedule registration and time-based work.
packages/…/ex13_conversation.pyAn event-driven conversation that shows waits, reminders, retries, and related runs.