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

OpenFGA Real-Time ReBAC Tuple Evaluation & Invalidation Caching Standard

Enforces sub-millisecond fine-grained authorization evaluations while preventing stale permissions and TOCTOU vulnerabilities. Combines event-driven distributed cache invalidation via change-data-capture (CDC) or transactional outbox with OpenFGA contextual tuples for dynamic request attributes.

Prohibited Anti-Pattern: Unbounded TTL Caching of Authorization Checks Without Graph-Aware Invalidation

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenFGA Real-Time ReBAC Tuple Evaluation & Invalidation Caching Standard - Enforces sub-millisecond fine-grained authorization evaluations while preventing stale permissions and TOCTOU vulnerabilities. Combines event-driven distributed cache invalidation via change-data-capture (CDC) or transactional outbox with OpenFGA contextual tuples for dynamic request attributes.
globs: src/auth/**/*.{ts,tsx}, src/lib/fga/**/*.{ts,tsx}, src/services/authorization/**/*.{ts,tsx}, src/middleware/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/openfga-rebac-realtime-cache-invalidation"
---

# OpenFGA Real-Time ReBAC Tuple Evaluation & Invalidation Caching Standard

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Unbounded TTL Caching of Authorization Checks Without Graph-Aware Invalidation

## System Constraints
You are a Principal Security & Distributed Systems Architect enforcing OpenFGA Real-Time ReBAC Tuple Evaluation & Invalidation Caching. Mandate invariants that eliminate stale permission evaluations, prevent static TTL caching over authorization decisions, and enforce explicit contextual tuples for request-scoped variables.

## Strict Guidelines
- Engineers MUST ALWAYS invalidate distributed and local authorization caches immediately upon relationship tuple mutations using a Transactional Outbox or CDC event stream.
- Engineers MUST NOT cache authorization check responses with static, long-lived TTLs without a connected event-driven invalidation mechanism.
- Code MUST pass dynamic, ephemeral, or request-scoped attributes (e.g., IP address, transient roles, time-of-day, tenant context) via OpenFGA Contextual Tuples rather than persisting short-lived records to the OpenFGA datastore.
- Services MUST incorporate the OpenFGA `authorization_model_id` into all cache keys to ensure atomic cache segregation during schema migrations.
- Evaluations involving non-empty Contextual Tuples MUST bypass shared global caches to avoid cross-request permission leakage and security pollution.
- Components NEVER treat a cache failure as a reason to grant access; authorization evaluation failures MUST fail closed (deny by default).

## Bad vs Good Implementations
### Naive TTL Check Caching vs. Event-Invalidated Contextual Check

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The check result is stored in Redis for 10 minutes with no mechanism to invalidate on tuple deletion or permission revocation. It completely ignores request-scoped security signals (like user IP) and omits the authorization model ID from the cache key, causing cross-model contamination on schema updates.
```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();

// ANTI-PATTERN: Naive static TTL caching creates TOCTOU security windows.
// If an admin revokes document access, user retains access for 10 minutes.
// Ignores dynamic request context and misses schema version partitioning.
export async function checkAccess(
  userId: string,
  relation: string,
  documentId: string,
  userIp: string
): Promise<boolean> {
  const cacheKey = `auth:${userId}:${relation}:${documentId}`;
  const cached = await redis.get(cacheKey);
  if (cached !== null) {
    return cached === '1';
  }

  const { allowed } = await fgaClient.check({
    user: `user:${userId}`,
    relation,
    object: `document:${documentId}`,
  });

  // Stale state vulnerability: persistent 10-minute cache with zero invalidation hook
  await redis.set(cacheKey, allowed ? '1' : '0', 'EX', 600);
  return allowed ?? false;
}
```

