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

OpenFGA ReBAC Sub-Millisecond Graph Authorization and Cache Invalidation Invariant

Enforces sub-millisecond OpenFGA relationship-based access control (ReBAC) evaluations while guaranteeing zero stale-graph traversals. Mandates strict fail-closed authorization boundaries, deterministic transactional tuple synchronization via transactional outbox patterns, request-scoped contextual tuples, and precise cache invalidation across distributed services.

Prohibited Anti-Pattern: Stale Tuple Authorization Bypasses and Fail-Open Distributed In-Memory Caching

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenFGA ReBAC Sub-Millisecond Graph Authorization and Cache Invalidation Invariant - Enforces sub-millisecond OpenFGA relationship-based access control (ReBAC) evaluations while guaranteeing zero stale-graph traversals. Mandates strict fail-closed authorization boundaries, deterministic transactional tuple synchronization via transactional outbox patterns, request-scoped contextual tuples, and precise cache invalidation across distributed services.
globs: src/auth/**/*.ts, src/guards/**/*.ts, src/services/**/*.ts, src/lib/fga/**/*.ts, src/middleware/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/openfga-rebac-graph-auth-cache-invalidation-standard"
---

# OpenFGA ReBAC Sub-Millisecond Graph Authorization and Cache Invalidation Invariant

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Stale Tuple Authorization Bypasses and Fail-Open Distributed In-Memory Caching

## System Constraints
You are a Principal Engineer enforcing OpenFGA Real-Time Relationship-Based Access Control (ReBAC). Mandate strict real-time authorization checks, transactional tuple lifecycle management, fail-closed access evaluations, and deterministic cache invalidation to prevent privilege escalation via stale relationship graphs.

## Strict Guidelines
- Engineers MUST ALWAYS enforce fail-closed evaluation: any OpenFGA network timeout, circuit breaker trip, or traversal error MUST evaluate strictly to `allowed: false`.
- Engineers MUST NOT cache positive authorization decisions without deterministic, event-driven cache invalidation keyed directly to OpenFGA tuple relationship identifiers (e.g., `user:<id>#relation@object:<id>`).
- Services MUST synchronize relationship tuple writes and deletes with primary database mutations using a Transactional Outbox pattern or atomic two-phase commit to prevent split-brain authorization states.
- Engineers MUST leverage OpenFGA `contextual_tuples` for ephemeral request attributes (e.g., resource lease, step-up MFA, IP boundary) rather than mutating persistent store tuples.
- Components NEVER store or trust static permission flags inside long-lived JWTs or local session states; relationship graph resolution MUST occur on every state-mutating and sensitive read operation.

## Bad vs Good Implementations
### Fail-Open Naive Check with Stale Unbounded Redis Cache vs. Fail-Closed ReBAC Invalidation Wrapper

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The bad example caches authorization decisions for 1 hour without event-driven invalidation, allowing revoked users access. Crucially, it fails open on network errors, creating a catastrophic security bypass during FGA degraded states.
```typescript
import { OpenFgaClient } from '@openfga/sdk';
import { redis } from '../redis';

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

export async function authorizeUser(userId: string, relation: string, documentId: string): Promise<boolean> {
  const cacheKey = `auth:${userId}:${relation}:${documentId}`;
  const cached = await redis.get(cacheKey);
  if (cached) return cached === 'true'; // Stale: ignores real-time revocation in OpenFGA

  try {
    const { allowed } = await fga.check({
      user: `user:${userId}`,
      relation,
      object: `document:${documentId}`
    });
    await redis.set(cacheKey, allowed ? 'true' : 'false', 'EX', 3600); // Dangerously long 1h TTL without invalidation
    return allowed ?? false;
  } catch (error) {
    // ANTI-PATTERN: Failing open under load or transient network failure
    console.error('FGA check failed, granting fallback access', error);
    return true;
  }
}
```

