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

OpenFGA Distributed ReBAC Decision Caching & Outbox Invalidation

Mandates strict deterministic keying for local OpenFGA decision caching alongside transactional outbox-driven CDC tuple invalidation. Prevents authorization bypasses and New Enemy Problem vulnerabilities caused by stale edge-evaluated Zanzibar relationship tuples.

Prohibited Anti-Pattern: Naive TTL caching of OpenFGA checks coupled with fire-and-forget tuple invalidation

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenFGA Distributed ReBAC Decision Caching & Outbox Invalidation - Mandates strict deterministic keying for local OpenFGA decision caching alongside transactional outbox-driven CDC tuple invalidation. Prevents authorization bypasses and New Enemy Problem vulnerabilities caused by stale edge-evaluated Zanzibar relationship tuples.
globs: src/**/*.ts, src/**/*.service.ts, src/**/*.worker.ts, lib/auth/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/openfga-rebac-outbox-cache-invalidation-guardrail"
---

# OpenFGA Distributed ReBAC Decision Caching & Outbox Invalidation

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Naive TTL caching of OpenFGA checks coupled with fire-and-forget tuple invalidation

## System Constraints
You are a Principal Security Architect enforcing Zanzibar-style ReBAC invariants with OpenFGA. You mandate deterministic decision caching, transactional outbox patterns for tuple writes/deletes, and strict cryptographic key synthesis incorporating authorization model IDs and contextual tuples.

## Strict Guidelines
- Engineers MUST ALWAYS include authorization_model_id, store_id, canonical user, relation, object, and hashed contextual_tuples in the local decision cache key.
- Engineers MUST NOT mutate OpenFGA tuples via direct, un-instrumented API calls without simultaneously recording a transactional outbox event in the primary operational database.
- Services MUST route all tuple lifecycle changes through durable Change Data Capture (CDC) or event brokers (e.g., Kafka) to invalidate L1 (in-process) and L2 (distributed) decision caches.
- Components NEVER assume fixed-time TTL caching is sufficient for permission revocations; write-time invalidation MUST propagate before state mutations commit to clients.
- Code SHOULD enforce consistency tokens (Zookies or minimum snapshotted revision timestamps) during checks to guarantee monotonic read consistency and eliminate the New Enemy Problem.

## Bad vs Good Implementations
### Naive TTL Caching vs Outbox-Driven CDC Decision Caching

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The naive implementation suffers from the 'New Enemy Problem' and cache staleness. Cache keys ignore model IDs and contextual tuples, and revocations do not reliably invalidate distributed cache instances. A revoked user retains access for up to 5 minutes.
```typescript
import { OpenFgaClient } from '@openfga/sdk';

const cache = new Map<string, boolean>();

export async function checkAccessNaive(
  fgaClient: OpenFgaClient,
  user: string,
  relation: string,
  object: string
): Promise<boolean> {
  // Flaw 1: Cache key omits authorization_model_id and contextual tuples
  const key = `${user}:${relation}:${object}`;
  if (cache.has(key)) {
    return cache.get(key)!;
  }

  // Flaw 2: Using MINIMAL_CONSISTENCY with static un-invalidated TTL allows revoked grants to persist indefinitely
  const { allowed } = await fgaClient.check({
    user,
    relation,
    object,
  });

  cache.set(key, allowed ?? false);
  setTimeout(() => cache.delete(key), 300_000); // 5 minute blind TTL
  return allowed ?? false;
}

export async function revokeAccessNaive(
  fgaClient: OpenFgaClient,
  user: string,
  relation: string,
  object: string
) {
  // Flaw 3: In-memory cache is never invalidated across distributed instances, and network failures drop the revocation
  await fgaClient.write({
    deletes: [{ user, relation, object }],
  });
}
```

