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

OpenFGA Distributed ReBAC Bounded Consistency Token Propagation

Enforces bounded read-after-write consistency for OpenFGA ReBAC checks across geo-distributed services. Prevents authorization bypass and stale permission errors (such as immediate 403 Forbidden regressions following grant mutations) without degrading cluster performance via blanket synchronous read-locks on primary databases.

Prohibited Anti-Pattern: Global Unconditional Primary Synchronization or Asynchronous Edge Read-After-Write Stale Permissions

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenFGA Distributed ReBAC Bounded Consistency Token Propagation - Enforces bounded read-after-write consistency for OpenFGA ReBAC checks across geo-distributed services. Prevents authorization bypass and stale permission errors (such as immediate 403 Forbidden regressions following grant mutations) without degrading cluster performance via blanket synchronous read-locks on primary databases.
globs: src/**/*.ts, src/auth/**/*.ts, src/middleware/**/*.ts, src/services/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/openfga-rebac-consistency-token-propagation"
---

# OpenFGA Distributed ReBAC Bounded Consistency Token Propagation

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Global Unconditional Primary Synchronization or Asynchronous Edge Read-After-Write Stale Permissions

## System Constraints
You are a Principal Software Architect enforcing production-grade OpenFGA ReBAC patterns. Geo-distributed authorization must balance read-replica latency with causal consistency. You must ensure that mutation responses extract consistency tokens and propagate them via downstream request contexts (e.g., HTTP headers, session stores). For checks, apply HIGHER_CONSISTENCY conditionally within mutation grace windows and default to MINIMIZE_LATENCY everywhere else. Reject any implementation that hardcodes global HIGHER_CONSISTENCY across all client calls or discards consistency tokens returned from write operations.

## Strict Guidelines
- Engineers MUST ALWAYS extract and capture write completion metadata (or consistency timestamps) from OpenFGA writeTuple executions and propagate them downstream to the initiating user session context.
- Engineers MUST NOT configure OpenFGA clients with blanket ConsistencyPreference.HIGHER_CONSISTENCY on global singletons, as this routes all read checks directly to the primary datastore replica and causes severe lock contention.
- Code SHOULD conditionally upgrade check evaluations to ConsistencyPreference.HIGHER_CONSISTENCY only when the requesting context holds an active, unexpired consistency token indicating a recent write by the actor.
- Services MUST propagate consistency tokens across distributed service boundaries using standardized request tracing headers (e.g., 'X-FGA-Consistency-Token').
- Components NEVER execute raw OpenFGA check calls inside performance-critical read paths without explicitly declaring the intended ConsistencyPreference based on actor session freshness.

## Bad vs Good Implementations
### Contextual Consistency Enforcement in OpenFGA Service Layer

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The bad example creates an unbounded race condition: if client-level default is MINIMIZE_LATENCY, subsequent checks on read replicas fail immediately after write. Alternatively, if globally set to HIGHER_CONSISTENCY, all edge reads synchronously bombard the primary database, exhausting connection pools.
```typescript
import { OpenFgaClient, ConsistencyPreference } from '@openfga/sdk';

export class AuthorizationService {
  private fgaClient: OpenFgaClient;

  constructor() {
    // ANTI-PATTERN: Forcing HIGHER_CONSISTENCY globally on the client
    // routes all check traffic across all regions to the primary database, leading to lock contention.
    this.fgaClient = new OpenFgaClient({
      apiUrl: process.env.FGA_API_URL!,
      storeId: process.env.FGA_STORE_ID!,
      authorizationModelId: process.env.FGA_MODEL_ID!,
    });
  }

  async grantDocumentAccess(userId: string, documentId: string): Promise<void> {
    await this.fgaClient.write({
      writes: [{
        user: `user:${userId}`,
        relation: 'viewer',
        object: `document:${documentId}`
      }]
    });
    // Write result discarded; no consistency token tracked for client
  }

  async canAccessDocument(userId: string, documentId: string): Promise<boolean> {
    // Always uses default client-level consistency; under MINIMIZE_LATENCY default,
    // immediate reads after grant will fail due to read-replica lag.
    const response = await this.fgaClient.check({
      user: `user:${userId}`,
      relation: 'viewer',
      object: `document:${documentId}`
    });
    return !!response.allowed;
  }
}
```