#### Production Standard (Correct)
> **Standard**: Enforces verified production invariants and compliant error handling.
```typescript
import { OpenFgaClient, ClientCheckRequest } from '@openfga/sdk';
import { redis } from '../redis';
import { logger } from '../logger';

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

interface CheckOptions {
  contextualTuples?: Array<{
    user: string;
    relation: string;
    object: string;
  }>;
}

export async function authorizeUser(
  userId: string,
  relation: string,
  documentId: string,
  opts: CheckOptions = {}
): Promise<boolean> {
  const objectKey = `document:${documentId}`;
  const userKey = `user:${userId}`;
  const cacheKey = `fga:cache:${userKey}#${relation}@${objectKey}`;

  // Ephemeral sub-second micro-cache strictly for burst request deduplication
  const cached = await redis.get(cacheKey).catch(() => null);
  if (cached !== null) {
    return cached === '1';
  }

  const checkPayload: ClientCheckRequest = {
    user: userKey,
    relation,
    object: objectKey,
    contextualTuples: opts.contextualTuples
  };

  try {
    const response = await fga.check(checkPayload);
    const isAllowed = response.allowed ?? false;

    // Bound micro-cache (maximum 5 seconds) to tolerate rapid read spikes safely
    if (isAllowed) {
      await redis.set(cacheKey, '1', 'EX', 5).catch((err) => {
        logger.warn({ err }, 'FGA cache write failure; continuing without cache');
      });
    }

    return isAllowed;
  } catch (error) {
    // INVARIANT: Fail-closed on any error or timeout
    logger.error({ error, userKey, relation, objectKey }, 'OpenFGA evaluation failed - access denied');
    return false;
  }
}

export async function invalidateObjectRelations(documentId: string): Promise<void> {
  const pattern = `fga:cache:*@document:${documentId}`;
  const stream = redis.scanStream({ match: pattern, count: 100 });
  stream.on('data', async (keys: string[]) => {
    if (keys.length > 0) {
      const pipeline = redis.pipeline();
      keys.forEach((k) => pipeline.del(k));
      await pipeline.exec();
    }
  });
}
```

Recommended Agent Skills (askills.dev)

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

Architectural Specification & Invariant Rationale

Architectural Invariant Design: OpenFGA ReBAC Sub-Millisecond Graph Authorization and Cache Invalidation Invariant

OpenFGA ReBAC Sub-Millisecond Graph Authorization and Cache Invalidation Invariant defines an industrial-grade behavioral standard for security engineering. Enforces sub-millisecond OpenFGA relationship-based access control (ReBAC) evaluations while guaranteeing zero stale-graph traversals. Mandates strict fail-closed authorization boundaries, deterministic transactional tuple synchronization via transactional outbox patterns, request-scoped contextual tuples, and precise cache invalidation across distributed services. 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: Stale Tuple Authorization Bypasses and Fail-Open Distributed In-Memory Caching 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 DriftStale Tuple Authorization Bypasses and Fail-Open Distributed In-Memory CachingCritical
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 enforce fail-closed evaluation

Engineers MUST ALWAYS enforce fail-closed evaluation: any OpenFGA network timeout, circuit breaker trip, or traversal error MUST evaluate strictly to `allowed: false`.

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 cache positive authorization decisions without deterministic, event-driven cache invalidation keyed directly to OpenFGA tuple relationship identifiers (e.g., `user

Engineers MUST NOT cache positive authorization decisions without deterministic, event-driven cache invalidation keyed directly to OpenFGA tuple relationship identifiers (e.g., `user:<id>#relation@object:<id>`).

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 synchronize relationship tuple writes and deletes with primary database mutations using a Transactional Outbox pattern or atomic two-phase commit to prevent split-brain authorization states.

Services MUST synchronize relationship tuple writes and deletes with primary database mutations using a Transactional Outbox pattern or atomic two-phase commit to prevent split-brain authorization states.

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 leverage OpenFGA `contextual_tuples` for ephemeral request attributes (e.g., resource lease, step-up MFA, IP boundary) rather than mutating persistent store tuples.

Engineers MUST leverage OpenFGA `contextual_tuples` for ephemeral request attributes (e.g., resource lease, step-up MFA, IP boundary) rather than mutating persistent store tuples.

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 or trust static permission flags inside long-lived JWTs or local session states

Components NEVER store or trust static permission flags inside long-lived JWTs or local session states; relationship graph resolution MUST occur on every state-mutating and sensitive read operation.

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 ReBAC Sub-Millisecond Graph Authorization and Cache Invalidation Invariant critical for AI coding assistants?

Enforces sub-millisecond OpenFGA relationship-based access control (ReBAC) evaluations while guaranteeing zero stale-graph traversals. Mandates strict fail-closed authorization boundaries, deterministic transactional tuple synchronization via transactional outbox patterns, request-scoped contextual tuples, and precise cache invalidation across distributed services. 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 (Stale Tuple Authorization Bypasses and Fail-Open Distributed In-Memory Caching) 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