# Temporal vs AWS Step Functions in 2026: Execution Guarantees, State Transition Pricing & Migration Pitfalls
Evaluating temporal vs step functions 2026 dictates system reliability, cloud expenditure, and developer velocity.
Summary: Choose Temporal for code-first sagas exceeding 5 million monthly executions where deterministic event replay, durable multi-year timers, and multi-cloud portability eliminate transition fees. Choose AWS Step Functions for serverless, AWS-native pipelines with low transition density (<5 steps per run) to eliminate control-plane management.
---
Architectural Paradigms: Code-as-Configuration vs. Declarative DSL
The core architectural divide between Temporal and AWS Step Functions centers on how developers model state transitions and orchestrate distributed systems.
Temporal: General-Purpose Programming as Durable Execution
Temporal executes workflow definitions authored directly in general-purpose languages—Go, TypeScript, Python, Java, or .NET. Application logic executes as standard imperative code: native for loops, try/catch/finally blocks, conditional branching, and concurrent asynchronous invocations (Promise.all or Go goroutines).
State is preserved implicitly within ordinary program variables. When a workflow pauses—awaiting an external human approval signal or a 30-day timer—the Temporal worker evicts the workflow state from memory. Upon resumption, Temporal re-instantiates the workflow function and replays its append-only event history through the deterministic code path. This instantly rebuilds the local call stack, variable values, and program counter without developer-managed state persistence.
AWS Step Functions: Declarative Amazon States Language (ASL)
AWS Step Functions enforces orchestration through a domain-specific declarative language: the Amazon States Language (ASL), structured as JSON or YAML documents. Each state machine is an explicit directed graph composed of discrete states: Task, Choice, Parallel, Map, Pass, Wait, Fail, and Succeed.
Data manipulation between states relies on JSONPath expressions or intrinsic functions (States.JsonMerge, States.ArrayContains, or modernized JSONata expressions). To execute arbitrary business logic, Step Functions delegates execution outward to external compute targets—primarily AWS Lambda functions, Amazon ECS tasks, or direct AWS SDK service integrations. State is explicitly transformed and serialized as a JSON document passed from the output of one state to the input of the next.
Developer Velocity and Local Ergonomics
Building complex sagas in ASL introduces distinct developer friction points:
- Expression Complexity: Complex data transformations require deep JSONPath gymnastics or intermediate Lambda functions whose sole purpose is data reshaping.
- Testing & Local Ergonomics: Validating an ASL state machine locally requires running the
amazon/aws-stepfunctions-localDocker container with custom mock configurations. Simulating asynchronous external callbacks or edge-case network partitions requires extensive mocking of AWS SDK responses. In contrast, Temporal provides@temporalio/testing, allowing complete test suites to run in-memory with millisecond-speed simulated time-skipping. - Refactoring & Code Reuse: Encapsulating reusable business rules across workflows requires managing nested state machines or sprawling CloudFormation/CDK constructs, whereas Temporal employs standard software packages, classes, and shared utility modules.
---
State Persistence & Deterministic Event Replay Mechanics
The durability guarantees of both platforms dictate how systems recover from infrastructure outages, worker crashes, and unhandled network partitions.
Temporal Event History Log
Temporal decouples orchestration compute from persistence. The Temporal server (managed via Temporal Cloud or self-hosted) maintains an append-only event history log backed by a transactional datastore (PostgreSQL, MySQL, Cassandra, or ScyllaDB):
1. When a workflow schedules an Activity (a unit of non-deterministic I/O), Temporal records an ActivityTaskScheduled event.
2. An external worker polls the task queue via long-polling gRPC, executes the network call, and reports an ActivityTaskCompleted event containing the serialized payload.
3. If a worker pod crashes mid-execution, another worker picks up the workflow task and replays the event history from the beginning. When it encounters the completed activity call, Temporal observes that ActivityTaskCompleted already exists in history. Instead of re-running the side effect, Temporal injects the recorded result immediately and advances to the next instruction.
This mechanism grants Temporal exactly-once execution semantics for workflow control logic and at-least-once semantics for activities, with fine-grained idempotency keys preventing duplicate external mutations.
AWS Step Functions State Machine Execution
Step Functions manages state transitions inside AWS's proprietary control plane:
- State transitions are committed to managed internal storage before invoking downstream targets.
- Step Functions Standard workflows offer strictly orchestrated at-most-once or at-least-once execution depending on the service integration pattern (
RequestResponse,RunAJob, orWaitForTaskToken). - Because Step Functions does not execute application code within the engine itself, it does not perform code-level replay. Instead, the engine processes the state machine graph deterministically by reading state outputs from previous transitions.
- In Express workflows, execution history is not persisted to an interactive console audit trail. Events stream directly to Amazon CloudWatch Logs, eliminating state transition fees at the expense of at-least-once execution guarantees and visual state recovery.
---
6-Criteria Architectural Comparison Matrix
The table below contrasts the two engines across core architecture, operational scaling, and engineering velocity dimensions.
| Dimension | Temporal (Self-Hosted / Cloud) | AWS Step Functions (Standard / Express) | Architectural Verdict |
|---|---|---|---|
| 1. Programming Model | Code-as-configuration (TypeScript, Go, Python, Java, .NET). Native loops, exceptions, typing. | Declarative JSON/YAML (Amazon States Language) with JSONPath / JSONata transformations. | Temporal: Eliminates DSL impedance mismatch; full support for IDE tooling, unit tests, and refactoring. |
| 2. State Persistence & Replay | Append-only event history log on PostgreSQL/Cassandra. Deterministic replay restores memory stack. | Proprietary AWS managed transition checkpoints; payloads forwarded as discrete JSON documents. | Temporal: Provides native in-memory variables across years of execution; Step Functions requires external state stores for complex data. |
| 3. Pricing & Scale Mechanics | Temporal Cloud: Consumption-based action metering ($25 per 1M Actions base rate) plus active storage and execution retention. Self-Hosted: EC2/EKS compute + DB storage infrastructure only. | Standard: $0.025 per 1,000 state transitions ($25/1M transitions). Express: $1.00/1M executions + duration ($0.00001667/GB-s). | Temporal: Substantial cost advantage for high-transition workflows; Step Functions Standard becomes cost-prohibitive at scale. |
| 4. Duration Limits & Timers | Unlimited multi-year execution with ContinueAsNew; durable timer scheduling across seconds to years (sub-second timing not guaranteed due to persistence latency). | Standard: 1-year hard execution limit. Express: 5-minute hard execution limit. | Temporal: Required for durable subscriptions, customer lifecycle journeys, and multi-month business processes. |
| 5. Asynchronous Signaling & Inspection | First-class Signals (push inputs async) and Queries (synchronous internal state inspection without event history persistence; billed as Actions in Temporal Cloud). | Task Token callbacks (.waitForTaskToken) via SQS/EventBridge, or polling loops against DynamoDB. | Temporal: Real-time state queries without database read overhead; bidirectional event steering. |
| 6. Multi-Cloud & Local Ergonomics | 100% cloud-agnostic. Runs on local machines (temporal server start-dev), Kubernetes, AWS, GCP, Azure. | Strictly locked to AWS IAM, EventBridge, CloudWatch, and AWS SDK integrations. Complex local container mocking. | Temporal: Zero vendor lock-in; identical execution environment on developer laptops, CI pipelines, and production clusters. |
| 7. Performance & Latency | High-throughput gRPC task dispatch via persistent worker long-polling; sticky execution memory caching avoids cold boots. | Synchronous checkpointing per state transition in Standard workflows; Express workflows achieve sub-second latency for transient runs. | Temporal: Lower end-to-end orchestration overhead for long-lived, multi-step pipelines; Step Functions Express excels for short-lived streaming events. |
| 8. Maintenance & Operational Burden | Self-Hosted: High (SRE required for DB clustering). Temporal Cloud: Low (fully managed control plane). | Zero control plane maintenance. AWS manages scaling, availability, and multi-AZ replication natively. | AWS Step Functions: Wins on operational simplicity for small engineering teams with no dedicated infrastructure staff. |
---
3-Year Total Cost of Ownership (TCO) Model
Evaluating durable execution engine total cost of ownership reveals fundamentally divergent pricing mechanics: AWS Step Functions Standard charges directly for every state transition, penalizing workflows with high step counts, retries, or loops. Temporal decouples the control plane, charging either by abstract Actions (Temporal Cloud) or standard compute infrastructure (Self-Hosted), regardless of internal state iterations. Navigating aws step functions state transition pricing limits is crucial when workflows scale beyond single-digit millions.
Baseline Benchmark Assumptions
To model enterprise scale accurately, we evaluate a standard distributed transaction workflow:
- Workflow Topology: 10 distinct state transitions per workflow execution (e.g., validate order, reserve stock, process authorization, capture payment, initiate shipment, send telemetry, notify customer, plus error checks).
- Payload Distribution: Average 15KB JSON payload per step; 3% of executions carry oversized document attachments requiring S3 Claim-Check handling.
- Compute Sizing: Downstream activity compute runs on equivalent EKS/EC2 worker pools or AWS Lambda instances across all architectures.
- DevOps Compensation: Enterprise DevOps/Site Reliability Engineer (SRE) fully burdened rate calculated at $180,000/year ($15,000/month), benchmarked against US Bureau of Labor Statistics (BLS) tech compensation data and industry salary benchmarks (such as Levels.fyi and Radford) for senior DevOps/SRE personnel (including base salary, health benefits, payroll taxes, and tooling overhead).
3-Year Cost Projection Matrix
| Workflows / Month | Transition / Action Volume | AWS Step Functions Standard | Temporal Cloud (List Price)* | Temporal Self-Hosted (EKS) |
|---|---|---|---|---|
| 5,000,000 | 50M Transitions / 60M Actions | $138,600 | $154,800 | $297,000 |
| 50,000,000 | 500M Transitions / 600M Actions | $1,134,000 | $1,195,200 | $954,000 |
| 250,000,000 | 2.5B Transitions / 3.0B Actions | $5,409,000 | $5,463,000 | $3,321,000 |
\Note: Temporal Cloud costs reflect published pay-as-you-go list pricing ($25 per 1M Actions). High-volume enterprise customers typically negotiate custom annual volume commitments or deploy self-hosted clusters on Kubernetes.*
Detailed Expense Breakdown by Scale Tier
Tier 1: 5 Million Workflows / Month (50M Monthly Transitions)
- AWS Step Functions Standard: State transitions cost $1,250/mo ($0.025/1k). S3 claim-checks and CloudWatch logs consume $350/mo. Downstream Lambda compute totals $1,500/mo. Allocating 0.05 DevOps FTE ($750/mo) brings monthly cost to $3,850 (3-Year Total: $138,600).
- Temporal Cloud: 60M billable Actions cost $1,500/mo at published list price ($25/1M Actions). Storage and active execution retention add $250/mo. Worker compute on EKS costs $1,800/mo. Allocating 0.05 DevOps FTE ($750/mo) brings monthly cost to $4,300 (3-Year Total: $154,800).
- Temporal Self-Hosted (EKS): EKS cluster nodes (3x
m6i.xlarge) and Amazon RDS PostgreSQL multi-AZ cost $1,200/mo. Worker compute costs $1,800/mo. Allocating 0.35 DevOps FTE ($5,250/mo) for cluster maintenance brings monthly cost to $8,250 (3-Year Total: $297,000).
Tier 2: 50 Million Workflows / Month (500M Monthly Transitions)
- AWS Step Functions Standard: Transition fees surge to $12,500/mo ($0.025/1k). S3 payload storage and CloudWatch logs cost $3,500/mo. Downstream compute scales to $14,000/mo. Allocating 0.10 DevOps FTE ($1,500/mo) brings monthly cost to $31,500 (3-Year Total: $1,134,000).
- Temporal Cloud: 600M billable Actions cost $15,000/mo at published list price ($25/1M Actions). Storage and active execution retention cost $2,200/mo. Worker compute costs $14,500/mo. Allocating 0.10 DevOps FTE ($1,500/mo) brings monthly cost to $33,200 (3-Year Total: $1,195,200).
- Temporal Self-Hosted (EKS): EKS control plane (6x
m6i.2xlarge) and Aurora PostgreSQL cost $4,500/mo. Worker compute costs $14,500/mo. Allocating 0.50 DevOps FTE ($7,500/mo) brings monthly cost to $26,500 (3-Year Total: $954,000).
Tier 3: 250 Million Workflows / Month (2.5B Monthly Transitions)
- AWS Step Functions Standard: Transition fees reach $62,500/mo ($2.25M over 3 years). S3 claim-checks and logging total $17,500/mo. Downstream compute consumes $68,000/mo. Allocating 0.15 DevOps FTE ($2,250/mo) brings monthly cost to $150,250 (3-Year Total: $5,409,000).
- Temporal Cloud: 3.0B billable Actions cost $75,000/mo at published list price ($25/1M Actions). Storage costs $9,500/mo. Worker compute costs $65,000/mo. Allocating 0.15 DevOps FTE ($2,250/mo) brings monthly cost to $151,750 (3-Year Total: $5,463,000).
- Temporal Self-Hosted (EKS): Clustered infrastructure totals $16,000/mo based on AWS Pricing Calculator estimates: 16x
c6i.4xlargeEC2 compute instances for Temporal History, Matching, and Frontend pods (~$7,940/mo at $0.68/hr on-demand in us-east-1) alongside a dedicated multi-AZ NVMe storage cluster (e.g., 6xi3en.2xlargenodes or managed ScyllaDB on provisioned IOPS gp3 volumes including inter-AZ data replication, totaling ~$8,060/mo). Worker compute costs $65,000/mo. Allocating 0.75 dedicated SRE FTE ($11,250/mo) brings monthly cost to $92,250 (3-Year Total: $3,321,000). Net 3-year savings versus Step Functions Standard: $2,088,000.
Strategic TCO Analysis
1. The Sub-5M Plateau: At low volume (<5M executions/month), AWS Step Functions Standard is economically superior. Self-hosting Temporal yields negative ROI due to baseline DevOps labor overhead ($189,000 over 3 years).
2. The 50M Parity Zone: At 50M monthly workflows, Step Functions Standard costs ($1.13M) converge with Temporal Cloud list pricing ($1.19M), while self-hosted Temporal ($954K) delivers a 16% cost reduction alongside code-first developer velocity.
3. The 250M Scale Inflection: In comparing temporal cloud vs step functions tco at 250M monthly workflows (2.5B transitions), Step Functions Standard incurs over $2.25M in raw transition surcharges. Self-hosted Temporal on EKS drops total 3-year expenditure to $3.32M—a net savings of $2,088,000 compared to Step Functions Standard, even after fully accounting for dedicated SRE salaries. While Temporal Cloud list pricing tracks closely to Step Functions list costs ($5.46M vs $5.41M), high-volume enterprises typically negotiate custom enterprise commitments or deploy self-hosted clusters on Kubernetes.
---
Asynchronous Signaling, Timers & Human-in-the-Loop Orchestration
Enterprise orchestrators must accommodate asynchronous human approvals, webhooks, and delayed external signals without consuming expensive polling resources.
First-Class Signals & Queries in Temporal
Temporal treats asynchronous external communication as a primary language construct:
- Signals: Asynchronous push messages delivered directly into a running workflow execution. A workflow exposes typed signal handlers via
defineSignal()and pauses until an event occurs usingcondition(() => isApproved, '7 days'). When a signal arrives, Temporal appends aWorkflowExecutionSignaledevent to the history log and immediately unblocks the listening thread. - Queries: Synchronous read-only calls (
defineQuery()) that inspect the internal memory state of a workflow execution (e.g., retrieving the current stage of an ongoing migration) without appending events to the history log or advancing the program counter. In self-hosted clusters, queries introduce zero database write persistence overhead; in Temporal Cloud, each query execution is metered as a billable Action. - Updates: A hybrid mechanism that synchronously validates an incoming request, mutates workflow state, and returns the updated state to the caller in a single round-trip.
Step Functions Callback Tokens & Polling
AWS Step Functions addresses asynchronous external pauses through two primary patterns:
1. Task Token Callbacks (`.waitForTaskToken`): A task state invokes an external service (e.g., publishes to Amazon SQS or invokes an SNS topic), appending an opaque generated token (TaskToken) to the message. The state machine pauses indefinitely (up to 1 year). The external system must capture this token, store it in an external datastore (such as Amazon DynamoDB), and eventually issue an AWS SDK API call (SendTaskSuccess or SendTaskFailure).
2. EventBridge & Polling Loops: Alternately, workflows enter a Wait state, followed by a Task that checks DynamoDB for an approval record, looping back if not approved. Each iteration consumes transitions ($0.025 per 1,000), generating significant recurring cost.
Step Functions lacks any native mechanism equivalent to Temporal Queries; inspecting the internal intermediate state of an active execution requires externalizing state changes to Amazon DynamoDB or parsing raw CloudWatch logs.
---
Migration Failure Modes: 4 Critical Edge Cases
Analyzing migrating step functions to temporal failure modes reveals fundamental shifts in execution domains. Engineering teams that treat Temporal workflows like standard procedural code routinely trigger severe outages during migration cutovers.
1. Non-Deterministic Code Execution & Replay Desynchronization
- Root Cause: Temporal workers reconstruct workflow state by replaying code against historical event logs. The workflow function must be 100% deterministic. If developers use native system calls—such as
Date.now(),Math.random(),crypto.randomUUID(), reading process environment variables, or executing raw database queries inside the workflow definition—the values generated during replay diverge from the recorded history. - Production Symptom: Temporal throws
NonDeterministicWorkflowErrororWorkflowExecutionFailed. The worker abruptly terminates the workflow task, placing the execution in a stuck state that cannot advance. - Engineering Remediation:
- Isolate all non-deterministic logic and I/O inside Activities.
- Utilize Temporal's deterministic runtime primitives: workflow.now(), workflow.uuid4(), and workflow.sleep().
- Enforce static analysis across CI/CD pipelines using @temporalio/eslint-plugin-workflow.
2. The 256KB Payload Ceiling & Claim-Check Cutover Hazards
- Root Cause: AWS Step Functions enforces a strict 256KB maximum payload size for state inputs, state outputs, and execution history. In contrast, Temporal recommends workflow payloads remain under 2MB to preserve low latency and avoid event history bloat, backed by a default gRPC transport limit of 4MB across server and SDK configurations. During phased hybrid migrations—where Step Functions invokes Temporal or vice versa via message buses—teams often pass rich entity graphs or document arrays that exceed 256KB.
- Production Symptom: Step Functions throws
States.DataLimitExceeded, failing the state machine immediately without triggering standard retry blocks. - Engineering Remediation:
- Implement the Claim-Check Pattern. Store raw payloads exceeding 100KB in Amazon S3, passing only an S3 URI, SHA-256 hash, and payload schema version across state transitions.
- In Temporal, configure an end-to-end PayloadCodec on client and worker data converters to automatically compress (Gzip/Snappy) or offload large payloads to S3 transparently to the application logic.
3. Unhandled Event History Growth Exceeding 51,200 Events
- Root Cause: While AWS Step Functions Standard executions support up to 25,000 events before terminating with an execution failure, Temporal's server engine enforces a warning threshold at 10,240 events (
history_count_warnor 10MBhistory_size_warn) and a hard termination limit at 51,200 events (history_count_limitor 50MBhistory_size_limit). In long-running subscriptions, perpetual polling loops, or high-frequency IoT ingest workflows, appending activity tasks without compaction causes the event history log to grow monotonically. - Production Symptom: Temporal issues warning logs upon crossing 10,240 events. As history approaches the 51,200-event hard limit, worker memory consumption spikes during replay, orchestration latency increases, and the server forcibly terminates the execution with an engine history limit error.
- Engineering Remediation:
- Implement workflow.continueAsNew(). This primitive atomically commits current state, terminates the active execution history, and spins up a fresh workflow run inheriting accumulated state.
- Establish a hard threshold: trigger continueAsNew well before reaching warning levels—recommended every 2,000 iterations or whenever workflowInfo().historyLength > 2000.
4. Activity Timeout Misconfigurations & Worker Pool Starvation
- Root Cause: Step Functions developers accustomed to AWS Lambda's 15-minute global timeout often migrate to Temporal and define activities with only a
ScheduleToCloseTimeout(e.g., 2 hours) while omittingStartToCloseTimeoutandHeartbeatTimeout. - Production Symptom: If an activity worker encounters an out-of-memory crash, power loss, or unhandled socket hang while processing a task, Temporal cannot distinguish between an active long-running computation and a dead worker. The activity remains locked until the entire 2-hour
ScheduleToCloseTimeoutelapses. Worker queues saturate with zombie tasks, starving healthy workers and creating severe thundering-herd spikes upon recovery. - Engineering Remediation:
- Always enforce StartToCloseTimeout (the maximum duration of a single execution attempt, e.g., 30 seconds).
- For operations lasting longer than a few seconds, implement activity.Context.Heartbeat() within the activity implementation and configure HeartbeatTimeout: '10s'.
- Configure exponential backoff retry policies with strict jitter on all activity definitions.
---
Event-Driven Saga Architecture: Order Fulfillment Blueprint
The distributed saga orchestration pattern coordinates microservices transactions by executing compensating actions in reverse order upon encountering irrecoverable failures.
sequenceDiagram
autonumber
participant Client
participant Orchestrator as Temporal Workflow (Saga)
participant Inventory as Inventory Service
participant Payment as Payment Gateway
participant Shipping as Shipping Carrier
participant DeadLetter as Compensation Store
Client->>Orchestrator: Start Order (OrderID, Amount, SKU)
activate Orchestrator
Orchestrator->>Inventory: Activity: ReserveInventory(SKU, Qty)
Inventory-->>Orchestrator: Success (ReservationID)
Note over Orchestrator: Registered Compensation: ReleaseInventory()
Orchestrator->>Payment: Activity: AuthorizeAndCapture(Amount)
Payment-->>Orchestrator: Success (TransactionID)
Note over Orchestrator: Registered Compensation: RefundPayment()
Orchestrator->>Shipping: Activity: CreateShipmentLabel(Address)
Shipping-->>Orchestrator: Failure: Carrier API 503 Outage (Retries Exhausted)
Note over Orchestrator: SAGA FAILURE TRIGGERED - BEGIN COMPENSATIONS
rect rgb(255, 230, 230)
Orchestrator->>Payment: Compensate: RefundPayment(TransactionID)
Payment-->>Orchestrator: Refund Confirmed
Orchestrator->>Inventory: Compensate: ReleaseInventory(ReservationID)
Inventory-->>Orchestrator: Stock Restored
end
Orchestrator->>DeadLetter: Activity: RecordFailedOrderAudit()
DeadLetter-->>Orchestrator: Audit Committed
Orchestrator-->>Client: Workflow Failed (OrderCancelledException)
deactivate Orchestrator---
Production-Grade TypeScript Deterministic Workflow
Below is an enterprise-grade Temporal workflow demonstrating deterministic workflow execution for a multi-step distributed saga with deterministic signaling, queryable intermediate state, explicit activity timeouts, and continueAsNew history compaction.
import {
proxyActivities,
defineSignal,
defineQuery,
setHandler,
workflowInfo,
continueAsNew,
ApplicationFailure
} from '@temporalio/workflow';
import type * as activities from './activities';
// Define typed Activity Proxies with strict timeouts
const {
reserveInventory,
releaseInventory,
processPayment,
refundPayment,
generateShipmentLabel,
emitAuditTelemetry
} = proxyActivities<typeof activities>({
startToCloseTimeout: '30 seconds',
heartbeatTimeout: '10 seconds',
retry: {
initialInterval: '1 second',
backoffCoefficient: 2,
maximumInterval: '30 seconds',
maximumAttempts: 3,
nonRetryableErrorTypes: ['PaymentDeclinedError', 'InvalidInventorySkuError']
}
});
// Signals & Queries Definitions
export const cancelOrderSignal = defineSignal<[string]>('cancelOrder');
export const orderStatusQuery = defineQuery<OrderStatus, []>('orderStatus');
export interface OrderInput {
orderId: string;
customerId: string;
sku: string;
quantity: number;
amountCents: number;
iterationCount?: number;
}
export interface OrderStatus {
stage: 'INITIALIZING' | 'INVENTORY_RESERVED' | 'PAYMENT_CAPTURED' | 'COMPLETED' | 'COMPENSATED';
reservationId?: string;
paymentId?: string;
shipmentTrackingId?: string;
cancellationReason?: string;
}
export async function orderFulfillmentWorkflow(input: OrderInput): Promise<string> {
const compensations: Array<() => Promise<void>> = [];
const status: OrderStatus = { stage: 'INITIALIZING' };
let isCancelled = false;
let cancelReason = '';
// Register Query Handler: Reads in-memory variable without appending history events
setHandler(orderStatusQuery, () => status);
// Register Signal Handler: Asynchronous external steering
setHandler(cancelOrderSignal, (reason: string) => {
isCancelled = true;
cancelReason = reason;
});
try {
// Stage 1: Inventory Reservation
const reservation = await reserveInventory({
orderId: input.orderId,
sku: input.sku,
quantity: input.quantity
});
status.reservationId = reservation.reservationId;
status.stage = 'INVENTORY_RESERVED';
// Register compensating action in reverse order
compensations.push(async () => {
await releaseInventory({ reservationId: reservation.reservationId });
});
// Handle asynchronous cancellation signal during processing
if (isCancelled) {
throw new ApplicationFailure(`Order cancelled by user: ${cancelReason}`);
}
// Stage 2: Payment Capture
const payment = await processPayment({
orderId: input.orderId,
amountCents: input.amountCents,
customerId: input.customerId
});
status.paymentId = payment.transactionId;
status.stage = 'PAYMENT_CAPTURED';
compensations.push(async () => {
await refundPayment({ transactionId: payment.transactionId });
});
// Check history limit for long-lived workflows / continuous recurring loops
const currentIteration = input.iterationCount ?? 1;
if (workflowInfo().historyLength > 2000) {
await continueAsNew<typeof orderFulfillmentWorkflow>({
...input,
iterationCount: currentIteration + 1
});
}
// Stage 3: Shipment Label Generation
const shipment = await generateShipmentLabel({
orderId: input.orderId,
reservationId: reservation.reservationId
});
status.shipmentTrackingId = shipment.trackingNumber;
status.stage = 'COMPLETED';
await emitAuditTelemetry({
orderId: input.orderId,
status: 'SUCCESS',
trackingId: shipment.trackingNumber
});
return shipment.trackingNumber;
} catch (err: unknown) {
// SAGA ROLLBACK: Execute compensations in LIFO order
status.stage = 'COMPENSATED';
status.cancellationReason = err instanceof Error ? err.message : 'Unknown error';
for (const compensate of compensations.reverse()) {
try {
await compensate();
} catch (compensationError) {
await emitAuditTelemetry({
orderId: input.orderId,
status: 'COMPENSATION_CRITICAL_FAILURE',
error: String(compensationError)
});
}
}
throw new ApplicationFailure(
`Saga execution aborted. Rolled back successfully. Cause: ${status.cancellationReason}`
);
}
}---
Architectural Falsifiability: How to Verify System Failure
An orchestration architecture has objectively failed if any of the following conditions persist in production:
1. Replay Desynchronization Rate > 0.001%: More than 1 in 100,000 Temporal workflow tasks fails with NonDeterministicWorkflowError, indicating unisolated side effects or unversioned workflow definitions.
2. State Transition Bill Exceeds 35% of Total Cloud Compute: In AWS Step Functions, state transition charges outpace the actual compute (Lambda/ECS) costs executing the underlying tasks.
3. Payload Cutover Abort Rate > 0%: State machines terminate with States.DataLimitExceeded during peak traffic, demonstrating absence of the claim-check pattern for large JSON documents.
4. Worker Recovery Delay Exceeding 30 Seconds: An activity worker failure leaves tasks locked without heartbeats, blocking task queues and delaying recovery beyond SLA thresholds.
---
Strategic Decision Verdict & Advisory CTA
When architecting distributed enterprise systems in 2026:
- Select AWS Step Functions if your workload runs fewer than 5 million monthly workflows, executes primarily on AWS Lambda/DynamoDB, and your team lacks dedicated infrastructure engineering capacity.
- Select Temporal (Cloud or Self-Hosted) if your workflows represent core business domain sagas, require complex branching and compensation logic, exceed 50 million monthly state transitions, or must operate across multi-cloud environments.
For organizations evaluating complex distributed architectures, Wise Hustlers provides custom software engineering advisory to assist engineering leadership in benchmarking throughput requirements, refactoring ASL state machines into deterministic code, and building high-scale distributed systems.
---
Frequently Asked Questions
When should an enterprise choose AWS Step Functions over Temporal?
AWS Step Functions is the optimal choice for organizations with modest monthly execution volumes (<5M runs/month) whose architecture is deeply embedded within the AWS ecosystem. If your state machines consist of simple, linear pipelines coordinating AWS Lambda, DynamoDB, and SNS, Step Functions eliminates the operational overhead of managing external workers or paying base cluster infrastructure costs.
How does Temporal guarantee exactly-once execution semantics if worker processes crash?
Temporal decouples orchestration logic from activity side effects using an append-only event history log. When a worker node crashes mid-execution, another worker assumes the workflow task and replays the code deterministically. Because previously completed activities are already committed to the history log, Temporal intercepts those calls and returns the historical result without re-executing external network requests, preserving exactly-once execution flow.
Can Step Functions Express Workflows replace Temporal for high-throughput microservices?
Step Functions Express Workflows significantly lower execution costs ($1.00 per 1M requests plus duration-based memory charges) compared to Standard workflows, making them suitable for high-volume streaming ingest. However, Express workflows enforce a 5-minute maximum execution duration, provide at-least-once rather than exactly-once execution guarantees, lack native human-in-the-loop callback capabilities, and do not persist interactive visual execution histories in the console. For complex, long-running business sagas, Express workflows cannot substitute for Temporal.
What is the operational burden of self-hosting Temporal versus adopting Temporal Cloud?
Self-hosting Temporal requires configuring and managing a distributed cluster comprising Frontend, History, Matching, and Internal Worker services backed by a high-availability Cassandra, ScyllaDB, or PostgreSQL database. At scales exceeding 50 million monthly executions, this demands dedicated SRE capacity (0.5 to 0.8 FTE) for database shard tuning, history compaction, and version upgrades. Temporal Cloud abstracts this control-plane burden entirely, providing a contractually backed 99.9% availability SLA (with 99.99% availability design objectives in multi-region deployments) and action-based metering that eliminates internal cluster management.
---
References & Primary Sources
- Temporal Documentation: Durable Execution Model - Official architecture specifications for event history logs, activities, and deterministic replay.
- Temporal Cloud Pricing - Official consumption-based action metering rates, active execution retention, and storage pricing.
- Temporal Server Default Limits - Technical specifications for the 10,240 event warning threshold, 51,200 event hard termination limit, and payload sizing guidelines.
- AWS Step Functions Pricing - Official pricing mechanics for Standard state transitions and Express workflow duration.
- AWS Step Functions Quotas and Limits - Technical documentation on the 256KB payload limit and execution history constraints.
- Amazon States Language (ASL) Specification - State machine schema definitions, task dispatch patterns, and intrinsic functions.
- AWS Pricing Calculator - Official cost model estimates for Amazon EC2 compute instances and EBS/IOPS provisioning.
- U.S. Bureau of Labor Statistics: Computer and Information Technology Occupations - Benchmark compensation data for systems infrastructure and Site Reliability Engineers.