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

OpenFGA Distributed Cache Invalidation and Consistency Invariant

Enforces synchronous distributed edge cache invalidation and explicit consistency levels during OpenFGA tuple mutations. Prevents authorization Time-of-Check to Time-of-Use (TOCTOU) race conditions where revoked access privileges persist in distributed edge caches or stale Zanzibar read replicas.

Prohibited Anti-Pattern: Fire-and-forget cache eviction and weak-consistency checks following OpenFGA tuple revocations

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenFGA Distributed Cache Invalidation and Consistency Invariant - Enforces synchronous distributed edge cache invalidation and explicit consistency levels during OpenFGA tuple mutations. Prevents authorization Time-of-Check to Time-of-Use (TOCTOU) race conditions where revoked access privileges persist in distributed edge caches or stale Zanzibar read replicas.
globs: src/**/*.service.ts, src/**/authz/**/*.ts, src/**/fga/**/*.ts, src/**/guards/**/*.ts, lib/auth/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/openfga-cache-consistency-toctou-guardrail"
---

# OpenFGA Distributed Cache Invalidation and Consistency Invariant

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Fire-and-forget cache eviction and weak-consistency checks following OpenFGA tuple revocations

## System Constraints
You are a Principal Security Architect enforcing zero-trust authorization invariants using OpenFGA. You must prevent TOCTOU vulnerabilities caused by distributed cache divergence and weak read replicas. Every tuple mutation must coordinate synchronous cache eviction before acknowledging success, and all post-mutation or privilege-sensitive checks must explicitly specify ConsistencyPreference.HIGHER_CONSISTENCY.

## Strict Guidelines
- Engineers MUST ALWAYS await distributed cache invalidation before returning a success response for OpenFGA tuple writes or deletes.
- Engineers MUST NOT rely on asynchronous fire-and-forget (.catch(console.error)) cache eviction patterns during permission grants or revocations.
- Services MUST explicitly pass ConsistencyPreference.HIGHER_CONSISTENCY to fgaClient.check() when querying state immediately after a mutation or when protecting high-severity operations.
- Code MUST employ two-phase cache eviction (invalidate before write and invalidate after write) or cache fencing to prevent concurrent read races from repopulating revoked credentials.
- Components NEVER assume default OpenFGA client consistency, as default MINIMIZE_LATENCY reads may route to laggy Zanzibar replica datastores.

## Bad vs Good Implementations
### Asynchronous Cache Invalidation and Unspecified Consistency (TOCTOU Flaw)

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Cache eviction is detached from the write acknowledgement, leaving edge nodes serving stale allow decisions for seconds or minutes. Additionally, the check call defaults to MINIMIZE_LATENCY, which reads from stale OpenFGA datastore replicas and repopulates the edge cache with stale permissions.
```typescript
import { OpenFgaClient } from '@openfga/sdk';
import { Redis } from 'ioredis';

export async function revokeViewerAccess(
  fgaClient: OpenFgaClient,
  redis: Redis,
  userId: string,
  documentId: string
): Promise<void> {
  // Anti-pattern 1: Mutation acknowledged before cache eviction completes
  await fgaClient.write({
    deletes: [{ user: `user:${userId}`, relation: 'viewer', object: `document:${documentId}` }],
  });
  // Anti-pattern 2: Fire-and-forget non-deterministic eviction allows TOCTOU window
  redis.del(`authz:${userId}:doc:${documentId}`).catch((err) => console.error(err));
}

export async function canViewDocument(
  fgaClient: OpenFgaClient,
  redis: Redis,
  userId: string,
  documentId: string
): Promise<boolean> {
  const cached = await redis.get(`authz:${userId}:doc:${documentId}`);
  if (cached !== null) return cached === 'true';

  // Anti-pattern 3: Implicit MINIMIZE_LATENCY reads from lagging read-replicas
  const { allowed } = await fgaClient.check({
    user: `user:${userId}`,
    relation: 'viewer',
    object: `document:${documentId}`,
  });
  await redis.set(`authz:${userId}:doc:${documentId}`, String(allowed), 'EX', 300);
  return allowed ?? false;
}
```

