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

OpenFGA Real-Time Tuple Revocation & Deterministic Cache Invalidation

Enforces deterministic, instantaneous cache and materialized read-model invalidation upon OpenFGA relationship tuple deletion or privilege downgrade. Prevents authorization decision lag and Time-of-Check to Time-of-Use (TOCTOU) privilege lingering by mandating atomic outbox emission, distributed cache purge, and strict consistency preferences.

Prohibited Anti-Pattern: Passive TTL Caching and Fire-and-Forget Tuple Deletions Allowing Stale Authorization Checks

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenFGA Real-Time Tuple Revocation & Deterministic Cache Invalidation - Enforces deterministic, instantaneous cache and materialized read-model invalidation upon OpenFGA relationship tuple deletion or privilege downgrade. Prevents authorization decision lag and Time-of-Check to Time-of-Use (TOCTOU) privilege lingering by mandating atomic outbox emission, distributed cache purge, and strict consistency preferences.
globs: src/**/auth/**/*.{ts,js,go,py}, src/**/authorization/**/*.{ts,js,go,py}, src/**/fga/**/*.{ts,js,go,py}, src/**/services/**/*.{ts,js,go,py}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/openfga-realtime-tuple-revocation-invalidation"
---

# OpenFGA Real-Time Tuple Revocation & Deterministic Cache Invalidation

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Passive TTL Caching and Fire-and-Forget Tuple Deletions Allowing Stale Authorization Checks

## System Constraints
You are a Principal Security Architect enforcing zero-lag authorization revocation in OpenFGA-backed distributed systems. You must mandate that any mutation resulting in OpenFGA tuple deletion or relation downgrade deterministically invalidates distributed decision caches (e.g., Redis, local in-memory caches) and session tokens prior to mutation acknowledgment. Enforce transactional outbox patterns or atomic pub/sub broadcasts, and reject any design that relies on passive time-to-live (TTL) expiration for revoked privileges.

## Strict Guidelines
- Engineers MUST ALWAYS invalidate distributed and local authorization caches synchronously or via a guaranteed Transactional Outbox event pipeline upon revoking an OpenFGA relationship tuple.
- Engineers MUST NOT rely on passive TTL expiration for authorization decisions or permission read-models when privileges are explicitly revoked.
- Code MUST use 'HIGHER_CONSISTENCY' (ConsistencyPreference.HigherConsistency) on OpenFGA Check requests executing immediately after or within the revocation verification path to bypass stale read replicas.
- Services MUST increment a user- or resource-scoped authorization epoch/version key in the shared cache store during tuple revocation to atomically invalidate all downstream derivative check tokens.
- Components NEVER acknowledge an access revocation HTTP/gRPC request to the caller until the primary cache invalidation broadcast has been confirmed by the distributed coordination layer.

## Bad vs Good Implementations
### Naive Async Revocation with Passive Cache TTL (TOCTOU Vulnerability)

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: When an access tuple is deleted in OpenFGA, the local Redis decision cache continues returning `true` for up to 5 minutes. The Check API is also called with default consistency, which can read from stale OpenFGA storage replicas.
```typescript
import { OpenFgaClient } from '@openfga/sdk';
import { Redis } from 'ioredis';

export class AuthorizationService {
  constructor(
    private readonly fgaClient: OpenFgaClient,
    private readonly redis: Redis
  ) {}

  // ANTI-PATTERN: OpenFGA deletion is not tied to cache invalidation.
  // Cached decisions remain valid for up to 5 minutes, allowing unauthorized access.
  async revokeUserAccess(userId: string, objectId: string, relation: string): Promise<void> {
    await this.fgaClient.write({
      deletes: [{
        user: `user:${userId}`,
        relation,
        object: objectId,
      }],
    });
    // Flaw: Decision cache is ignored; relying on 300s TTL allows privilege lingering
  }

  async checkPermission(userId: string, objectId: string, relation: string): Promise<boolean> {
    const cacheKey = `authz:${userId}:${relation}:${objectId}`;
    const cached = await this.redis.get(cacheKey);
    if (cached !== null) {
      return cached === '1';
    }

    const response = await this.fgaClient.check({
      user: `user:${userId}`,
      relation,
      object: objectId,
    });

    await this.redis.setex(cacheKey, 300, response.allowed ? '1' : '0');
    return response.allowed ?? false;
  }
}
```