#### Production Standard (Correct)
> **Standard**: Includes the authorization model ID in the cache key, segregates and bypasses caching when dynamic contextual tuples are used, enforces a fail-closed error strategy, and provides an explicit event hook (`handleTupleMutationEvent`) to evict stale entries in real time.
```typescript
import { OpenFgaClient, ClientCheckRequest } from '@openfga/sdk';
import { createHash } from 'node:crypto';

interface AuthorizationContext {
  ipAddress?: string;
  isBreakGlass?: boolean;
}

export class ResilientAuthorizationService {
  constructor(
    private readonly fgaClient: OpenFgaClient,
    private readonly localCache: Map<string, { allowed: boolean; expiresAt: number }>,
    private readonly activeModelId: string
  ) {}

  public async checkAccess(
    userId: string,
    relation: string,
    documentId: string,
    context?: AuthorizationContext
  ): Promise<boolean> {
    const user = `user:${userId}`;
    const object = `document:${documentId}`;

    // Contextual tuples for dynamic/ephemeral conditions
    const contextualTuples: ClientCheckRequest['contextualTuples'] = [];
    if (context?.isBreakGlass) {
      contextualTuples.push({
        user,
        relation: 'emergency_responder',
        object,
      });
    }

    // Never read/write global cache when request-scoped contextual tuples exist
    if (contextualTuples.length > 0) {
      const response = await this.fgaClient.check({
        user,
        relation,
        object,
        contextualTuples,
      }, {
        authorizationModelId: this.activeModelId,
      });
      return response.allowed ?? false;
    }

    const cacheKey = this.buildCacheKey(this.activeModelId, user, relation, object);
    const cached = this.localCache.get(cacheKey);
    if (cached && cached.expiresAt > Date.now()) {
      return cached.allowed;
    }

    // Fail-closed execution
    try {
      const response = await this.fgaClient.check({
        user,
        relation,
        object,
      }, {
        authorizationModelId: this.activeModelId,
      });

      const allowed = response.allowed ?? false;
      // Store with strict short safety bound (max 30s) alongside proactive event invalidation
      this.localCache.set(cacheKey, {
        allowed,
        expiresAt: Date.now() + 30_000,
      });

      return allowed;
    } catch (error) {
      // Security invariant: Fail closed on downstream auth failures
      return false;
    }
  }

  // Called by Kafka/RabbitMQ consumer reacting to OpenFGA tuple changes
  public handleTupleMutationEvent(event: { user: string; relation: string; object: string }): void {
    const cacheKey = this.buildCacheKey(this.activeModelId, event.user, event.relation, event.object);
    this.localCache.delete(cacheKey);
  }

  private buildCacheKey(modelId: string, user: string, relation: string, object: string): string {
    return `fga:${modelId}:${user}:${relation}:${object}`;
  }
}
```

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 Real-Time ReBAC Tuple Evaluation & Invalidation Caching Standard

OpenFGA Real-Time ReBAC Tuple Evaluation & Invalidation Caching Standard defines an industrial-grade behavioral standard for security engineering. Enforces sub-millisecond fine-grained authorization evaluations while preventing stale permissions and TOCTOU vulnerabilities. Combines event-driven distributed cache invalidation via change-data-capture (CDC) or transactional outbox with OpenFGA contextual tuples for dynamic request attributes. 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: Unbounded TTL Caching of Authorization Checks Without Graph-Aware Invalidation 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 DriftUnbounded TTL Caching of Authorization Checks Without Graph-Aware InvalidationCritical
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 invalidate distributed and local authorization caches immediately upon relationship tuple mutations using a Transactional Outbox or CDC event stream.

Engineers MUST ALWAYS invalidate distributed and local authorization caches immediately upon relationship tuple mutations using a Transactional Outbox or CDC event stream.

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 authorization check responses with static, long-lived TTLs without a connected event-driven invalidation mechanism.

Engineers MUST NOT cache authorization check responses with static, long-lived TTLs without a connected event-driven invalidation mechanism.

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

Code MUST pass dynamic, ephemeral, or request-scoped attributes (e.g., IP address, transient roles, time-of-day, tenant context) via OpenFGA Contextual Tuples rather than persisting short-lived records to the OpenFGA datastore.

Code MUST pass dynamic, ephemeral, or request-scoped attributes (e.g., IP address, transient roles, time-of-day, tenant context) via OpenFGA Contextual Tuples rather than persisting short-lived records to the OpenFGA datastore.

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

Services MUST incorporate the OpenFGA `authorization_model_id` into all cache keys to ensure atomic cache segregation during schema migrations.

Services MUST incorporate the OpenFGA `authorization_model_id` into all cache keys to ensure atomic cache segregation during schema migrations.

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

Evaluations involving non-empty Contextual Tuples MUST bypass shared global caches to avoid cross-request permission leakage and security pollution.

Evaluations involving non-empty Contextual Tuples MUST bypass shared global caches to avoid cross-request permission leakage and security pollution.

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.
6

Components NEVER treat a cache failure as a reason to grant access

Components NEVER treat a cache failure as a reason to grant access; authorization evaluation failures MUST fail closed (deny by default).

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 Real-Time ReBAC Tuple Evaluation & Invalidation Caching Standard critical for AI coding assistants?

Enforces sub-millisecond fine-grained authorization evaluations while preventing stale permissions and TOCTOU vulnerabilities. Combines event-driven distributed cache invalidation via change-data-capture (CDC) or transactional outbox with OpenFGA contextual tuples for dynamic request attributes. 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 (Unbounded TTL Caching of Authorization Checks Without Graph-Aware Invalidation) 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