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

OpenFGA Zanzibar Zookie Consistency Token & New Enemy Anomaly Prevention

Enforces strict causal ordering across OpenFGA authorization checks and relational mutations to eliminate the Zanzibar 'New Enemy' problem. Writes must capture transactional consistency tokens and propagate them across distributed request boundaries so subsequent read-checks guarantee snapshot evaluation at least as fresh as the mutation.

Prohibited Anti-Pattern: Unsynchronized Eventual-Consistency Checks Causing Stale ACL Reads and Privilege Leaks

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenFGA Zanzibar Zookie Consistency Token & New Enemy Anomaly Prevention - Enforces strict causal ordering across OpenFGA authorization checks and relational mutations to eliminate the Zanzibar 'New Enemy' problem. Writes must capture transactional consistency tokens and propagate them across distributed request boundaries so subsequent read-checks guarantee snapshot evaluation at least as fresh as the mutation.
globs: src/**/*.service.ts, src/**/*.controller.ts, src/**/*.middleware.ts, src/**/authz/*.ts, src/**/fga/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/openfga-zanzibar-zookie-consistency-token-standard"
---

# OpenFGA Zanzibar Zookie Consistency Token & New Enemy Anomaly Prevention

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Unsynchronized Eventual-Consistency Checks Causing Stale ACL Reads and Privilege Leaks

## System Constraints
You are a Principal Software Architect enforcing the Zanzibar Zookie Consistency Token Standard across OpenFGA implementations. You must prevent the 'New Enemy' authorization anomaly where revoking access on a write leader fails to reflect immediately on subsequent read checks evaluated against stale read replicas. Mandate explicit consistency token propagation, transaction-scoped snapshot checking, and HIGHER_CONSISTENCY configurations whenever access mutations casually precede access evaluations.

## Strict Guidelines
- Engineers MUST ALWAYS capture the consistency token or snapshot timestamp returned from write tuple operations mutating permissions.
- Engineers MUST propagate the consistency token across cross-service and client-server boundaries using a standardized HTTP header (e.g., 'x-openfga-consistency-token').
- Services MUST evaluate OpenFGA checks using 'ConsistencyPreference.HIGHER_CONSISTENCY' or pass the explicit causal snapshot token whenever evaluating permissions immediately following an ACL mutation.
- Engineers MUST NOT rely on default client configurations (which default to MINIMIZE_LATENCY) for workflows that revoke access or transfer critical ownership.
- Components NEVER execute dependent data access requests based on eventual-consistency checks without validating causal read-at-least-as-fresh-as guarantees.

## Bad vs Good Implementations
### Revoking Access and Performing Immediate Evaluation Without Consistency Token

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The check call defaults to MINIMIZE_LATENCY and ignores the causal write boundary. If the check hits an asynchronous read replica, it returns true (allowed) despite the immediately preceding revocation, leaking unauthorized data to an adversary.
```typescript
import { OpenFgaClient } from '@openfga/sdk';

export class DocumentAccessService {
  constructor(private readonly fgaClient: OpenFgaClient) {}

  async revokeAndVerifyAccess(docId: string, revokedUserId: string): Promise<boolean> {
    // ANTI-PATTERN: Write response ignored; default consistency allows stale replica check.
    // Leads to Zanzibar 'New Enemy' anomaly: revoked user can still read on a stale replica.
    await this.fgaClient.writeTuples([{
      user: `user:${revokedUserId}`,
      relation: 'viewer',
      object: `document:${docId}`,
    }]);

    const { allowed } = await this.fgaClient.check({
      user: `user:${revokedUserId}`,
      relation: 'viewer',
      object: `document:${docId}`,
    });

    return allowed;
  }
}
```

