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

OpenFGA Zanzibar Check-After-Write Consistency Token Standard

Mandates transactional snapshot token propagation and explicit consistency preferences across OpenFGA authorization checks following write mutations. Eliminates the Google Zanzibar 'New Enemy' stale-read anomaly where lagged authorization replicas grant unauthorized access to revoked subjects.

Prohibited Anti-Pattern: Uncoordinated Write-Then-Check Invocations and Default Stale-Read Querying (The 'New Enemy' Anomaly)

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenFGA Zanzibar Check-After-Write Consistency Token Standard - Mandates transactional snapshot token propagation and explicit consistency preferences across OpenFGA authorization checks following write mutations. Eliminates the Google Zanzibar 'New Enemy' stale-read anomaly where lagged authorization replicas grant unauthorized access to revoked subjects.
globs: src/auth/**/*.ts, src/services/**/*.ts, src/controllers/**/*.ts, src/middleware/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/openfga-zanzibar-consistency-token-standard"
---

# OpenFGA Zanzibar Check-After-Write Consistency Token Standard

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Uncoordinated Write-Then-Check Invocations and Default Stale-Read Querying (The 'New Enemy' Anomaly)

## System Constraints
You are a Principal Software Architect enforcing Google Zanzibar consistency models in OpenFGA. You must prevent the 'new enemy' security flaw by strictly requiring causal ordering and consistency tokens across all check-after-write operations. Any authorization check executed after a mutation or within a causally dependent request MUST explicitly pass HIGHER_CONSISTENCY or a verifiable snapshot token.

## Strict Guidelines
- Engineers MUST ALWAYS specify `consistency: ConsistencyPreference.HIGHER_CONSISTENCY` on authorization check queries when checking permissions immediately following a relationship tuple write or delete.
- Engineers MUST NOT rely on default eventual consistency (`ConsistencyPreference.MINIMIZE_LATENCY`) for authorization checks in mutating HTTP flows (POST, PUT, PATCH, DELETE) or during critical security boundary evaluations.
- Code SHOULD propagate consistency metadata (e.g., commit timestamps or snapshot tokens) via distributed context, session state, or response headers to preserve causal ordering across distributed services.
- Services MUST wrap primary datastore modifications and authorization tuple changes in a coordinated transactional outbox or two-phase pattern, recording the returned OpenFGA transaction timestamp.
- Components NEVER execute raw `client.check()` without explicitly declaring a `consistency` parameter or validating that downstream read replicas have ingested upstream mutation tokens.

## Bad vs Good Implementations
### Stale Read on Membership Revocation (New Enemy Anti-Pattern)

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Executing `client.check()` without specifying `consistency` defaults to `MINIMIZE_LATENCY`, querying an OpenFGA read replica that may lag behind the write node. Revoked users can retain access during this replication window.
```typescript
import { OpenFgaClient } from '@openfga/sdk';

export async function revokeAndVerifyAccess(
  fgaClient: OpenFgaClient,
  orgId: string,
  userId: string,
  resourceId: string
): Promise<boolean> {
  // Anti-pattern: Relationship tuple is deleted, but eventual consistency allows stale reads
  await fgaClient.write({
    deletes: [{
      user: `user:${userId}`,
      relation: 'member',
      object: `organization:${orgId}`
    }]
  });

  // CRITICAL VULNERABILITY: Default check hits an un-replicated query node
  // (Zanzibar 'New Enemy' flaw: user appears authorized despite revocation)
  const { allowed } = await fgaClient.check({
    user: `user:${userId}`,
    relation: 'can_read',
    object: `document:${resourceId}`
  });

  return allowed;
}
```

#### Production Standard (Correct)
> **Standard**: By explicitly configuring `ConsistencyPreference.HIGHER_CONSISTENCY`, the query bypasses stale in-memory read caches and guarantees reading directly from primary storage or catching up to recent transaction boundaries.
```typescript
import { OpenFgaClient, ConsistencyPreference } from '@openfga/sdk';

export async function revokeAndVerifyAccess(
  fgaClient: OpenFgaClient,
  orgId: string,
  userId: string,
  resourceId: string
): Promise<boolean> {
  // 1. Execute mutation and capture transaction completion
  await fgaClient.write({
    deletes: [{
      user: `user:${userId}`,
      relation: 'member',
      object: `organization:${orgId}`
    }]
  });

  // 2. Enforce HIGHER_CONSISTENCY to bypass stale replica cache and prevent 'New Enemy'
  const { allowed } = await fgaClient.check(
    {
      user: `user:${userId}`,
      relation: 'can_read',
      object: `document:${resourceId}`
    },
    {
      consistency: ConsistencyPreference.HIGHER_CONSISTENCY
    }
  );

  return allowed;
}
```

Recommended Agent Skills (askills.dev)

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

Architectural Specification & Invariant Rationale

Architectural Invariant Design: OpenFGA Zanzibar Check-After-Write Consistency Token Standard

OpenFGA Zanzibar Check-After-Write Consistency Token Standard defines an industrial-grade behavioral standard for backend engineering. Mandates transactional snapshot token propagation and explicit consistency preferences across OpenFGA authorization checks following write mutations. Eliminates the Google Zanzibar 'New Enemy' stale-read anomaly where lagged authorization replicas grant unauthorized access to revoked subjects. 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: Uncoordinated Write-Then-Check Invocations and Default Stale-Read Querying (The 'New Enemy' Anomaly) 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 DriftUncoordinated Write-Then-Check Invocations and Default Stale-Read Querying (The 'New Enemy' Anomaly)Critical
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 specify `consistency

Engineers MUST ALWAYS specify `consistency: ConsistencyPreference.HIGHER_CONSISTENCY` on authorization check queries when checking permissions immediately following a relationship tuple write or delete.

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 rely on default eventual consistency (`ConsistencyPreference.MINIMIZE_LATENCY`) for authorization checks in mutating HTTP flows (POST, PUT, PATCH, DELETE) or during critical security boundary evaluations.

Engineers MUST NOT rely on default eventual consistency (`ConsistencyPreference.MINIMIZE_LATENCY`) for authorization checks in mutating HTTP flows (POST, PUT, PATCH, DELETE) or during critical security boundary evaluations.

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 propagate consistency metadata (e.g., commit timestamps or snapshot tokens) via distributed context, session state, or response headers to preserve causal ordering across distributed services.

Code SHOULD propagate consistency metadata (e.g., commit timestamps or snapshot tokens) via distributed context, session state, or response headers to preserve causal ordering across distributed services.

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 wrap primary datastore modifications and authorization tuple changes in a coordinated transactional outbox or two-phase pattern, recording the returned OpenFGA transaction timestamp.

Services MUST wrap primary datastore modifications and authorization tuple changes in a coordinated transactional outbox or two-phase pattern, recording the returned OpenFGA transaction timestamp.

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 `client.check()` without explicitly declaring a `consistency` parameter or validating that downstream read replicas have ingested upstream mutation tokens.

Components NEVER execute raw `client.check()` without explicitly declaring a `consistency` parameter or validating that downstream read replicas have ingested upstream mutation tokens.

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 Zanzibar Check-After-Write Consistency Token Standard critical for AI coding assistants?

Mandates transactional snapshot token propagation and explicit consistency preferences across OpenFGA authorization checks following write mutations. Eliminates the Google Zanzibar 'New Enemy' stale-read anomaly where lagged authorization replicas grant unauthorized access to revoked subjects. 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 (Uncoordinated Write-Then-Check Invocations and Default Stale-Read Querying (The 'New Enemy' Anomaly)) 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