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

Temporal Durable Execution Determinism and Virtual Clock Invariant

Enforces strict execution determinism across Temporal workflow definitions to prevent replay mismatch panics during worker redeployments. Prohibits native wall-clock queries, unseeded random number generation, raw socket/HTTP I/O, native timers, and unversioned control flow modifications within workflow contexts.

Prohibited Anti-Pattern: Leaking Native Wall Clocks, Unseeded Randomness, or Direct Network I/O Inside Temporal Workflows

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Temporal Durable Execution Determinism and Virtual Clock Invariant - Enforces strict execution determinism across Temporal workflow definitions to prevent replay mismatch panics during worker redeployments. Prohibits native wall-clock queries, unseeded random number generation, raw socket/HTTP I/O, native timers, and unversioned control flow modifications within workflow contexts.
globs: **/workflows/**/*.ts, **/workflows/**/*.js, **/temporal/**/*.ts, src/workflows/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/temporal-durable-execution-determinism-guardrail"
---

# Temporal Durable Execution Determinism and Virtual Clock Invariant

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Leaking Native Wall Clocks, Unseeded Randomness, or Direct Network I/O Inside Temporal Workflows

## System Constraints
You are a Principal Distributed Systems Architect enforcing absolute determinism inside Temporal Durable Workflows. Every workflow execution must reconstruct state precisely through event replay without diverging from its historical execution log. Reject all native network I/O, unseeded randomness, raw wall clocks, global mutable state, and unshielded structural changes.

## Strict Guidelines
- Engineers MUST ALWAYS isolate all network calls, file system I/O, and non-deterministic third-party APIs inside Temporal Activities, never inside Workflows.
- Engineers MUST ALWAYS use SDK-provided virtualized time routines (e.g., `workflow.sleep()` or SDK-intercepted `Date.now()`) rather than native asynchronous timers (`setTimeout`, `setInterval`).
- Engineers MUST ALWAYS guard any workflow code modifications or branch shifts on historical executions using `patched()` or `deprecatePatch()` to guarantee backward replay safety.
- Engineers MUST NOT invoke native pseudo-random generation (e.g., `Math.random()`, `crypto.randomUUID()`) inside workflow code; deterministic helpers such as `workflow.uuid4()` MUST be used instead.
- Code SHOULD avoid storing mutable state in module-scoped global variables across workflow invocations, as workers reuse isolates across replay contexts.
- Services MUST configure distinct task queues and activities with rigorous retry policies and timeouts rather than executing direct asynchronous promises inside workflows.
- Components NEVER execute raw thread/goroutine spawns or unbounded concurrency constructs without passing them through Temporal's deterministic orchestration schedulers.

## Bad vs Good Implementations
### Non-Deterministic I/O, Timers, and Randomness vs. Certified Temporal Workflow Primitives

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Direct HTTP calls via axios fail during worker crash replays because Temporal workflows cannot perform arbitrary network I/O. Using `crypto.randomUUID()` generates divergent strings upon history re-evaluation, causing a NonDeterministicWorkflowPolicy panic. Native `setTimeout` does not persist durable timers to Temporal Server, losing execution state on worker restart.
```typescript
import axios from 'axios';
import crypto from 'node:crypto';

// ANTI-PATTERN: Native I/O, native wall-clock/timers, and unseeded UUIDs violate replay determinism
export async function processOrderWorkflow(orderId: string, amount: number): Promise<void> {
  // 1. Non-deterministic UUID: will generate a different value on every replay
  const idempotencyKey = crypto.randomUUID();

  // 2. Direct external I/O: prohibited inside workflow function
  const fxResponse = await axios.get(`https://api.exchange.com/rates?base=USD`);
  const rate = fxResponse.data.rate;

  // 3. Native timer bypasses Temporal event history
  await new Promise((resolve) => setTimeout(resolve, 60000));

  // 4. Modifying branch logic without versioning breaks running historical executions
  if (amount > 1000) {
    await axios.post('https://audit.internal/log', { orderId, idempotencyKey });
  }
}
```

#### Production Standard (Correct)
> **Standard**: Network calls and external integrations are safely delegated to activities with durable timeouts and retries. Randomness uses `uuid4()` provided by the Temporal SDK, which relies on deterministic internal pseudo-random state recorded in event history. Native timers are replaced with durable `sleep()`, and structural changes use `patched()` to maintain backward replay compatibility across rolling updates.
```typescript
import {
  proxyActivities,
  sleep,
  patched,
  uuid4
} from '@temporalio/workflow';
import type * as activities from '../activities/order-activities';