#### Production Standard (Correct)
> **Standard**: Pre- and post-write cache invalidation prevents stale permission windows, and the explicit ConsistencyPreference.HIGHER_CONSISTENCY flag ensures OpenFGA bypasses out-of-sync read replicas, preventing the distributed cache from being repopulated with revoked privileges.
```typescript
import { OpenFgaClient, ConsistencyPreference } from '@openfga/sdk';
import { Redis } from 'ioredis';

export async function revokeViewerAccess(
  fgaClient: OpenFgaClient,
  redis: Redis,
  userId: string,
  documentId: string
): Promise<void> {
  const cacheKey = `authz:${userId}:doc:${documentId}`;
  
  // Step 1: Pre-invalidate edge cache to abort in-flight reads
  await redis.del(cacheKey);

  // Step 2: Authoritative write to OpenFGA storage
  await fgaClient.write({
    deletes: [{ user: `user:${userId}`, relation: 'viewer', object: `document:${documentId}` }],
  });

  // Step 3: Strictly await post-write eviction to guarantee consistency across all nodes
  await redis.del(cacheKey);
}

export async function canViewDocument(
  fgaClient: OpenFgaClient,
  redis: Redis,
  userId: string,
  documentId: string,
  options?: { bypassCache?: boolean }
): Promise<boolean> {
  const cacheKey = `authz:${userId}:doc:${documentId}`;

  if (!options?.bypassCache) {
    const cached = await redis.get(cacheKey);
    if (cached !== null) return cached === 'true';
  }

  // Invariant: HIGHER_CONSISTENCY bypasses lagging replicas to avoid TOCTOU repopulation
  const { allowed } = await fgaClient.check({
    user: `user:${userId}`,
    relation: 'viewer',
    object: `document:${documentId}`,
    consistency: ConsistencyPreference.HIGHER_CONSISTENCY,
  });

  const decision = allowed ?? false;
  // Conservative TTL with explicit numeric cast
  await redis.set(cacheKey, String(decision), 'EX', 60);
  return decision;
}
```

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 Distributed Cache Invalidation and Consistency Invariant

OpenFGA Distributed Cache Invalidation and Consistency Invariant defines an industrial-grade behavioral standard for security engineering. Enforces synchronous distributed edge cache invalidation and explicit consistency levels during OpenFGA tuple mutations. Prevents authorization Time-of-Check to Time-of-Use (TOCTOU) race conditions where revoked access privileges persist in distributed edge caches or stale Zanzibar read replicas. 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: Fire-and-forget cache eviction and weak-consistency checks following OpenFGA tuple revocations 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 DriftFire-and-forget cache eviction and weak-consistency checks following OpenFGA tuple revocationsCritical
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 await distributed cache invalidation before returning a success response for OpenFGA tuple writes or deletes.

Engineers MUST ALWAYS await distributed cache invalidation before returning a success response for OpenFGA tuple writes or deletes.

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 asynchronous fire-and-forget (.catch(console.error)) cache eviction patterns during permission grants or revocations.

Engineers MUST NOT rely on asynchronous fire-and-forget (.catch(console.error)) cache eviction patterns during permission grants or revocations.

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 explicitly pass ConsistencyPreference.HIGHER_CONSISTENCY to fgaClient.check() when querying state immediately after a mutation or when protecting high-severity operations.

Services MUST explicitly pass ConsistencyPreference.HIGHER_CONSISTENCY to fgaClient.check() when querying state immediately after a mutation or when protecting high-severity operations.

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

Code MUST employ two-phase cache eviction (invalidate before write and invalidate after write) or cache fencing to prevent concurrent read races from repopulating revoked credentials.

Code MUST employ two-phase cache eviction (invalidate before write and invalidate after write) or cache fencing to prevent concurrent read races from repopulating revoked credentials.

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 assume default OpenFGA client consistency, as default MINIMIZE_LATENCY reads may route to laggy Zanzibar replica datastores.

Components NEVER assume default OpenFGA client consistency, as default MINIMIZE_LATENCY reads may route to laggy Zanzibar replica datastores.

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 Cache Invalidation and Consistency Invariant critical for AI coding assistants?

Enforces synchronous distributed edge cache invalidation and explicit consistency levels during OpenFGA tuple mutations. Prevents authorization Time-of-Check to Time-of-Use (TOCTOU) race conditions where revoked access privileges persist in distributed edge caches or stale Zanzibar read replicas. 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 (Fire-and-forget cache eviction and weak-consistency checks following OpenFGA tuple revocations) 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