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

OpenFGA Monotonic Snapshot Read-After-Write Consistency Invariant

Guarantees zero-stale authorization evaluations across distributed ReBAC topologies by enforcing monotonic Zanzibar zookie checkpoint propagation on all mutation paths. Prevents authorization bypass anomalies caused by evaluating permissions against out-of-order or stale read replicas following relational tuple writes. Mandates contextual snapshot token capture, transactional session propagation, and strict consistency token verification on all post-write Check evaluations.

Prohibited Anti-Pattern: Executing OpenFGA Check API Calls Without Monotonic Consistency Tokens Post-Mutation

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenFGA Monotonic Snapshot Read-After-Write Consistency Invariant - Guarantees zero-stale authorization evaluations across distributed ReBAC topologies by enforcing monotonic Zanzibar zookie checkpoint propagation on all mutation paths. Prevents authorization bypass anomalies caused by evaluating permissions against out-of-order or stale read replicas following relational tuple writes. Mandates contextual snapshot token capture, transactional session propagation, and strict consistency token verification on all post-write Check evaluations.
globs: src/auth/**/*.{ts,tsx}, src/security/**/*.{ts,tsx}, src/services/**/*.{ts,tsx}, src/api/**/*.{ts,tsx}, src/lib/openfga/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/openfga-monotonic-snapshot-consistency-invariant"
---

# OpenFGA Monotonic Snapshot Read-After-Write Consistency Invariant

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Executing OpenFGA Check API Calls Without Monotonic Consistency Tokens Post-Mutation

## System Constraints
You are a Principal Security Architect enforcing the OpenFGA Monotonic Snapshot Read-After-Write Consistency Invariant. You must ensure that every mutation written to OpenFGA captures the resulting transaction snapshot token (zookie/consistency token) and propagates it across downstream service calls and read operations. Forbid any naked OpenFGA Check or Expand API evaluations without explicit consistency tokens in execution contexts that immediately follow a tuple write or depend on causal mutation ordering.

## Strict Guidelines
- Engineers MUST ALWAYS capture the write snapshot token (e.g., OpenFGA `consistency_token` or transaction commit timestamp) returned from `openFgaClient.write()` or `openFgaClient.writeTuples()`.
- Engineers MUST ALWAYS pass the captured monotonic consistency token into subsequent `openFgaClient.check()` calls within the same causal context or HTTP request pipeline.
- Engineers MUST NOT rely on default eventual consistency options (e.g., `ConsistencyPreference.UNSPECIFIED` or `ConsistencyPreference.MINIMIZE_LATENCY`) when performing authorization decisions on freshly mutated resources.
- Services MUST serialize the latest monotonic consistency token into the outbound response headers (e.g., `X-OpenFGA-Consistency-Token`) or user session context so downstream consumer services preserve the causal read-after-write boundary.
- Components NEVER execute write-then-check authorization patterns without enforcing an explicit monotonic invariant checkpoint, as asynchronous database replication lag permits unauthorized access or false denial anomalies.

## Bad vs Good Implementations
### Enforcing Monotonic Consistency Token Propagation on ReBAC Mutations

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The check call executes against the OpenFGA cluster without a monotonic consistency token or consistency preference. In a distributed multi-replica topology, the check request may hit an out-of-sync database replica, returning `allowed: false` immediately after a successful write (read-after-write anomaly).
```typescript
import { OpenFgaClient } from '@openfga/sdk';

export async function grantAndVerifyAccess(
  fgaClient: OpenFgaClient,
  userId: string,
  documentId: string
): Promise<boolean> {
  // Anti-Pattern: Writes tuple without capturing or passing consistency metadata
  await fgaClient.write({
    writes: [
      {
        user: `user:${userId}`,
        relation: 'editor',
        object: `document:${documentId}`,
      },
    ],
  });

  // Stale Read Anomaly: Read-replica lag can evaluate against a pre-write snapshot
  const response = await fgaClient.check({
    user: `user:${userId}`,
    relation: 'editor',
    object: `document:${documentId}`,
  });

  return response.allowed ?? false;
}
```

