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

OpenFGA Distributed ReBAC Tuple Evaluation & Cache Stampede Elimination Standard

Enforces deterministic ReBAC graph evaluation coalescing, model-version-bound cache keys, and causal consistency token propagation for OpenFGA authorization checks. Prevents authorization bypasses arising from stale permission revocations (New Enemy Problem) and mitigates upstream OpenFGA graph amplification and cache stampedes under high concurrency.

Prohibited Anti-Pattern: Naive Tuple Key-Value Caching with Uncoordinated In-Flight Graph Traversals and Stale Consistency Tokens

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenFGA Distributed ReBAC Tuple Evaluation & Cache Stampede Elimination Standard - Enforces deterministic ReBAC graph evaluation coalescing, model-version-bound cache keys, and causal consistency token propagation for OpenFGA authorization checks. Prevents authorization bypasses arising from stale permission revocations (New Enemy Problem) and mitigates upstream OpenFGA graph amplification and cache stampedes under high concurrency.
globs: src/**/auth/**/*.{ts,js,go}, src/**/guards/**/*.{ts,js,go}, src/**/security/**/*.{ts,js,go}, src/**/authorization/**/*.{ts,js,go}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/openfga-distributed-tuple-cache-consistency-standard"
---

# OpenFGA Distributed ReBAC Tuple Evaluation & Cache Stampede Elimination Standard

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Naive Tuple Key-Value Caching with Uncoordinated In-Flight Graph Traversals and Stale Consistency Tokens

## System Constraints
You are a Principal Software Architect enforcing zero-trust relationship-based access control (ReBAC) cache consistency. Every OpenFGA authorization check MUST eliminate graph evaluation amplification and cache stampedes using request coalescing (singleflight), causal consistency tokens, and schema-bound tuple hashing. Under no circumstances may an authorization check return unvalidated stale tuples or execute unbounded parallel ReBAC graph queries.

## Strict Guidelines
- Engineers MUST ALWAYS bound authorization cache keys to the specific `store_id`, `authorization_model_id`, and deterministic contextual tuple digest.
- Engineers MUST NOT implement uncoordinated read-through caches for OpenFGA `check` requests without in-process singleflight / promise-coalescing to avoid cache stampedes on hot graph paths.
- Services MUST enforce causal consistency tokens (`consistency: ConsistencyPreference.HIGHER_CONSISTENCY` or contextual tokens) on read-after-write mutations to prevent the New Enemy problem.
- Code SHOULD implement probabilistic early expiration (e.g., XFetch algorithm) or aggressive negative cache limits (TTL <= 2s) to prevent persistent bypasses from revoked relations.
- Components NEVER store OpenFGA evaluations in global distributed caches without an event-driven invalidation pipeline subscribed to OpenFGA store changelog streams.

## Bad vs Good Implementations
### OpenFGA Resilient Coalesced Check with Causal Consistency Guard

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Suffers from cache stampedes on hot objects, exposes the system to the 'New Enemy' stale authorization vulnerability due to static TTL without causal tokens, and does not pin the authorization_model_id, risking model drift evaluation mismatches.
```typescript
import { OpenFgaClient } from '@openfga/sdk';
import Redis from 'ioredis';

const fgaClient = new OpenFgaClient({
  apiUrl: process.env.FGA_API_URL!,
  storeId: process.env.FGA_STORE_ID!,
});
const redis = new Redis();

// VULNERABLE: Naive distributed cache without singleflight, no modelId pinning, no consistency token
export async function checkAccess(user: string, relation: string, object: string): Promise<boolean> {
  const cacheKey = `fga:${user}:${relation}:${object}`;
  const cached = await redis.get(cacheKey);
  if (cached !== null) {
    return cached === 'true';
  }

  // Cache stampede: 50,000 concurrent requests trigger 50,000 recursive graph traversals
  const { allowed } = await fgaClient.check({
    user,
    relation,
    object,
  });

  // Stale ACL: revocation of relation remains masked for 5 minutes (New Enemy vulnerability)
  await redis.setex(cacheKey, 300, String(allowed));
  return allowed ?? false;
}
```

