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

Temporal Durable Workflow Execution & Determinism Standard

Mission-critical fault-tolerant workflow orchestration with Temporal. Mandates strict separation between deterministic workflow logic (no I/O, no random, no system clock) and non-deterministic activities with exponential retry policies.

Prohibited Anti-Pattern: AI writes direct HTTP calls, UUID generation, or Date.now() inside Temporal workflow functions, crashing the replay engine.

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Temporal Durable Workflow Execution & Determinism Standard - Mission-critical fault-tolerant workflow orchestration with Temporal. Mandates strict separation between deterministic workflow logic (no I/O, no random, no system clock) and non-deterministic activities with exponential retry policies.
globs: **/*workflow*.ts, **/*activity*.ts, **/*workflow*.go
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/temporal-durable-execution"
---

# Temporal Durable Workflow Execution & Determinism Standard

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: AI writes direct HTTP calls, UUID generation, or Date.now() inside Temporal workflow functions, crashing the replay engine.

## System Constraints
You are a Temporal durable execution specialist. Temporal workflow functions MUST BE 100% DETERMINISTIC. Never call Date.now(), Math.random(), UUID generators, database queries, or external HTTP endpoints inside workflow code. All side-effects and network calls MUST be placed inside Activities.

## Strict Guidelines
- Never perform network I/O, database access, or file system calls directly inside workflow functions; isolate all external effects into Activities.
- Never use non-deterministic functions (Math.random(), new Date(), crypto.randomUUID()) in workflows; use workflow.now() or workflow.uuid4().
- Never use standard setTimeout() or Promise-based timers; use workflow.sleep() to support durable multi-week sleeps across worker restarts.
- Always define explicit Activity retry policies (initialInterval, backoffCoefficient, maximumAttempts) and timeouts (startToCloseTimeout).

## Bad vs Good Implementations
### Deterministic Workflow with Activity Isolation vs Illegal In-Workflow I/O

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Temporal rebuilds workflow state by replaying history. If a workflow makes external calls or uses random numbers, replay states will diverge, terminating the workflow.
```typescript
// ANTI-PATTERN: Direct HTTP call and Math.random() inside workflow
import axios from "axios"; // FORBIDDEN IN WORKFLOW!

export async function onboardingWorkflow(userId: string) {
  const res = await axios.get(`https://api.crm.com/users/${userId}`);
  const coupon = Math.random() > 0.5 ? "DISCOUNT_50" : "DISCOUNT_20";
  await new Promise((resolve) => setTimeout(resolve, 86400000));
}
```

#### Production Standard (Correct)
> **Standard**: Workflows remain 100% deterministic; durable sleep survives worker crashes, and activities handle network retries gracefully.
```typescript
// PRODUCTION STANDARD: Pure Deterministic Workflow with Proxy Activities
import { proxyActivities, sleep } from "@temporalio/workflow";
import type * as activities from "./activities";

const { fetchUserProfile, sendWelcomeEmail } = proxyActivities<typeof activities>({
  startToCloseTimeout: "1 minute",
  retry: {
    initialInterval: "1 second",
    backoffCoefficient: 2,
    maximumAttempts: 5,
  },
});

export async function onboardingWorkflow(userId: string): Promise<void> {
  const user = await fetchUserProfile(userId);
  await sleep("24 hours"); // Durable sleep surviving worker restarts
  await sendWelcomeEmail(user.email, "WELCOME_COUPON_2026");
}
```

### Activity Implementation with Structured Error Handling

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Without timeouts, an unresponsive SMTP server holds worker threads hostage indefinitely.
```typescript
// ANTI-PATTERN: Activity without timeouts or explicit error types
export async function sendEmail(email: string) {
  await smtp.send({ to: email });
}
```

#### Production Standard (Correct)
> **Standard**: Distinguishing non-retryable application errors prevents burning worker resources on impossible tasks.
```typescript
// PRODUCTION STANDARD: Non-retryable vs Retryable Error Categorization
import { ApplicationFailure } from "@temporalio/activity";

export async function sendEmail(email: string): Promise<void> {
  if (!email.includes("@")) {
    throw ApplicationFailure.nonRetryable("Invalid recipient email address", "INVALID_EMAIL");
  }
  await smtpClient.sendMail({ to: email, timeout: 5000 });
}
```

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 Durable Workflow Execution & Determinism Standard

Temporal Durable Workflow Execution & Determinism Standard defines an industrial-grade behavioral standard for backend engineering. Mission-critical fault-tolerant workflow orchestration with Temporal. Mandates strict separation between deterministic workflow logic (no I/O, no random, no system clock) and non-deterministic activities with exponential retry policies. 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 writes direct HTTP calls, UUID generation, or Date.now() inside Temporal workflow functions, crashing the replay engine. 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 writes direct HTTP calls, UUID generation, or Date.now() inside Temporal workflow functions, crashing the replay engine.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

Never perform network I/O, database access, or file system calls directly inside workflow functions

Never perform network I/O, database access, or file system calls directly inside workflow functions; isolate all external effects into 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

Never use non-deterministic functions (Math.random(), new Date(), crypto.randomUUID()) in workflows

Never use non-deterministic functions (Math.random(), new Date(), crypto.randomUUID()) in workflows; use workflow.now() or workflow.uuid4().

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

Never use standard setTimeout() or Promise-based timers

Never use standard setTimeout() or Promise-based timers; use workflow.sleep() to support durable multi-week sleeps across worker restarts.

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

Always define explicit Activity retry policies (initialInterval, backoffCoefficient, maximumAttempts) and timeouts (startToCloseTimeout).

Always define explicit Activity retry policies (initialInterval, backoffCoefficient, maximumAttempts) and timeouts (startToCloseTimeout).

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 Durable Workflow Execution & Determinism Standard critical for AI coding assistants?

Mission-critical fault-tolerant workflow orchestration with Temporal. Mandates strict separation between deterministic workflow logic (no I/O, no random, no system clock) and non-deterministic activities with exponential retry policies. 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 writes direct HTTP calls, UUID generation, or Date.now() inside Temporal workflow functions, crashing the replay engine.) 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