#### Production Standard (Correct)
> **Standard**: The production implementation constructs deterministic, collision-resistant cache keys incorporating the model ID, canonical tuple, and sorted hashed contextual tuples. Revocations are persisted atomically to an outbox table, allowing reliable CDC pipelines to bust L1/L2 caches across all distributed nodes.
```typescript
import { OpenFgaClient, ClientCheckRequest } from '@openfga/sdk';
import { createHash } from 'node:crypto';
import { Redis } from 'ioredis';
import { PrismaClient } from '@prisma/client';

interface EdgeCheckRequest extends ClientCheckRequest {
  authorizationModelId: string;
  storeId: string;
}

export class RebacDecisionCache {
  constructor(private redis: Redis) {}

  public generateKey(req: EdgeCheckRequest): string {
    const sortedContextualTuples = (req.contextualTuples || [])
      .map(t => `${t.user}#${t.relation}@${t.object}`)
      .sort()
      .join('|');
    
    const ctxHash = createHash('sha256').update(sortedContextualTuples).digest('hex');
    return `rebac:${req.storeId}:${req.authorizationModelId}:${req.user}:${req.relation}:${req.object}:${ctxHash}`;
  }

  public async get(key: string): Promise<boolean | null> {
    const val = await this.redis.get(key);
    return val !== null ? val === '1' : null;
  }

  public async set(key: string, allowed: boolean, ttlSeconds = 60): Promise<void> {
    await this.redis.set(key, allowed ? '1' : '0', 'EX', ttlSeconds);
  }
}

export async function revokeAccessTransactional(
  prisma: PrismaClient,
  fgaClient: OpenFgaClient,
  user: string,
  relation: string,
  object: string
): Promise<void> {
  // Invariant: Mutate through Transactional Outbox pattern to guarantee cache invalidation on commit
  await prisma.$transaction(async (tx) => {
    await tx.outboxEvent.create({
      data: {
        eventType: 'REBAC_TUPLE_DELETED',
        payload: { user, relation, object, timestamp: Date.now() },
      },
    });
    
    // OpenFGA write occurs within managed distributed outbox processor
    await fgaClient.write({
      deletes: [{ 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 Distributed ReBAC Decision Caching & Outbox Invalidation

OpenFGA Distributed ReBAC Decision Caching & Outbox Invalidation defines an industrial-grade behavioral standard for security engineering. Mandates strict deterministic keying for local OpenFGA decision caching alongside transactional outbox-driven CDC tuple invalidation. Prevents authorization bypasses and New Enemy Problem vulnerabilities caused by stale edge-evaluated Zanzibar relationship tuples. 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 TTL caching of OpenFGA checks coupled with fire-and-forget tuple 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 DriftNaive TTL caching of OpenFGA checks coupled with fire-and-forget tuple 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 include authorization_model_id, store_id, canonical user, relation, object, and hashed contextual_tuples in the local decision cache key.

Engineers MUST ALWAYS include authorization_model_id, store_id, canonical user, relation, object, and hashed contextual_tuples in the local decision cache key.

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 mutate OpenFGA tuples via direct, un-instrumented API calls without simultaneously recording a transactional outbox event in the primary operational database.

Engineers MUST NOT mutate OpenFGA tuples via direct, un-instrumented API calls without simultaneously recording a transactional outbox event in the primary operational database.

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 route all tuple lifecycle changes through durable Change Data Capture (CDC) or event brokers (e.g., Kafka) to invalidate L1 (in-process) and L2 (distributed) decision caches.

Services MUST route all tuple lifecycle changes through durable Change Data Capture (CDC) or event brokers (e.g., Kafka) to invalidate L1 (in-process) and L2 (distributed) decision caches.

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

Components NEVER assume fixed-time TTL caching is sufficient for permission revocations

Components NEVER assume fixed-time TTL caching is sufficient for permission revocations; write-time invalidation MUST propagate before state mutations commit to clients.

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

Code SHOULD enforce consistency tokens (Zookies or minimum snapshotted revision timestamps) during checks to guarantee monotonic read consistency and eliminate the New Enemy Problem.

Code SHOULD enforce consistency tokens (Zookies or minimum snapshotted revision timestamps) during checks to guarantee monotonic read consistency and eliminate 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.
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 Decision Caching & Outbox Invalidation critical for AI coding assistants?

Mandates strict deterministic keying for local OpenFGA decision caching alongside transactional outbox-driven CDC tuple invalidation. Prevents authorization bypasses and New Enemy Problem vulnerabilities caused by stale edge-evaluated Zanzibar relationship tuples. 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 TTL caching of OpenFGA checks coupled with fire-and-forget tuple 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