Understanding Temporal's Event-Sourced Execution Model
Temporal records every step of a workflow as an immutable event in a history log. The workflow code itself is deterministic: it replays the entire history on every restart to reach the exact same state. This design eliminates the need for manual checkpointing or complex retry logic that typically plagues distributed systems.
When a workflow calls an activity, Temporal persists the activity task in a queue, executes it in a worker, and records the result (success, failure, or timeout) as an event. The workflow code never directly executes non-deterministic operations such as network calls, random number generation, or current time lookups. Instead, it uses Temporal primitives like proxyActivities, sleep, and random from the SDK that are backed by the event history.
The TypeScript SDK (v1.9 as of late 2024) builds on this model with strong typing for workflow signatures, activity interfaces, and payload codecs. A typical workflow history limit is 50,000 events before Temporal starts using continue-as-new to keep histories manageable. Exceeding this limit without continue-as-new triggers a workflow task failure.
Local Environment Setup with Docker Compose
Start by running a complete Temporal cluster locally using the official auto-setup image. Create a docker-compose.yml with the following services:
version: "3.8"
services:
temporal:
image: temporalio/auto-setup:1.24.0
ports:
- 7233:7233
environment:
- DB=postgresql
- DB_PORT=5432
- POSTGRES_USER=temporal
- POSTGRES_PW=temporal
- POSTGRES_SEEDS=postgres
postgres:
image: postgres:16
environment:
- POSTGRES_USER=temporal
- POSTGRES_PASSWORD=temporal
ports:
- 5432:5432
temporal-web:
image: temporalio/web:2.30.0
ports:
- 8080:8080
environment:
- TEMPORAL_GRPC_ENDPOINT=temporal:7233
After docker compose up, the Temporal Web UI is available at http://localhost:8080. The gRPC endpoint for workers and clients runs on port 7233. For production-like testing, enable TLS and namespace isolation early. The default namespace is default.
Defining Activities and Workflows
Activities contain the side-effectful code. They are regular async functions wrapped by the SDK. Workflows orchestrate activities and must remain deterministic.
Here is a complete example of an order processing workflow that demonstrates multiple patterns:
import { proxyActivities, defineSignal, defineQuery, setHandler, sleep } from '@temporalio/workflow';
import type * as activities from './activities';
const { chargeCustomer, reserveInventory, shipOrder, refundCustomer, releaseInventory } = proxyActivities<typeof activities>({
startToCloseTimeout: '5m',
retry: {
maximumAttempts: 3,
backoffCoefficient: 2.0,
initialInterval: '1s',
},
});
export const approveOrderSignal = defineSignal<[string]>('approveOrder');
export const orderStatusQuery = defineQuery<string>('orderStatus');
export async function OrderProcessingWorkflow(orderId: string, customerId: string, amount: number): Promise<string> {
let status = 'PENDING';
let approved = false;
setHandler(approveOrderSignal, (approvalReason: string) => {
approved = true;
status = `APPROVED: ${approvalReason}`;
});
setHandler(orderStatusQuery, () => status);
try {
await reserveInventory(orderId);
status = 'INVENTORY_RESERVED';
// Wait up to 24h for human approval using a signal
await sleep('24h');
if (!approved) {
throw new Error('Order not approved in time');
}
await chargeCustomer(customerId, amount);
status = 'PAYMENT_COMPLETED';
const trackingId = await shipOrder(orderId);
status = `SHIPPED:${trackingId}`;
return trackingId;
} catch (err) {
// Compensation saga runs in reverse order
if (status.includes('PAYMENT_COMPLETED')) {
await refundCustomer(customerId, amount);
}
if (status.includes('INVENTORY_RESERVED')) {
await releaseInventory(orderId);
}
throw err;
}
}
The proxyActivities call creates typed stubs with per-activity retry policies and timeouts. The saga compensation logic is explicit and runs only for steps that previously succeeded. This pattern avoids distributed transaction coordinators like 2PC.
Signal and Query Mechanics
Signals allow external systems to inject events into a running workflow. In the example above, approveOrderSignal lets an admin dashboard send approval after manual review. Signals are delivered exactly once and are recorded in the workflow history.
Queries provide read-only access to workflow state without advancing the workflow. orderStatusQuery can be called from a Next.js API route using the Temporal client:
import { Client } from '@temporalio/client';
const client = new Client();
const handle = client.workflow.getHandle('order-123');
const status = await handle.query(orderStatusQuery);
console.log(status);
Queries are useful for real-time dashboards. They execute against the latest replayed state without blocking the workflow. However, queries cannot be used during workflow replay if they depend on non-deterministic data.
Implementing the Saga Pattern with Compensation
The saga pattern manages long-running business transactions without locking resources. Each forward step has a corresponding compensating activity. Temporal guarantees that if a workflow fails, the compensation activities execute in reverse chronological order.
In the order example, releasing inventory only happens if inventory was reserved and a later step failed. The SDK does not automatically infer compensation order; developers must code the catch block carefully. A more robust approach uses a stack of compensation functions:
const compensations: Array<() => Promise<void>> = [];
try {
await reserveInventory(orderId);
compensations.push(() => releaseInventory(orderId));
await chargeCustomer(customerId, amount);
compensations.push(() => refundCustomer(customerId, amount));
// ... more steps
} catch (err) {
for (const compensation of compensations.reverse()) {
try {
await compensation();
} catch (compensationErr) {
// Log but do not throw - saga should not fail in compensation
console.error('Compensation failed:', compensationErr);
}
}
throw err;
}
This pattern scales to workflows with 10+ steps. Temporal's visibility into each compensation execution provides full auditability. Trade-off: each activity call adds roughly 200-800ms of latency due to task queuing and history persistence.
Testing Workflows Deterministically
The @temporalio/testing package provides a TestWorkflowEnvironment that mocks the Temporal server. Tests run in milliseconds because time can be fast-forwarded.
import { TestWorkflowEnvironment } from '@temporalio/testing';
import { Worker } from '@temporalio/worker';
test('order workflow succeeds with approval', async () => {
const env = await TestWorkflowEnvironment.create();
const worker = await Worker.create({
connection: env.connection,
workflowsPath: require.resolve('./workflows'),
activities: {
reserveInventory: async () => {},
chargeCustomer: async () => {},
shipOrder: async () => 'TRACK-999',
// mock other activities
},
});
await worker.runUntil(async () => {
const handle = await env.client.workflow.start('OrderProcessingWorkflow', {
args: ['order-123', 'cust-456', 99.99],
workflowId: 'test-order-123',
taskQueue: 'test',
});
// Fast-forward past the sleep
await env.sleep('25h');
await handle.signal(approveOrderSignal, 'Manual review passed');
const result = await handle.result();
expect(result).toBe('TRACK-999');
});
await env.teardown();
});
The test environment allows deterministic simulation of time, signals, and failures. Coverage of compensation paths is straightforward by throwing errors at specific points. Tests run in under 2 seconds even for workflows that sleep for days in production.
Integration Patterns with Next.js and Express
For Next.js applications, start workflows from Server Actions or API routes. Use a singleton Temporal client instance to avoid connection overhead:
// lib/temporal.ts
import { Client } from '@temporalio/client';
let client: Client | null = null;
export async function getTemporalClient(): Promise<Client> {
if (!client) {
client = new Client({
connection: {
address: process.env.TEMPORAL_ADDRESS || 'localhost:7233',
},
namespace: 'default',
});
}
return client;
}
Then in an API route:
export async function POST(request: Request) {
const { orderId, customerId, amount } = await request.json();
const client = await getTemporalClient();
const handle = await client.workflow.start('OrderProcessingWorkflow', {
args: [orderId, customerId, amount],
workflowId: `order-${orderId}`,
taskQueue: 'orders',
// Add search attributes for visibility
searchAttributes: {
OrderStatus: ['PENDING'],
},
});
return Response.json({ workflowId: handle.workflowId });
}
Long-running workflows survive Next.js cold starts and serverless function timeouts because execution lives in the Temporal cluster, not the web server.
Observability with Metrics, Tracing and Search Attributes
Temporal emits Prometheus metrics out of the box: temporal_workflow_task_execution_latency, temporal_activity_execution_latency, and temporal_workflow_completed. Configure the worker to report metrics:
const worker = await Worker.create({
metrics: {
prometheus: {
bindAddress: '0.0.0.0:9000',
},
},
// ... other options
});
For distributed tracing, the SDK supports OpenTelemetry. Set the OTEL_TRACES_EXPORTER environment variable and every workflow and activity automatically appears in Jaeger or Grafana Tempo with correct parent-child relationships.
Search attributes allow filtering workflows in the Temporal Web UI and CLI. Register custom attributes in your Temporal cluster (e.g., OrderStatus as Keyword, CustomerId as Keyword). Update them during workflow execution using upsertSearchAttributes. This enables queries like OrderStatus = 'PENDING' AND CustomerId = 'cust-456'.
Production Deployment: Self-Hosted vs Temporal Cloud
Self-hosted deployments require running Temporal server, a database (PostgreSQL, MySQL, or Cassandra), Elasticsearch for advanced visibility, and multiple workers. High availability needs at least three Temporal frontend instances and matching database replicas. Maintenance includes history archival configuration and regular PostgreSQL vacuuming.
Temporal Cloud abstracts this entirely. Pricing is based on active workflow executions, actions (workflow task, activity task, signal), and storage. As of 2024, the free tier includes 10,000 workflow actions per month. A typical order processing workflow consumes approximately 12-18 actions depending on signals and retries.
Workers in production should run in auto-scaling groups with task queue partitioning. Use multiple task queues for priority routing (e.g., orders-high, orders-low). Worker versioning (introduced in Temporal server 1.20+) allows zero-downtime deployment of workflow code changes by running old and new workflow definitions side-by-side until all old executions complete.
Performance Characteristics and Trade-offs
Each command a workflow issues (ScheduleActivity, Sleep, Signal, etc.) results in a workflow task. A typical task takes 50-300ms depending on cluster load and history size. For latency-sensitive operations, keep the number of commands per workflow low or use local activities (which execute in the worker process without task queuing but lose some durability guarantees).
Continue-as-new resets the workflow history after a set number of events. A common pattern is to continue-as-new every 1,000 events or after completing a business phase. The SDK provides continueAsNew with identical arguments to the original workflow.
Memory usage per worker scales with concurrent workflow executions because each open workflow keeps its state in memory during replay. Temporal recommends keeping workflow logic lightweight; move heavy computation to activities. The workflow.maxCachedWorkflows setting defaults to 1000 and should be tuned based on available RAM.
Determinism requirements create a learning curve. Common mistakes include using Date.now(), Math.random(), or external configuration inside workflows. The SDK throws DeterminismViolationError during replay when it detects such issues. Solution: use workflow.now() and workflow.random() instead.
Advanced Patterns: Child Workflows and Updates
Child workflows allow composition. A parent order workflow can start a fraud detection child workflow and wait for its result:
const fraudResult = await executeChild('FraudDetectionWorkflow', {
args: [orderId, customerId],
workflowId: `fraud-${orderId}`,
parentClosePolicy: 'TERMINATE',
});
Updates (added in Temporal 1.24) provide a safer, typed alternative to signals. Unlike signals, updates can return values and participate in validation logic before acceptance. Use updates when the caller needs a synchronous response from the workflow.
Namespace isolation is critical for multi-tenant SaaS applications. Each customer gets a dedicated namespace with its own rate limits and retention policies. Temporal Cloud supports up to hundreds of namespaces per account.
Error Handling and Retry Semantics
Temporal distinguishes between application errors and workflow task failures. Application errors (thrown from activities or workflows) are recorded in history and can trigger retries according to the retry policy. Workflow task failures (non-deterministic code, OOM, etc.) cause the workflow to pause until fixed.
Activity retry policies should be tuned per operation. Database operations might use:
retry: {
maximumAttempts: 5,
initialInterval: '500ms',
maximumInterval: '30s',
backoffCoefficient: 2,
nonRetryableErrorTypes: ['InvalidOrderError', 'ValidationError'],
}
Always classify errors correctly. Transient network errors should retry; business validation errors should not. The SDK allows passing custom error classes that serialize properly across the wire using a payload codec.
Versioning and Long-Running Workflow Evolution
Workflow definitions cannot change after an execution starts without breaking replay. Temporal's patching mechanism helps:
import { patch } from '@temporalio/workflow';
if (patch('add-approval-step', 1, 2)) {
// New code path with approval
await waitForApproval();
}
The patch ID and version numbers must remain stable. For larger changes, use workflow versioning with worker build IDs and compatible version sets in the Temporal namespace. This allows gradual migration of running workflows.
Long-running workflows (months or years) are common use cases: loan processing, subscription billing, and insurance claims. Temporal's history archival feature moves completed workflow histories to cheaper storage (S3, GCS) while keeping metadata searchable.
Security Considerations
Enable mTLS between workers and the Temporal server. Use separate certificates for each namespace when possible. Data passed to workflows and activities is encrypted at rest when using Temporal Cloud. For self-hosted setups, configure PostgreSQL encryption and network policies.
Sensitive data should not be stored in workflow history. Use the payloadCodec to encrypt PII before it reaches the Temporal server. The official @temporalio/encryption package provides AES-256-GCM encryption with key rotation support.
Workflow IDs should be meaningful and unique. Using UUIDv7 provides both uniqueness and time ordering. Rate-limit workflow starts per customer to prevent abuse.
When to Choose Temporal vs Alternatives
Temporal excels when you need exactly-once execution semantics, automatic retries with full state recovery, and the ability to update or query long-running processes. Alternatives like AWS Step Functions offer similar durability but with vendor lock-in and less expressive programming model (JSON-based state machines).
Camunda and Zeebe provide BPMN modeling but require learning a different paradigm. In-process solutions like BullMQ or Redis Streams lack the strong durability guarantees when the worker process crashes.
Measured across production systems, Temporal reduces engineering time spent on retry logic, saga coordination, and state persistence by approximately 60-70% compared to custom implementations, though this varies by team experience. The main cost is the operational complexity of running the Temporal cluster or the monthly bill from Temporal Cloud.
For teams already invested in TypeScript, the SDK provides excellent developer experience with full type safety from workflow definition through to signal and query handlers. The combination of deterministic execution, built-in observability, and explicit compensation logic makes Temporal a powerful foundation for complex business processes in startups and enterprises alike.
