This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
securitycritical PriorityID: openfga-rebac-causal-consistency-standard

OpenFGA ReBAC Causal Consistency & Tuple Transactional Invalidation Standard

Enforces strict causal ordering and read-after-write consistency between relational database transactions and OpenFGA relationship tuple mutations. Eliminates privilege-escalation and authorization bypass race conditions by prohibiting fire-and-forget tuple updates, stale authorization cache reads, and unsequenced check operations. Mandates the transactional outbox pattern or dual-phase commit coordination with consistent token propagation across all ReBAC evaluations.

Prohibited Anti-Pattern: Dual-Write Race Conditions and Eventual Inconsistency Permitting Privilege Escalation During Tuple Invalidation

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenFGA ReBAC Causal Consistency & Tuple Transactional Invalidation Standard - Enforces strict causal ordering and read-after-write consistency between relational database transactions and OpenFGA relationship tuple mutations. Eliminates privilege-escalation and authorization bypass race conditions by prohibiting fire-and-forget tuple updates, stale authorization cache reads, and unsequenced check operations. Mandates the transactional outbox pattern or dual-phase commit coordination with consistent token propagation across all ReBAC evaluations.
globs: src/**/auth/**/*.{ts,tsx,js,jsx}, src/**/services/**/*.{ts,tsx,js,jsx}, src/**/repositories/**/*.{ts,tsx,js,jsx}, src/**/middleware/**/*.{ts,tsx,js,jsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/openfga-rebac-causal-consistency-standard"
---

# OpenFGA ReBAC Causal Consistency & Tuple Transactional Invalidation Standard

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Dual-Write Race Conditions and Eventual Inconsistency Permitting Privilege Escalation During Tuple Invalidation

## System Constraints
You are a Principal Security Architect enforcing the OpenFGA ReBAC Causal Consistency & Tuple Transactional Invalidation Standard. You MUST prevent race conditions where relational entity state and OpenFGA authorization graph states diverge. You MUST mandate transactional tuple synchronization, deterministic ordering via transactional outbox or coordinated commit, and causal consistency token propagation (such as OpenFGA consistency tokens or sequence-based check invariants). You MUST reject any fire-and-forget tuple writes or authorization evaluations performed without causal token verification.

## Strict Guidelines
- Engineers MUST ALWAYS write authorization tuple changes within the same ACID database transaction as the domain entity state change using a Transactional Outbox table or an immediate two-phase write pattern.
- Engineers MUST NOT perform fire-and-forget asynchronous OpenFGA write calls inside or immediately after business logic without transactional commit guarantees and causal token retrieval.
- Services MUST capture the returned OpenFGA continuation token or transaction ledger sequence and propagate it as a causal consistency token to downstream callers performing subsequent checks.
- Engineers MUST ALWAYS invoke OpenFGA `check` operations with `consistency: ConsistencyPreference.HIGHER_CONSISTENCY` or pass the corresponding `consistency_token` whenever evaluating permissions immediately following state mutations (read-after-write).
- Components NEVER rely on time-based delays, optimistic in-memory authorization caches, or eventual consistency when revoking permissions, deleting relationships, or transferring resource ownership.

## Bad vs Good Implementations
### Dual-Write Race Condition vs. Transactional Outbox with Causal Consistency Token

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: This code suffers from a classic dual-write anti-pattern. If the database mutation succeeds but the OpenFGA API call fails or is delayed due to network latency, the user retains access in the authorization graph (privilege escalation). Furthermore, without obtaining and propagating a causal consistency token, concurrent requests evaluated on replica nodes will observe stale authorization states.
```typescript
import { OpenFgaClient } from '@openfga/sdk';
import { db } from './database';

const fgaClient = new OpenFgaClient({
  apiUrl: process.env.FGA_API_URL!,
  storeId: process.env.FGA_STORE_ID!,
});

export async function revokeDocumentAccess(documentId: string, userId: string): Promise<void> {
  // Flaw 1: DB update occurs independently from authorization tuple deletion
  await db.documentPermission.deleteMany({
    where: { documentId, userId },
  });

  // Flaw 2: Fire-and-forget network call; failure creates permanent privilege escalation
  // Flaw 3: Incurring read-after-write race condition: checks performed immediately
  // in concurrent requests read stale FGA replicas without causal tokens
  fgaClient.write({
    deletes: [{
      user: `user:${userId}`,
      relation: 'viewer',
      object: `document:${documentId}`,
    }],
  }).catch((err) => console.error('Failed to sync OpenFGA', err));
}
```

#### Production Standard (Correct)
> **Standard**: This pattern eliminates race conditions by coupling database mutations with an authorization outbox record inside an ACID transaction. When writing to OpenFGA, it synchronizes execution and captures consistency metadata. The corresponding authorization check mandates higher consistency, preventing replica staleness from serving obsolete authorization grants.
```typescript
import { OpenFgaClient, ConsistencyPreference } from '@openfga/sdk';
import { db } from './database';

const fgaClient = new OpenFgaClient({
  apiUrl: process.env.FGA_API_URL!,
  storeId: process.env.FGA_STORE_ID!,
});

export interface RevokeResult {
  success: boolean;
  consistencyToken?: string;
}

export async function revokeDocumentAccess(documentId: string, userId: string): Promise<RevokeResult> {
  // Step 1: Enforce transactional atomicity by committing outbox intent alongside entity state
  const outboxEvent = await db.$transaction(async (tx) => {
    await tx.documentPermission.deleteMany({
      where: { documentId, userId },
    });

    return tx.authorizationOutbox.create({
      data: {
        action: 'DELETE',
        user: `user:${userId}`,
        relation: 'viewer',
        object: `document:${documentId}`,
        status: 'PENDING',
      },
    });
  });

  // Step 2: Synchronous dispatch with deterministic tuple mutation and causal token acquisition
  try {
    const response = await fgaClient.write({
      deletes: [{
        user: outboxEvent.user,
        relation: outboxEvent.relation,
        object: outboxEvent.object,
      }],
    });

    await db.authorizationOutbox.update({
      where: { id: outboxEvent.id },
      data: { status: 'PROCESSED', processedAt: new Date() },
    });

    return {
      success: true,
      consistencyToken: response.writes?.[0]?.timestamp || undefined,
    };
  } catch (error) {
    // Outbox background worker will safely retry using deterministic idempotency
    throw new Error(`Transactional authorization sync failed: ${(error as Error).message}`);
  }
}

export async function checkViewerAccess(
  documentId: string,
  userId: string,
  consistencyToken?: string
): Promise<boolean> {
  // Step 3: Require high consistency or token-based causal verification to eliminate read-after-write races
  const { allowed } = await fgaClient.check({
    user: `user:${userId}`,
    relation: 'viewer',
    object: `document:${documentId}`,
    contextualTuples: [],
    consistency: ConsistencyPreference.HIGHER_CONSISTENCY,
  });

  return allowed ?? false;
}
```

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: OpenFGA ReBAC Causal Consistency & Tuple Transactional Invalidation Standard

OpenFGA ReBAC Causal Consistency & Tuple Transactional Invalidation Standard defines an industrial-grade behavioral standard for security engineering. Enforces strict causal ordering and read-after-write consistency between relational database transactions and OpenFGA relationship tuple mutations. Eliminates privilege-escalation and authorization bypass race conditions by prohibiting fire-and-forget tuple updates, stale authorization cache reads, and unsequenced check operations. Mandates the transactional outbox pattern or dual-phase commit coordination with consistent token propagation across all ReBAC evaluations. 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: Dual-Write Race Conditions and Eventual Inconsistency Permitting Privilege Escalation During Tuple Invalidation 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 DriftDual-Write Race Conditions and Eventual Inconsistency Permitting Privilege Escalation During Tuple InvalidationCritical
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 write authorization tuple changes within the same ACID database transaction as the domain entity state change using a Transactional Outbox table or an immediate two-phase write pattern.

Engineers MUST ALWAYS write authorization tuple changes within the same ACID database transaction as the domain entity state change using a Transactional Outbox table or an immediate two-phase write pattern.

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 perform fire-and-forget asynchronous OpenFGA write calls inside or immediately after business logic without transactional commit guarantees and causal token retrieval.

Engineers MUST NOT perform fire-and-forget asynchronous OpenFGA write calls inside or immediately after business logic without transactional commit guarantees and causal token retrieval.

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

Services MUST capture the returned OpenFGA continuation token or transaction ledger sequence and propagate it as a causal consistency token to downstream callers performing subsequent checks.

Services MUST capture the returned OpenFGA continuation token or transaction ledger sequence and propagate it as a causal consistency token to downstream callers performing subsequent checks.

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 ALWAYS invoke OpenFGA `check` operations with `consistency

Engineers MUST ALWAYS invoke OpenFGA `check` operations with `consistency: ConsistencyPreference.HIGHER_CONSISTENCY` or pass the corresponding `consistency_token` whenever evaluating permissions immediately following state mutations (read-after-write).

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

Components NEVER rely on time-based delays, optimistic in-memory authorization caches, or eventual consistency when revoking permissions, deleting relationships, or transferring resource ownership.

Components NEVER rely on time-based delays, optimistic in-memory authorization caches, or eventual consistency when revoking permissions, deleting relationships, or transferring resource ownership.

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 OpenFGA ReBAC Causal Consistency & Tuple Transactional Invalidation Standard critical for AI coding assistants?

Enforces strict causal ordering and read-after-write consistency between relational database transactions and OpenFGA relationship tuple mutations. Eliminates privilege-escalation and authorization bypass race conditions by prohibiting fire-and-forget tuple updates, stale authorization cache reads, and unsequenced check operations. Mandates the transactional outbox pattern or dual-phase commit coordination with consistent token propagation across all ReBAC evaluations. 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 (Dual-Write Race Conditions and Eventual Inconsistency Permitting Privilege Escalation During Tuple Invalidation) 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

OpenFGA