#### Production Standard (Correct)
> **Standard**: The good example captures the write snapshot identifier and enforces `ConsistencyPreference.HIGHER_CONSISTENCY` with explicit checkpoint headers on subsequent checks. This guarantees linearizable read-after-write semantics across distributed replicas.
```typescript
import { OpenFgaClient, ConsistencyPreference } from '@openfga/sdk';

export interface AuthzEvaluationContext {
  userId: string;
  documentId: string;
  correlationToken?: string;
}

export interface MutationResult {
  allowed: boolean;
  consistencyToken: string;
}

export async function grantAndVerifyAccess(
  fgaClient: OpenFgaClient,
  context: AuthzEvaluationContext
): Promise<MutationResult> {
  // Invariant Fix: Capture write transaction metadata and monotonically enforce checkpoint
  const writeResult = await fgaClient.write({
    writes: [
      {
        user: `user:${context.userId}`,
        relation: 'editor',
        object: `document:${context.documentId}`,
      },
    ],
  });

  // OpenFGA returns the write transaction snapshot token
  const consistencyToken = writeResult.writes?.[0]?.timestamp?.toISOString() ?? new Date().toISOString();

  // Enforce HIGHER_CONSISTENCY using the captured monotonic snapshot token
  const checkResponse = await fgaClient.check({
    user: `user:${context.userId}`,
    relation: 'editor',
    object: `document:${context.documentId}`,
    consistency: ConsistencyPreference.HIGHER_CONSISTENCY,
  }, {
    headers: {
      'X-OpenFGA-Consistency-Token': consistencyToken,
    },
  });

  if (!checkResponse.allowed) {
    throw new Error(`Monotonic consistency violation: write confirmed but check failed for document:${context.documentId}`);
  }

  return {
    allowed: true,
    consistencyToken,
  };
}
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: OpenFGA Monotonic Snapshot Read-After-Write Consistency Invariant

OpenFGA Monotonic Snapshot Read-After-Write Consistency Invariant defines an industrial-grade behavioral standard for security engineering. Guarantees zero-stale authorization evaluations across distributed ReBAC topologies by enforcing monotonic Zanzibar zookie checkpoint propagation on all mutation paths. Prevents authorization bypass anomalies caused by evaluating permissions against out-of-order or stale read replicas following relational tuple writes. Mandates contextual snapshot token capture, transactional session propagation, and strict consistency token verification on all post-write Check 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: Executing OpenFGA Check API Calls Without Monotonic Consistency Tokens Post-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 DriftExecuting OpenFGA Check API Calls Without Monotonic Consistency Tokens Post-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 capture the write snapshot token (e.g., OpenFGA `consistency_token` or transaction commit timestamp) returned from `openFgaClient.write()` or `openFgaClient.writeTuples()`.

Engineers MUST ALWAYS capture the write snapshot token (e.g., OpenFGA `consistency_token` or transaction commit timestamp) returned from `openFgaClient.write()` or `openFgaClient.writeTuples()`.

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 pass the captured monotonic consistency token into subsequent `openFgaClient.check()` calls within the same causal context or HTTP request pipeline.

Engineers MUST ALWAYS pass the captured monotonic consistency token into subsequent `openFgaClient.check()` calls within the same causal context or HTTP request pipeline.

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 NOT rely on default eventual consistency options (e.g., `ConsistencyPreference.UNSPECIFIED` or `ConsistencyPreference.MINIMIZE_LATENCY`) when performing authorization decisions on freshly mutated resources.

Engineers MUST NOT rely on default eventual consistency options (e.g., `ConsistencyPreference.UNSPECIFIED` or `ConsistencyPreference.MINIMIZE_LATENCY`) when performing authorization decisions on freshly mutated resources.

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 serialize the latest monotonic consistency token into the outbound response headers (e.g., `X-OpenFGA-Consistency-Token`) or user session context so downstream consumer services preserve the causal read-after-write boundary.

Services MUST serialize the latest monotonic consistency token into the outbound response headers (e.g., `X-OpenFGA-Consistency-Token`) or user session context so downstream consumer services preserve the causal read-after-write boundary.

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 write-then-check authorization patterns without enforcing an explicit monotonic invariant checkpoint, as asynchronous database replication lag permits unauthorized access or false denial anomalies.

Components NEVER execute write-then-check authorization patterns without enforcing an explicit monotonic invariant checkpoint, as asynchronous database replication lag permits unauthorized access or false denial anomalies.

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 Monotonic Snapshot Read-After-Write Consistency Invariant critical for AI coding assistants?

Guarantees zero-stale authorization evaluations across distributed ReBAC topologies by enforcing monotonic Zanzibar zookie checkpoint propagation on all mutation paths. Prevents authorization bypass anomalies caused by evaluating permissions against out-of-order or stale read replicas following relational tuple writes. Mandates contextual snapshot token capture, transactional session propagation, and strict consistency token verification on all post-write Check 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 (Executing OpenFGA Check API Calls Without Monotonic Consistency Tokens Post-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

OpenFGA