#### Production Standard (Correct)
> **Standard**: Implements in-flight request coalescing (singleflight), binds the cache key to the store and model version, supports Causal Consistency preferences for read-after-write operations, and enforces minimal TTLs to limit revocation lag.
```typescript
import { OpenFgaClient, ConsistencyPreference, ClientCheckRequest } from '@openfga/sdk';
import Redis from 'ioredis';
import { createHash } from 'node:crypto';

const fgaClient = new OpenFgaClient({
  apiUrl: process.env.FGA_API_URL!,
  storeId: process.env.FGA_STORE_ID!,
  authorizationModelId: process.env.FGA_MODEL_ID!,
});
const redis = new Redis();

// In-process singleflight coordinator to prevent local stampedes
const inFlightChecks = new Map<string, Promise<boolean>>();

export interface GuardedCheckOptions {
  causalConsistencyToken?: string;
  contextualTuples?: ClientCheckRequest['contextualTuples'];
}

export async function checkAccess(
  user: string,
  relation: string,
  object: string,
  opts: GuardedCheckOptions = {}
): Promise<boolean> {
  const modelId = fgaClient.getAuthorizationModelId();
  const ctxHash = opts.contextualTuples 
    ? createHash('sha256').update(JSON.stringify(opts.contextualTuples)).digest('hex')
    : 'none';
  
  // Deterministic schema-bound cache key incorporating store and model
  const cacheKey = `fga:${fgaClient.getStoreId()}:${modelId}:${user}:${relation}:${object}:${ctxHash}`;

  // Bypass cache if strict causal consistency is mandated by a write-token
  if (!opts.causalConsistencyToken) {
    const cached = await redis.get(cacheKey);
    if (cached !== null) {
      return cached === '1';
    }
  }

  // Request coalescing: collapse concurrent identical evaluation graph queries
  if (inFlightChecks.has(cacheKey)) {
    return inFlightChecks.get(cacheKey)!;
  }

  const checkPromise = (async () => {
    try {
      const response = await fgaClient.check({
        user,
        relation,
        object,
        contextualTuples: opts.contextualTuples,
      }, {
        consistency: opts.causalConsistencyToken 
          ? ConsistencyPreference.HigherConsistency 
          : ConsistencyPreference.MinimizeLatency,
      });

      const allowed = response.allowed ?? false;
      // Short TTL with probabilistic early expiration buffer; reject long-lived stale grants
      const ttlSeconds = allowed ? 5 : 2; // Strict low TTL for negatives and fast revocation convergence
      await redis.set(cacheKey, allowed ? '1' : '0', 'EX', ttlSeconds);
      return allowed;
    } finally {
      inFlightChecks.delete(cacheKey);
    }
  })();

  inFlightChecks.set(cacheKey, checkPromise);
  return checkPromise;
}
```

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 ReBAC Tuple Evaluation & Cache Stampede Elimination Standard

OpenFGA Distributed ReBAC Tuple Evaluation & Cache Stampede Elimination Standard defines an industrial-grade behavioral standard for security engineering. Enforces deterministic ReBAC graph evaluation coalescing, model-version-bound cache keys, and causal consistency token propagation for OpenFGA authorization checks. Prevents authorization bypasses arising from stale permission revocations (New Enemy Problem) and mitigates upstream OpenFGA graph amplification and cache stampedes under high concurrency. 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: Naive Tuple Key-Value Caching with Uncoordinated In-Flight Graph Traversals and Stale Consistency Tokens 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 DriftNaive Tuple Key-Value Caching with Uncoordinated In-Flight Graph Traversals and Stale Consistency TokensCritical
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 bound authorization cache keys to the specific `store_id`, `authorization_model_id`, and deterministic contextual tuple digest.

Engineers MUST ALWAYS bound authorization cache keys to the specific `store_id`, `authorization_model_id`, and deterministic contextual tuple digest.

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 implement uncoordinated read-through caches for OpenFGA `check` requests without in-process singleflight / promise-coalescing to avoid cache stampedes on hot graph paths.

Engineers MUST NOT implement uncoordinated read-through caches for OpenFGA `check` requests without in-process singleflight / promise-coalescing to avoid cache stampedes on hot graph paths.

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 enforce causal consistency tokens (`consistency

Services MUST enforce causal consistency tokens (`consistency: ConsistencyPreference.HIGHER_CONSISTENCY` or contextual tokens) on read-after-write mutations to prevent the New Enemy problem.

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 SHOULD implement probabilistic early expiration (e.g., XFetch algorithm) or aggressive negative cache limits (TTL <= 2s) to prevent persistent bypasses from revoked relations.

Code SHOULD implement probabilistic early expiration (e.g., XFetch algorithm) or aggressive negative cache limits (TTL <= 2s) to prevent persistent bypasses from revoked relations.

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 store OpenFGA evaluations in global distributed caches without an event-driven invalidation pipeline subscribed to OpenFGA store changelog streams.

Components NEVER store OpenFGA evaluations in global distributed caches without an event-driven invalidation pipeline subscribed to OpenFGA store changelog streams.

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 ReBAC Tuple Evaluation & Cache Stampede Elimination Standard critical for AI coding assistants?

Enforces deterministic ReBAC graph evaluation coalescing, model-version-bound cache keys, and causal consistency token propagation for OpenFGA authorization checks. Prevents authorization bypasses arising from stale permission revocations (New Enemy Problem) and mitigates upstream OpenFGA graph amplification and cache stampedes under high concurrency. 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 (Naive Tuple Key-Value Caching with Uncoordinated In-Flight Graph Traversals and Stale Consistency Tokens) 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