#### Production Standard (Correct)
> **Standard**: Enforces `ConsistencyPreference.HIGHER_CONSISTENCY` during check calls on post-write code paths, guaranteeing that read replicas have applied all mutations causally preceding this request before resolving authorization.
```typescript
import { OpenFgaClient, ConsistencyPreference, ClientCheckResponse } from '@openfga/sdk';

export interface RevocationResult {
  allowed: boolean;
  consistencyToken?: string;
}

export class DocumentAccessService {
  constructor(private readonly fgaClient: OpenFgaClient) {}

  async revokeAndVerifyAccess(
    docId: string,
    revokedUserId: string,
    correlationHeader?: string
  ): Promise<RevocationResult> {
    // INVARIANT: Capture write outcome and enforce causal freshness on subsequent checks.
    // Prevents the 'New Enemy' anomaly by strictly serializing the causal read boundary.
    await this.fgaClient.write({
      deletes: [{
        user: `user:${revokedUserId}`,
        relation: 'viewer',
        object: `document:${docId}`,
      }],
    });

    const checkResponse: ClientCheckResponse = await this.fgaClient.check(
      {
        user: `user:${revokedUserId}`,
        relation: 'viewer',
        object: `document:${docId}`,
      },
      {
        // Force check against a snapshot at least as fresh as the leader write
        consistency: ConsistencyPreference.HIGHER_CONSISTENCY,
      }
    );

    return {
      allowed: checkResponse.allowed ?? false,
      // Propagate downstream to client/microservices to preserve causal ordering
      consistencyToken: checkResponse.resolution || correlationHeader,
    };
  }
}
```

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 Zanzibar Zookie Consistency Token & New Enemy Anomaly Prevention

OpenFGA Zanzibar Zookie Consistency Token & New Enemy Anomaly Prevention defines an industrial-grade behavioral standard for backend engineering. Enforces strict causal ordering across OpenFGA authorization checks and relational mutations to eliminate the Zanzibar 'New Enemy' problem. Writes must capture transactional consistency tokens and propagate them across distributed request boundaries so subsequent read-checks guarantee snapshot evaluation at least as fresh as the mutation. 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: Unsynchronized Eventual-Consistency Checks Causing Stale ACL Reads and Privilege Leaks 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 DriftUnsynchronized Eventual-Consistency Checks Causing Stale ACL Reads and Privilege LeaksCritical
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 consistency token or snapshot timestamp returned from write tuple operations mutating permissions.

Engineers MUST ALWAYS capture the consistency token or snapshot timestamp returned from write tuple operations mutating permissions.

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 propagate the consistency token across cross-service and client-server boundaries using a standardized HTTP header (e.g., 'x-openfga-consistency-token').

Engineers MUST propagate the consistency token across cross-service and client-server boundaries using a standardized HTTP header (e.g., 'x-openfga-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.
3

Services MUST evaluate OpenFGA checks using 'ConsistencyPreference.HIGHER_CONSISTENCY' or pass the explicit causal snapshot token whenever evaluating permissions immediately following an ACL mutation.

Services MUST evaluate OpenFGA checks using 'ConsistencyPreference.HIGHER_CONSISTENCY' or pass the explicit causal snapshot token whenever evaluating permissions immediately following an ACL mutation.

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 NOT rely on default client configurations (which default to MINIMIZE_LATENCY) for workflows that revoke access or transfer critical ownership.

Engineers MUST NOT rely on default client configurations (which default to MINIMIZE_LATENCY) for workflows that revoke access or transfer critical 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.
5

Components NEVER execute dependent data access requests based on eventual-consistency checks without validating causal read-at-least-as-fresh-as guarantees.

Components NEVER execute dependent data access requests based on eventual-consistency checks without validating causal read-at-least-as-fresh-as guarantees.

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 Zookie Consistency Token & New Enemy Anomaly Prevention critical for AI coding assistants?

Enforces strict causal ordering across OpenFGA authorization checks and relational mutations to eliminate the Zanzibar 'New Enemy' problem. Writes must capture transactional consistency tokens and propagate them across distributed request boundaries so subsequent read-checks guarantee snapshot evaluation at least as fresh as the mutation. 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 (Unsynchronized Eventual-Consistency Checks Causing Stale ACL Reads and Privilege Leaks) 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