Temporal Rust SDK
This crate contains a prerelease Rust SDK. The SDK is built on top of Core and provides a native Rust experience for writing Temporal workflows and activities.
⚠️ The SDK is under active development and should be considered prerelease. The API can and will continue to evolve.
Quick Start
Activities
Activities are defined using the #[activities] and #[activity] macros:
use activities;
use ;
use ;
Workflows
Workflows are defined using the #[workflow] and #[workflow_methods] macros:
use ;
use ;
use Duration;
Running a Worker
The simplest way to configure a connection is with environment variables and/or a temporal.toml
config file. See the envconfig module docs for supported variables and
the TOML format.
use ;
use ;
use ;
async
Workflows in detail
Workflows are the core abstraction in Temporal. They are defined as structs with associated methods:
#[init](optional) - Constructor that receives initial input#[run](required) - Main workflow logic, must be async#[signal]- Handlers for external signals (sync or async)#[query]- Read-only handlers for querying workflow state (must be sync)#[update]- Handlers that can mutate state and return a result (sync or async)
#[run], #[signal], #[query], and #[update] all accept an optional name parameter to specify the name of the method. If not specified, the name of the method will be used.
Sync signals and updates are able to mutate state directly. Async methods must mutate state through
the context with state() or state_mut().
Workflow Logic Constraints
Workflow code must be deterministic. This means:
- No direct I/O operations (use activities instead)
- No threading or random number generation
- No access to system time (use
ctx.workflow_time()instead) - No global mutable state
- Do not use
tokioorfuturesconcurrency primitives directly in workflow code. Many of them (e.g.tokio::select!,tokio::spawn,futures::select!) introduce nondeterministic behavior that will break workflow replay. Instead, use the deterministic wrappers provided intemporalio_sdk::workflows:select!— deterministic select (polls in declaration order)join!— deterministic join for a fixed number of futuresjoin_all— deterministic join for a dynamic collection of futures
Runtime Nondeterminism Detection
The Rust SDK includes a runtime nondeterminism detector that monitors async wake sources inside
workflow code. It is enabled by default and can be disabled via
WorkerOptions::detect_nondeterministic_futures(false).
How it works: The SDK tracks which async wake-ups originate from SDK-provided primitives (timers, activities, child workflows, etc.) versus external sources. When a non-SDK wake is detected, the workflow task is failed with a descriptive error.
What it catches:
tokio::time::sleep/tokio::time::interval-- usectx.timer()insteadtokio::net/tokio::fs/ any async IO -- perform IO in activities, not workflowstokio::spawn-- do not spawn tasks from workflow codestd::thread::spawnwith async channels -- all cross-thread wakes are flagged- Direct use of
tokio::syncchannels (oneshot, mpsc, watch) -- usectx.state_mut()+ctx.wait_condition()for inter-future coordination instead
Detection timing: Detection is based on observing non-SDK wake sources. Because these wakes fire asynchronously (e.g., a tokio timer fires after the activation that started it), the failure is typically reported on the next workflow task, not the one that introduced the nondeterministic code. The workflow task that started the operation completes normally; the subsequent task fails with the detection error. The server then retries from that point.
What it does NOT catch:
futures::select!withoutbiased-- randomizes poll order within a single poll. Useworkflows::select!orfutures::select! { biased; ... }for deterministic ordering- Any combinator that only affects the order in which ready futures are polled
- Purely synchronous nondeterminism (e.g.,
std::time::SystemTime::now(),rand::random())
Disabling detection: Set detect_nondeterministic_futures(false) on WorkerOptions. This may
be useful during migration or for advanced users who understand the determinism constraints and want
to use patterns that trigger false positives.
Timers
// Wait for a duration
ctx.timer.await;
Child Workflows
let started = ctx
.child_workflow
.await?;
let result = started.result.await?;
Continue-As-New
// To continue as new, use the workflow context helper and propagate the termination
ctx.continue_as_new?;
Patching (Versioning)
Use patching to safely evolve workflow logic:
if ctx.patched else
Nexus Operations
The SDK supports starting Nexus operations from a workflow:
let started = ctx.start_nexus_operation.await?;
Defining Nexus handlers will be added later.
Activities in detail
Use Activities to perform side effects like I/O operations, API calls, or any non-deterministic work.
Error Handling
Activities return Result<T, ActivityError> with the following error types:
ActivityError::Retryable- Transient failure, will be retriedActivityError::NonRetryable- Permanent failure, will not be retriedActivityError::Cancelled- Activity was cancelledActivityError::WillCompleteAsync- Activity will complete asynchronously
Local Activities
For short-lived activities that you want to run on the same worker as the workflow:
ctx.start_local_activity?.await?;
Cancellation
Workflows and activities support cancellation. Note that in an activity, you must regularly
heartbeat with ctx.record_heartbeat(...) to receive cancellations.
use select;
// In a workflow: wait for cancellation
let reason = ctx.cancelled.await;
// Race a timer against cancellation
select!
Worker Configuration
Workers can be configured with various options:
let worker_options = new
.max_cached_workflows // Workflow cache size
.workflow_task_poller_behavior // Polling configuration
.activity_task_poller_behavior
.graceful_shutdown_period
.register_activities
.
.build;
Using the Client
The temporalio_client crate provides a client for interacting with the Temporal service. You can
use it to start workflows and communicate with running workflows via signals, queries, and updates,
among other operations.
Connecting and Starting Workflows
use ;
async
Signals, Queries, and Updates
Once you have a workflow handle, you can interact with the running workflow:
use ;
use ;
// Get a handle to an existing workflow (or use one from start_workflow)
let handle = client.;
// --- Signals (fire-and-forget messages) ---
handle.signal.await?;
// --- Queries (read workflow state) ---
let values = handle
.query
.await?;
// --- Updates (modify state and get a result) ---
let values = handle
.execute_update
.await?;
// Start an update and wait for acceptance only
let update_handle = handle
.start_update
.await?;
update_handle.get_result.await?;
// --- Untyped interactions (when types aren't known at compile time) ---
let pc = serde_json;
handle
.signal
.await?;
// UntypedQuery and UntypedUpdate work similarly
Cancelling and Terminating Workflows
use ;
// Request cancellation (workflow can handle this gracefully)
handle.cancel.await?;
// Terminate immediately (workflow cannot intercept this)
handle.terminate.await?;
Listing Workflows
use ListWorkflowsOptions;
use StreamExt;
let mut stream = client.list_workflows;
while let Some = stream.next.await