// Invariant: Delegate all side effects and I/O to activities with explicit timeouts
const { fetchExchangeRate, recordAuditLog } = proxyActivities<typeof activities>({
  startToCloseTimeout: '30 seconds',
  retry: {
    initialInterval: '1 second',
    maximumAttempts: 5,
    backoffCoefficient: 2,
  },
});

export async function processOrderWorkflow(orderId: string, amount: number): Promise<void> {
  // 1. Deterministic SDK-provided UUID seeded by workflow run ID
  const idempotencyKey = uuid4();

  // 2. Network I/O scheduled and recorded in workflow history via activity
  const rate = await fetchExchangeRate('USD');

  // 3. Durable timer orchestrated by Temporal cluster, fully replay-safe
  await sleep('1 minute');

  // 4. Backward-compatible patch ensures older historical events do not panic on replay
  if (patched('high-value-audit-v1')) {
    if (amount > 1000) {
      await recordAuditLog({ orderId, idempotencyKey, rate });
    }
  }
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Temporal Durable Execution Determinism and Virtual Clock Invariant

Temporal Durable Execution Determinism and Virtual Clock Invariant defines an industrial-grade behavioral standard for backend engineering. Enforces strict execution determinism across Temporal workflow definitions to prevent replay mismatch panics during worker redeployments. Prohibits native wall-clock queries, unseeded random number generation, raw socket/HTTP I/O, native timers, and unversioned control flow modifications within workflow contexts. 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: Leaking Native Wall Clocks, Unseeded Randomness, or Direct Network I/O Inside Temporal Workflows 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 DriftLeaking Native Wall Clocks, Unseeded Randomness, or Direct Network I/O Inside Temporal WorkflowsCritical
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

Engineers MUST ALWAYS isolate all network calls, file system I/O, and non-deterministic third-party APIs inside Temporal Activities, never inside Workflows.

Engineers MUST ALWAYS isolate all network calls, file system I/O, and non-deterministic third-party APIs inside Temporal Activities, never inside Workflows.

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

Engineers MUST ALWAYS use SDK-provided virtualized time routines (e.g., `workflow.sleep()` or SDK-intercepted `Date.now()`) rather than native asynchronous timers (`setTimeout`, `setInterval`).

Engineers MUST ALWAYS use SDK-provided virtualized time routines (e.g., `workflow.sleep()` or SDK-intercepted `Date.now()`) rather than native asynchronous timers (`setTimeout`, `setInterval`).

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

Engineers MUST ALWAYS guard any workflow code modifications or branch shifts on historical executions using `patched()` or `deprecatePatch()` to guarantee backward replay safety.

Engineers MUST ALWAYS guard any workflow code modifications or branch shifts on historical executions using `patched()` or `deprecatePatch()` to guarantee backward replay safety.

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

Engineers MUST NOT invoke native pseudo-random generation (e.g., `Math.random()`, `crypto.randomUUID()`) inside workflow code

Engineers MUST NOT invoke native pseudo-random generation (e.g., `Math.random()`, `crypto.randomUUID()`) inside workflow code; deterministic helpers such as `workflow.uuid4()` MUST be used instead.

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.
5

Code SHOULD avoid storing mutable state in module-scoped global variables across workflow invocations, as workers reuse isolates across replay contexts.

Code SHOULD avoid storing mutable state in module-scoped global variables across workflow invocations, as workers reuse isolates across replay contexts.

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.
6

Services MUST configure distinct task queues and activities with rigorous retry policies and timeouts rather than executing direct asynchronous promises inside workflows.

Services MUST configure distinct task queues and activities with rigorous retry policies and timeouts rather than executing direct asynchronous promises inside workflows.

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.
7

Components NEVER execute raw thread/goroutine spawns or unbounded concurrency constructs without passing them through Temporal's deterministic orchestration schedulers.

Components NEVER execute raw thread/goroutine spawns or unbounded concurrency constructs without passing them through Temporal's deterministic orchestration schedulers.

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 Execution Determinism and Virtual Clock Invariant critical for AI coding assistants?

Enforces strict execution determinism across Temporal workflow definitions to prevent replay mismatch panics during worker redeployments. Prohibits native wall-clock queries, unseeded random number generation, raw socket/HTTP I/O, native timers, and unversioned control flow modifications within workflow contexts. 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 (Leaking Native Wall Clocks, Unseeded Randomness, or Direct Network I/O Inside Temporal Workflows) 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