This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
backendcritical PriorityID: temporal-io-deterministic-workflow

Temporal.io Workflow Code Determinism & Side Effect Isolation Standard

Production standard for Temporal.io distributed orchestrations. Mandates strict determinism inside workflow functions, strictly prohibiting Math.random(), Date.now(), mutable global variables, or direct network/database calls outside Temporal Activities.

Prohibited Anti-Pattern: AI calls Date.now() or fetch() directly inside a Temporal workflow function, causing non-deterministic replay crashes during worker upgrades.

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Temporal.io Workflow Code Determinism & Side Effect Isolation Standard - Production standard for Temporal.io distributed orchestrations. Mandates strict determinism inside workflow functions, strictly prohibiting Math.random(), Date.now(), mutable global variables, or direct network/database calls outside Temporal Activities.
globs: **/workflows/**/*.ts, **/workflow.py, **/workflows/**/*.go
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/temporal-io-deterministic-workflow"
---

# Temporal.io Workflow Code Determinism & Side Effect Isolation Standard

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: AI calls Date.now() or fetch() directly inside a Temporal workflow function, causing non-deterministic replay crashes during worker upgrades.

## System Constraints
You are a Temporal.io Distributed Systems and Workflow Architect. Temporal workflows rely on event history replay for fault tolerance. NEVER call non-deterministic APIs (Date.now(), Math.random(), UUID v4, or direct I/O) directly inside workflow definitions. All side-effects and non-deterministic logic MUST execute inside Temporal Activities or use workflow.now() / workflow.sleep().

## Strict Guidelines
- MUST NOT execute direct network I/O, database queries, or filesystem operations inside workflow functions (must delegate to Activities).
- MUST use workflow.now() or workflow.sleep() instead of Date.now() / setTimeout().
- MUST use workflow-safe determinism helpers for random numbers or UUID generation.
- MUST handle workflow versioning via patched() or workflow.patched() before altering in-flight control flow structures.

## Bad vs Good Implementations
### Deterministic Order Fulfillment Workflow in TypeScript

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Temporal replays the workflow function from the beginning when a worker reboots. Calling Date.now() or fetch() creates different values on replay, resulting in a fatal NonDeterministicWorkflowError.
```typescript
// FATAL: Non-deterministic operations crash Temporal workflow replay!
import { proxyActivities } from '@temporalio/workflow';

export async function orderWorkflow(orderId: string) {
  // REPLAY CRASH: Date.now() returns different millisecond on event replay!
  const startTime = Date.now(); 
  
  // REPLAY CRASH: Direct fetch call inside workflow violates determinism!
  await fetch(`https://api.stripe.com/charge/${orderId}`);
}
```

#### Production Standard (Correct)
> **Standard**: Delegates all network operations to managed Activities with automatic exponential retry policies, and uses now() and sleep() to maintain replay determinism.
```typescript
import { proxyActivities, sleep, now } from '@temporalio/workflow';
import type * as activities from './activities';

const { chargePayment, sendConfirmationEmail } = proxyActivities<typeof activities>({
  startToCloseTimeout: '1 minute',
  retry: {
    maximumAttempts: 5,
    backoffCoefficient: 2,
  },
});

export async function orderWorkflow(orderId: string, amount: number) {
  // 1. Deterministic timestamp recorded in event history
  const startedAt = now(); 

  // 2. Delegate all network I/O to durable Activity with retry policy
  const paymentResult = await chargePayment(orderId, amount);
  
  // 3. Durable deterministic sleep
  await sleep('1 hour');
  
  await sendConfirmationEmail(orderId);
  return { success: true, startedAt, txId: paymentResult.txId };
}
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Recommended Agent Skills (askills.dev)

Ready-to-use executable skill functions tailored to this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Temporal.io Workflow Code Determinism & Side Effect Isolation Standard

Temporal.io Workflow Code Determinism & Side Effect Isolation Standard defines an industrial-grade behavioral standard for backend engineering. Production standard for Temporal.io distributed orchestrations. Mandates strict determinism inside workflow functions, strictly prohibiting Math.random(), Date.now(), mutable global variables, or direct network/database calls outside Temporal Activities. Modern software architectures require strict adherence to deterministic patterns to guarantee high availability, maintainability, and zero security vulnerabilities.