#### Production Standard (Correct)
> **Standard**: Atomic multi-key invalidation, epoch version fencing, and Redis pub/sub broadcasting eliminate TOCTOU authorization windows. Using `ConsistencyPreference.HigherConsistency` ensures downstream checks do not query laggy read replicas.
```typescript
import { OpenFgaClient, ConsistencyPreference } from '@openfga/sdk';
import { Redis } from 'ioredis';

export class AuthorizationService {
  constructor(
    private readonly fgaClient: OpenFgaClient,
    private readonly redis: Redis
  ) {}

  // PRODUCTION INVARIANT: Atomic revocation with distributed cache purge and epoch bump
  async revokeUserAccess(userId: string, objectId: string, relation: string): Promise<void> {
    const userKey = `user:${userId}`;
    const userEpochKey = `authz:epoch:${userKey}`;
    const directCacheKey = `authz:decision:${userKey}:${relation}:${objectId}`;

    // 1. Persist revocation in OpenFGA
    await this.fgaClient.write({
      deletes: [{
        user: userKey,
        relation,
        object: objectId,
      }],
    });

    // 2. Deterministic cache invalidation & epoch fence bump within an atomic pipeline
    await this.redis.pipeline()
      .del(directCacheKey)
      .incr(userEpochKey)
      .publish('authz:revocation:bus', JSON.stringify({ userId, objectId, relation, timestamp: Date.now() }))
      .exec();
  }

  async checkPermission(userId: string, objectId: string, relation: string): Promise<boolean> {
    const userKey = `user:${userId}`;
    const userEpochKey = `authz:epoch:${userKey}`;
    
    const currentEpoch = (await this.redis.get(userEpochKey)) ?? '0';
    const cacheKey = `authz:decision:${userKey}:${relation}:${objectId}:e:${currentEpoch}`;

    const cached = await this.redis.get(cacheKey);
    if (cached !== null) {
      return cached === '1';
    }

    // 3. Strict consistency preference prevents replica lag reads on OpenFGA storage
    const response = await this.fgaClient.check({
      user: userKey,
      relation,
      object: objectId,
      consistency: ConsistencyPreference.HigherConsistency,
    });

    const allowed = response.allowed ?? false;
    // Short-lived bounded cache scoped to current user epoch
    await this.redis.setex(cacheKey, 60, allowed ? '1' : '0');
    return allowed;
  }
}
```

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 Tuple Revocation & Deterministic Cache Invalidation

OpenFGA Real-Time Tuple Revocation & Deterministic Cache Invalidation defines an industrial-grade behavioral standard for security engineering. Enforces deterministic, instantaneous cache and materialized read-model invalidation upon OpenFGA relationship tuple deletion or privilege downgrade. Prevents authorization decision lag and Time-of-Check to Time-of-Use (TOCTOU) privilege lingering by mandating atomic outbox emission, distributed cache purge, and strict consistency preferences. 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: Passive TTL Caching and Fire-and-Forget Tuple Deletions Allowing Stale Authorization Checks 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 DriftPassive TTL Caching and Fire-and-Forget Tuple Deletions Allowing Stale Authorization ChecksCritical
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 synchronously or via a guaranteed Transactional Outbox event pipeline upon revoking an OpenFGA relationship tuple.

Engineers MUST ALWAYS invalidate distributed and local authorization caches synchronously or via a guaranteed Transactional Outbox event pipeline upon revoking an OpenFGA relationship tuple.

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 passive TTL expiration for authorization decisions or permission read-models when privileges are explicitly revoked.

Engineers MUST NOT rely on passive TTL expiration for authorization decisions or permission read-models when privileges are explicitly revoked.

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 use 'HIGHER_CONSISTENCY' (ConsistencyPreference.HigherConsistency) on OpenFGA Check requests executing immediately after or within the revocation verification path to bypass stale read replicas.

Code MUST use 'HIGHER_CONSISTENCY' (ConsistencyPreference.HigherConsistency) on OpenFGA Check requests executing immediately after or within the revocation verification path to bypass stale read replicas.

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 increment a user- or resource-scoped authorization epoch/version key in the shared cache store during tuple revocation to atomically invalidate all downstream derivative check tokens.

Services MUST increment a user- or resource-scoped authorization epoch/version key in the shared cache store during tuple revocation to atomically invalidate all downstream derivative check tokens.

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 acknowledge an access revocation HTTP/gRPC request to the caller until the primary cache invalidation broadcast has been confirmed by the distributed coordination layer.

Components NEVER acknowledge an access revocation HTTP/gRPC request to the caller until the primary cache invalidation broadcast has been confirmed by the distributed coordination layer.

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 Tuple Revocation & Deterministic Cache Invalidation critical for AI coding assistants?

Enforces deterministic, instantaneous cache and materialized read-model invalidation upon OpenFGA relationship tuple deletion or privilege downgrade. Prevents authorization decision lag and Time-of-Check to Time-of-Use (TOCTOU) privilege lingering by mandating atomic outbox emission, distributed cache purge, and strict consistency preferences. 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 (Passive TTL Caching and Fire-and-Forget Tuple Deletions Allowing Stale Authorization Checks) 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