This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
securitycritical PriorityID: openfga-zanzibar-distributed-cache-invalidation-standard

OpenFGA Zanzibar Distributed Cache Invalidation & Consistency Guardrail

Enforces strict causal consistency and atomic edge PDP cache invalidation during OpenFGA relationship tuple mutations. Prohibits heuristic TTL-based authorization caching for mutation-sensitive paths to eliminate stale read windows and privilege escalation vulnerabilities across distributed clusters.

Prohibited Anti-Pattern: Heuristic TTL Authorization Caching and Unversioned Asynchronous Edge Reads Permitting Revoked Access Retention

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenFGA Zanzibar Distributed Cache Invalidation & Consistency Guardrail - Enforces strict causal consistency and atomic edge PDP cache invalidation during OpenFGA relationship tuple mutations. Prohibits heuristic TTL-based authorization caching for mutation-sensitive paths to eliminate stale read windows and privilege escalation vulnerabilities across distributed clusters.
globs: src/auth/**/*.{ts,tsx,js,jsx}, src/security/**/*.{ts,tsx,js,jsx}, src/services/authz/**/*.{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-zanzibar-distributed-cache-invalidation-standard"
---

# OpenFGA Zanzibar Distributed Cache Invalidation & Consistency Guardrail

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Heuristic TTL Authorization Caching and Unversioned Asynchronous Edge Reads Permitting Revoked Access Retention

## System Constraints
You are a Principal Software Architect enforcing the OpenFGA Distributed Zanzibar Cache Invalidation Standard. Mandate strict causal consistency tokens (zookies/continuation tokens), deterministic CDC cache purge pipelines, and fail-closed edge authorization semantics to prevent stale privilege escalation across distributed Policy Decision Points (PDPs).

## Strict Guidelines
- Engineers MUST ALWAYS pass explicit consistency tokens or specify ConsistencyPreference.HIGHER_CONSISTENCY during OpenFGA check evaluations following relationship tuple writes.
- Engineers MUST NOT rely on static wall-clock TTLs for authorization cache invalidation when revoking relationships or modifying group memberships.
- Services MUST publish transactional CDC (Change Data Capture) or atomic invalidation messages across edge PDPs before acknowledging relationship tuple deletions to clients.
- Components NEVER fall back to stale local in-memory PDP caches upon invalidation channel failure; they MUST fail-closed or query upstream OpenFGA storage directly.
- Code SHOULD implement monotonic revision fencing or Lamport timestamps on cached authorization subtrees to reject out-of-order replication updates at the edge.

## Bad vs Good Implementations
### OpenFGA Relationship Revocation and Post-Mutation Check

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The mutation deletes the tuple but fails to propagate a snapshot consistency token (zookie equivalent) or invalidate downstream distributed PDP caches. The subsequent check defaults to cached reads, permitting authorization privilege escalation across distributed edge points.
```typescript
import { OpenFgaClient } from '@openfga/sdk';

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

// ANTI-PATTERN: Revokes access without consistency token propagation,
// relying on passive 60s TTL edge cache invalidation.
export async function revokeRole(userId: string, role: string, orgId: string) {
  await fgaClient.writeTuples({
    deletes: [{
      user: `user:${userId}`,
      relation: role,
      object: `organization:${orgId}`,
    }],
  });

  // Stale check: uses default MINIMIZE_LATENCY and stale local memoization,
  // causing edge nodes to falsely evaluate true for up to the remaining TTL.
  const { allowed } = await fgaClient.check({
    user: `user:${userId}`,
    relation: role,
    object: `organization:${orgId}`,
  });

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

#### Production Standard (Correct)
> **Standard**: The good example captures mutation state, broadcasts atomic eviction signals to edge caches, and forces ConsistencyPreference.HIGHER_CONSISTENCY on subsequent checks to guarantee causal consistency and block stale access.
```typescript
import { OpenFgaClient, ConsistencyPreference } from '@openfga/sdk';
import { edgePdpCacheManager } from '../infrastructure/cache';

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

export async function revokeRole(userId: string, role: string, orgId: string) {
  const tupleKey = {
    user: `user:${userId}`,
    relation: role,
    object: `organization:${orgId}`,
  };

  // Write mutation and capture monotonic transaction metadata
  const writeResult = await fgaClient.writeTuples({
    deletes: [tupleKey],
  });

  // Explicitly purge edge PDP caches and propagate causal consistency fence
  await edgePdpCacheManager.broadcastEviction({
    keys: [`${tupleKey.user}#${tupleKey.relation}@${tupleKey.object}`],
    minFreshnessTimestamp: Date.now(),
  });

  // Enforce HIGHER_CONSISTENCY to prevent stale Zanzibar read hazards ('New Enemy' problem)
  const { allowed } = await fgaClient.check(
    {
      user: tupleKey.user,
      relation: tupleKey.relation,
      object: tupleKey.object,
    },
    {
      consistency: ConsistencyPreference.HIGHER_CONSISTENCY,
    }
  );

  return { success: true, allowed, revision: writeResult };
}
```

Recommended Agent Skills (askills.dev)

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

Architectural Specification & Invariant Rationale

Architectural Invariant Design: OpenFGA Zanzibar Distributed Cache Invalidation & Consistency Guardrail

OpenFGA Zanzibar Distributed Cache Invalidation & Consistency Guardrail defines an industrial-grade behavioral standard for security engineering. Enforces strict causal consistency and atomic edge PDP cache invalidation during OpenFGA relationship tuple mutations. Prohibits heuristic TTL-based authorization caching for mutation-sensitive paths to eliminate stale read windows and privilege escalation vulnerabilities across distributed clusters. 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: Heuristic TTL Authorization Caching and Unversioned Asynchronous Edge Reads Permitting Revoked Access Retention 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 DriftHeuristic TTL Authorization Caching and Unversioned Asynchronous Edge Reads Permitting Revoked Access RetentionCritical
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 pass explicit consistency tokens or specify ConsistencyPreference.HIGHER_CONSISTENCY during OpenFGA check evaluations following relationship tuple writes.

Engineers MUST ALWAYS pass explicit consistency tokens or specify ConsistencyPreference.HIGHER_CONSISTENCY during OpenFGA check evaluations following relationship tuple writes.

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 static wall-clock TTLs for authorization cache invalidation when revoking relationships or modifying group memberships.

Engineers MUST NOT rely on static wall-clock TTLs for authorization cache invalidation when revoking relationships or modifying group memberships.

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 publish transactional CDC (Change Data Capture) or atomic invalidation messages across edge PDPs before acknowledging relationship tuple deletions to clients.

Services MUST publish transactional CDC (Change Data Capture) or atomic invalidation messages across edge PDPs before acknowledging relationship tuple deletions to clients.

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

Components NEVER fall back to stale local in-memory PDP caches upon invalidation channel failure

Components NEVER fall back to stale local in-memory PDP caches upon invalidation channel failure; they MUST fail-closed or query upstream OpenFGA storage directly.

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

Code SHOULD implement monotonic revision fencing or Lamport timestamps on cached authorization subtrees to reject out-of-order replication updates at the edge.

Code SHOULD implement monotonic revision fencing or Lamport timestamps on cached authorization subtrees to reject out-of-order replication updates at the edge.

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 Distributed Cache Invalidation & Consistency Guardrail critical for AI coding assistants?

Enforces strict causal consistency and atomic edge PDP cache invalidation during OpenFGA relationship tuple mutations. Prohibits heuristic TTL-based authorization caching for mutation-sensitive paths to eliminate stale read windows and privilege escalation vulnerabilities across distributed clusters. 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 (Heuristic TTL Authorization Caching and Unversioned Asynchronous Edge Reads Permitting Revoked Access Retention) 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