#### Production Standard (Correct)
> **Standard**: The good example applies bounded consistency based on session-aware write state. Read queries default to low-latency edge replicas, and dynamically upgrade to HIGHER_CONSISTENCY only within a tight, bounded grace window (3 seconds) following a known write, preventing edge stale-permission failures without causing DB connection pool exhaustion.
```typescript
import { OpenFgaClient, ConsistencyPreference, ClientCheckRequest } from '@openfga/sdk';

interface SessionAuthContext {
  actorId: string;
  lastMutationTimestamp?: number;
  consistencyToken?: string;
}

export class AuthorizationService {
  private fgaClient: OpenFgaClient;
  private readonly BOUNDED_SYNC_WINDOW_MS = 3000; // 3-second bounded window for replica convergence

  constructor() {
    this.fgaClient = new OpenFgaClient({
      apiUrl: process.env.FGA_API_URL!,
      storeId: process.env.FGA_STORE_ID!,
      authorizationModelId: process.env.FGA_MODEL_ID!,
    });
  }

  async grantDocumentAccess(
    actorId: string,
    targetUserId: string,
    documentId: string
  ): Promise<{ consistencyToken: string; timestamp: number }> {
    await this.fgaClient.write({
      writes: [{
        user: `user:${targetUserId}`,
        relation: 'viewer',
        object: `document:${documentId}`
      }]
    });

    // Generate bounded causal token tied to monotonic write timestamp
    const timestamp = Date.now();
    const consistencyToken = `fga_sync_${documentId}_${timestamp}`;
    return { consistencyToken, timestamp };
  }

  async canAccessDocument(
    context: SessionAuthContext,
    documentId: string
  ): Promise<boolean> {
    const isWithinMutationGraceWindow =
      Boolean(context.lastMutationTimestamp) &&
      (Date.now() - (context.lastMutationTimestamp ?? 0) < this.BOUNDED_SYNC_WINDOW_MS);

    // Route to primary only if session recently mutated state; otherwise route to fast replicas
    const consistency: ConsistencyPreference = isWithinMutationGraceWindow
      ? ConsistencyPreference.HIGHER_CONSISTENCY
      : ConsistencyPreference.MINIMIZE_LATENCY;

    const checkPayload: ClientCheckRequest = {
      user: `user:${context.actorId}`,
      relation: 'viewer',
      object: `document:${documentId}`
    };

    const response = await this.fgaClient.check(checkPayload, {
      consistency
    });

    return Boolean(response.allowed);
  }
}
```

Recommended Agent Skills (askills.dev)

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

Architectural Specification & Invariant Rationale

Architectural Invariant Design: OpenFGA Distributed ReBAC Bounded Consistency Token Propagation

OpenFGA Distributed ReBAC Bounded Consistency Token Propagation defines an industrial-grade behavioral standard for security engineering. Enforces bounded read-after-write consistency for OpenFGA ReBAC checks across geo-distributed services. Prevents authorization bypass and stale permission errors (such as immediate 403 Forbidden regressions following grant mutations) without degrading cluster performance via blanket synchronous read-locks on primary databases. 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: Global Unconditional Primary Synchronization or Asynchronous Edge Read-After-Write Stale Permissions 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 DriftGlobal Unconditional Primary Synchronization or Asynchronous Edge Read-After-Write Stale PermissionsCritical
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 extract and capture write completion metadata (or consistency timestamps) from OpenFGA writeTuple executions and propagate them downstream to the initiating user session context.

Engineers MUST ALWAYS extract and capture write completion metadata (or consistency timestamps) from OpenFGA writeTuple executions and propagate them downstream to the initiating user session context.

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 configure OpenFGA clients with blanket ConsistencyPreference.HIGHER_CONSISTENCY on global singletons, as this routes all read checks directly to the primary datastore replica and causes severe lock contention.

Engineers MUST NOT configure OpenFGA clients with blanket ConsistencyPreference.HIGHER_CONSISTENCY on global singletons, as this routes all read checks directly to the primary datastore replica and causes severe lock contention.

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

Code SHOULD conditionally upgrade check evaluations to ConsistencyPreference.HIGHER_CONSISTENCY only when the requesting context holds an active, unexpired consistency token indicating a recent write by the actor.

Code SHOULD conditionally upgrade check evaluations to ConsistencyPreference.HIGHER_CONSISTENCY only when the requesting context holds an active, unexpired consistency token indicating a recent write by the actor.

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

Services MUST propagate consistency tokens across distributed service boundaries using standardized request tracing headers (e.g., 'X-FGA-Consistency-Token').

Services MUST propagate consistency tokens across distributed service boundaries using standardized request tracing headers (e.g., 'X-FGA-Consistency-Token').

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 execute raw OpenFGA check calls inside performance-critical read paths without explicitly declaring the intended ConsistencyPreference based on actor session freshness.

Components NEVER execute raw OpenFGA check calls inside performance-critical read paths without explicitly declaring the intended ConsistencyPreference based on actor session freshness.

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 Distributed ReBAC Bounded Consistency Token Propagation critical for AI coding assistants?

Enforces bounded read-after-write consistency for OpenFGA ReBAC checks across geo-distributed services. Prevents authorization bypass and stale permission errors (such as immediate 403 Forbidden regressions following grant mutations) without degrading cluster performance via blanket synchronous read-locks on primary databases. 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 (Global Unconditional Primary Synchronization or Asynchronous Edge Read-After-Write Stale Permissions) 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