Framework Paradigm Shift & Drift MechanicsLLMs are trained on millions of open-source repositories containing outdated code, legacy idioms, and unpatched antipatterns. When coding assistants generate implementations for this stack, they default to common statistical tokens: AI calls Date.now() or fetch() directly inside a Temporal workflow function, causing non-deterministic replay crashes during worker upgrades. Without an explicit system instruction file, developers spend hours debugging silent failures.
Failure Modes & Production Blast Radius

Hazard Analysis: What Breaks Without This Rule

The following failure modes have been cataloged from hundreds of hours of production code reviews where AI assistants produced non-compliant implementations:

Failure ModeAI Symptom (The Anti-Pattern)SeverityProduction Impact & Remedy
AI Hallucination & Deprecation DriftAI calls Date.now() or fetch() directly inside a Temporal workflow function, causing non-deterministic replay crashes during worker upgrades.Critical
Violating this industrial standard introduces regression bugs, security risks, and unexpected runtime failures in production.
Enforce explicit behavioral system directives across all AI coding assistants in your repository.
Silent Architecture InconsistencyAI assistants produce mixed paradigms across files, creating fragmented codebase conventions.Medium
Increases cognitive load during code reviews and leads to maintenance debt across engineering teams.
Pin project conventions in .cursor/rules, CLAUDE.md, and AGENTS.md so all team agents follow identical guardrails.
Architectural Directives in Detail

Step-by-Step Production Directives

Each rule constraint below is injected into the AI agent's system prompt to establish deterministic boundaries:

1

MUST NOT execute direct network I/O, database queries, or filesystem operations inside workflow functions (must delegate to Activities).

MUST NOT execute direct network I/O, database queries, or filesystem operations inside workflow functions (must delegate to Activities).

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
2

MUST use workflow.now() or workflow.sleep() instead of Date.now() / setTimeout().

MUST use workflow.now() or workflow.sleep() instead of Date.now() / setTimeout().

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
3

MUST use workflow-safe determinism helpers for random numbers or UUID generation.

MUST use workflow-safe determinism helpers for random numbers or UUID generation.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
4

MUST handle workflow versioning via patched() or workflow.patched() before altering in-flight control flow structures.

MUST handle workflow versioning via patched() or workflow.patched() before altering in-flight control flow structures.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
Technical Questions & Answers

Frequently Asked Technical Questions

Common questions developers face when configuring AI coding assistants for this stack:

Q:Why is Temporal.io Workflow Code Determinism & Side Effect Isolation Standard critical for AI coding assistants?

Production standard for Temporal.io distributed orchestrations. Mandates strict determinism inside workflow functions, strictly prohibiting Math.random(), Date.now(), mutable global variables, or direct network/database calls outside Temporal Activities. Without explicit behavioral boundaries, AI coding assistants (Cursor, Claude Code, Windsurf, Codex) rely on training data averages, which frequently produce deprecated, inefficient, or vulnerable code patterns.

Q:How does adopting this rule prevent AI hallucinations?

This rule explicitly declares what the AI must avoid (AI calls Date.now() or fetch() directly inside a Temporal workflow function, causing non-deterministic replay crashes during worker upgrades.) and prescribes verified positive examples. Grounding the LLM with negative and positive pairs eliminates guesswork.

Q:Which AI coding environments are supported?

This specification is multi-platform compatible: Cursor (.cursor/rules/*.mdc & .cursorrules), Anthropic Claude Code (CLAUDE.md), Windsurf (.windsurfrules), Codex / Cline (AGENTS.md), and GitHub Copilot (.github/copilot-instructions.md).

Q:Can I combine this rule with other technology stacks?

Yes. Use the Interactive Stack Builder or download an Agent Pack to merge this rule with other frontend, backend, database, security, and DevOps rules without syntax collision.

Open Specification · CC BY 4.0·Free for Personal, Team & Commercial In-Repo Use

Citation & Open Source Attribution Guidelines

This specification is licensed under Creative Commons Attribution 4.0 International (CC BY 4.0). You are completely free to adapt and share this rule in your workspace. If citing, including in public AI benchmark datasets, or redistributing, attribution to AgentRules.org is required.

1 Rule in Stack

Temporal.io