This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
securitycritical PriorityID: openfga-temporal-dual-write-barrier

Deterministic Temporal Saga Barrier for OpenFGA Authorization Tuples

Prohibits direct, uncoordinated dual-writes between primary application datastores and OpenFGA relationship-based access control (ReBAC) stores. Enforces deterministic Temporal sagas with idempotent tuple synchronization, explicit compensation boundaries, and transactional outbox guarantees to eliminate authorization drift windows.

Prohibited Anti-Pattern: Non-Transactional Inline Tuples Dual-Writing and Fire-and-Forget ReBAC Mutation

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Deterministic Temporal Saga Barrier for OpenFGA Authorization Tuples - Prohibits direct, uncoordinated dual-writes between primary application datastores and OpenFGA relationship-based access control (ReBAC) stores. Enforces deterministic Temporal sagas with idempotent tuple synchronization, explicit compensation boundaries, and transactional outbox guarantees to eliminate authorization drift windows.
globs: src/workflows/**/*.{ts,tsx}, src/activities/**/*.{ts,tsx}, src/services/**/*.{ts,tsx}, src/handlers/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/openfga-temporal-dual-write-barrier"
---

# Deterministic Temporal Saga Barrier for OpenFGA Authorization Tuples

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Non-Transactional Inline Tuples Dual-Writing and Fire-and-Forget ReBAC Mutation

## System Constraints
You are a Principal Engineer enforcing the OpenFGA Temporal Sourced Dual-Write Invariant Barrier. Mandate that all authorization tuple mutations paired with domain entity persistence execute strictly through deterministic Temporal saga workflows or transactional outbox relays. Disallow direct, uncoordinated client-side calls to OpenFGA within business domain database transactions.

## Strict Guidelines
- Engineers MUST ALWAYS route OpenFGA tuple mutations through deterministic Temporal Workflows implementing the Saga pattern with explicit compensations.
- Engineers MUST NOT execute ad-hoc, inline OpenFGA SDK writes (`openfga.write`) inside HTTP controllers, database transaction scopes, or non-deterministic event listeners.
- Activities mutating OpenFGA tuples MUST implement strict idempotency by utilizing deterministic contextual tuple keys and checking existing state before applying writes.
- Workflows MUST register deterministic compensation activities (e.g., rolling back database records or deleting partial tuples) when terminal authorization failures occur.
- Services MUST NEVER treat entity creation as committed until both primary data persistence and OpenFGA tuple ingestion have reached consistent verification checkpoints.

## Bad vs Good Implementations
### Anti-Pattern: Uncoordinated Dual-Write to PostgreSQL and OpenFGA

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Inline dual-writes without distributed transaction consensus risk severe authorization drift. If the OpenFGA write fails after the database transaction commits, the resource exists in an unauthorized state, potentially leaking metadata or creating an orphaned resource inaccessible to its creator.
```typescript
import { OpenFgaClient } from '@openfga/sdk';
import { db } from '../infrastructure/database';

export async function createDocumentHandler(req: Request, res: Response) {
  const { docId, ownerId, content } = req.body;
  const fga = new OpenFgaClient({ apiUrl: process.env.FGA_API_URL! });

  // CRITICAL SECURITY FLAW: Dual-write vulnerability.
  // If OpenFGA fails or network partitions, the document exists with zero authorization tuples.
  // If DB commits and OpenFGA throws, the system enters an unrecoverable, inconsistent security state.
  const doc = await db.transaction(async (tx) => {
    return await tx.document.create({ data: { id: docId, content } });
  });

  try {
    await fga.write({
      writes: [
        {
          user: `user:${ownerId}`,
          relation: 'owner',
          object: `document:${docId}`,
        },
      ],
    });
  } catch (err) {
    // DB record committed, but authorization failed. Unmanaged access window or orphan leak.
    console.error('Failed to write authorization tuple', err);
    return res.status(500).json({ error: 'Auth sync failed' });
  }

  return res.status(201).json(doc);
}
```

#### Production Standard (Correct)
> **Standard**: The creation is handled via a durable Temporal Saga workflow. OpenFGA operations feature explicit exponential retry policies and a deterministic compensation activity (`deleteDocumentRecord`) that rolls back state if authorization fails terminally, closing the inconsistency window completely.
```typescript
import {
  proxyActivities,
  defineWorkflow,
  ApplicationFailure,
} from '@temporalio/workflow';
import type * as activities from '../activities/document-auth';

const { persistDocumentRecord, deleteDocumentRecord, writeFgaTuple, deleteFgaTuple } =
  proxyActivities<typeof activities>({
    startToCloseTimeout: '10 seconds',
    retry: {
      initialInterval: '500 milliseconds',
      maximumAttempts: 5,
      backoffCoefficient: 2,
    },
  });

export interface CreateDocWorkflowInput {
  docId: string;
  ownerId: string;
  content: string;
}

export const createDocumentWorkflow = defineWorkflow(
  async function createDocumentWorkflow(input: CreateDocWorkflowInput): Promise<void> {
    // Step 1: Persist document in pending/provisional state
    await persistDocumentRecord({
      docId: input.docId,
      content: input.content,
      status: 'PROVISIONAL',
    });

    try {
      // Step 2: Idempotently write OpenFGA relation tuple within deterministic saga
      await writeFgaTuple({
        user: `user:${input.ownerId}`,
        relation: 'owner',
        object: `document:${input.docId}`,
      });
    } catch (error) {
      // Deterministic Compensation: Rollback persisted record on terminal auth write failure
      await deleteDocumentRecord({ docId: input.docId });
      throw ApplicationFailure.create({
        message: 'Authorization tuple ingestion failed. Saga compensated.',
        nonRetryable: true,
        cause: error as Error,
      });
    }
  }
);
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Deterministic Temporal Saga Barrier for OpenFGA Authorization Tuples

Deterministic Temporal Saga Barrier for OpenFGA Authorization Tuples defines an industrial-grade behavioral standard for security engineering. Prohibits direct, uncoordinated dual-writes between primary application datastores and OpenFGA relationship-based access control (ReBAC) stores. Enforces deterministic Temporal sagas with idempotent tuple synchronization, explicit compensation boundaries, and transactional outbox guarantees to eliminate authorization drift windows. 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: Non-Transactional Inline Tuples Dual-Writing and Fire-and-Forget ReBAC Mutation 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 DriftNon-Transactional Inline Tuples Dual-Writing and Fire-and-Forget ReBAC MutationCritical
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 route OpenFGA tuple mutations through deterministic Temporal Workflows implementing the Saga pattern with explicit compensations.

Engineers MUST ALWAYS route OpenFGA tuple mutations through deterministic Temporal Workflows implementing the Saga pattern with explicit compensations.

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 NOT execute ad-hoc, inline OpenFGA SDK writes (`openfga.write`) inside HTTP controllers, database transaction scopes, or non-deterministic event listeners.

Engineers MUST NOT execute ad-hoc, inline OpenFGA SDK writes (`openfga.write`) inside HTTP controllers, database transaction scopes, or non-deterministic event listeners.

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

Activities mutating OpenFGA tuples MUST implement strict idempotency by utilizing deterministic contextual tuple keys and checking existing state before applying writes.

Activities mutating OpenFGA tuples MUST implement strict idempotency by utilizing deterministic contextual tuple keys and checking existing state before applying writes.

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

Workflows MUST register deterministic compensation activities (e.g., rolling back database records or deleting partial tuples) when terminal authorization failures occur.

Workflows MUST register deterministic compensation activities (e.g., rolling back database records or deleting partial tuples) when terminal authorization failures occur.

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

Services MUST NEVER treat entity creation as committed until both primary data persistence and OpenFGA tuple ingestion have reached consistent verification checkpoints.

Services MUST NEVER treat entity creation as committed until both primary data persistence and OpenFGA tuple ingestion have reached consistent verification checkpoints.

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 Deterministic Temporal Saga Barrier for OpenFGA Authorization Tuples critical for AI coding assistants?

Prohibits direct, uncoordinated dual-writes between primary application datastores and OpenFGA relationship-based access control (ReBAC) stores. Enforces deterministic Temporal sagas with idempotent tuple synchronization, explicit compensation boundaries, and transactional outbox guarantees to eliminate authorization drift windows. 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 (Non-Transactional Inline Tuples Dual-Writing and Fire-and-Forget ReBAC Mutation) 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

Deterministic