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

OpenFGA CDC-Driven Eventual ReBAC Cache Invalidation Standard

Eliminates authorization drift and stale permission evaluations by strictly forbidding direct dual-writes to OpenFGA and authorization caches during application requests. Enforces an atomic transactional outbox pattern paired with Change Data Capture (CDC) streaming to synchronize relational tuple mutations, OpenFGA writes, and distributed ReBAC cache evictions deterministically.

Prohibited Anti-Pattern: Dual-Writing Authorization Tuples and In-Memory/Redis Caches Directly from Application Request Handlers

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenFGA CDC-Driven Eventual ReBAC Cache Invalidation Standard - Eliminates authorization drift and stale permission evaluations by strictly forbidding direct dual-writes to OpenFGA and authorization caches during application requests. Enforces an atomic transactional outbox pattern paired with Change Data Capture (CDC) streaming to synchronize relational tuple mutations, OpenFGA writes, and distributed ReBAC cache evictions deterministically.
globs: src/**/*.ts, src/**/*.tsx, src/services/auth*/**/*.ts, src/repositories/**/*.ts, src/workers/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/openfga-cdc-outbox-rebac-cache-invalidation-standard"
---

# OpenFGA CDC-Driven Eventual ReBAC Cache Invalidation Standard

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Dual-Writing Authorization Tuples and In-Memory/Redis Caches Directly from Application Request Handlers

## System Constraints
You are a Principal Security Architect enforcing the OpenFGA CDC-Driven Eventual ReBAC Cache Invalidation Standard. You must strictly mandate transactional outbox storage for relational authorization mutations and block any direct writes to OpenFGA or ReBAC authorization caches within user-facing API request paths.

## Strict Guidelines
- Engineers MUST ALWAYS persist authorization tuple modifications (e.g., grants, revokes, role assignments) in the same database transaction as the business entity via a dedicated outbox table (e.g., `fga_outbox_events`).
- Engineers MUST NOT execute direct write/delete calls against OpenFGA APIs (`client.write`) or distributed ReBAC caches (e.g., Redis `del`/`unlink`) inside synchronous HTTP/RPC mutation handlers.
- Services MUST process authorization outbox events asynchronously via an idempotent CDC consumer (e.g., Debezium, Kafka Connect, or dedicated logical replication stream) before propagating to OpenFGA.
- Code SHOULD include the database Log Sequence Number (LSN) or a monotonically increasing transaction timestamp in outbox events to prevent out-of-order cache invalidation races.
- Components NEVER treat cached ReBAC checks as authoritative without validating cache lease TTLs or invalidation version vectors when high-integrity operations (e.g., privilege escalation, payments) are executed.

## Bad vs Good Implementations
### Dual-Write Authorization Mutation vs. Transactional Outbox Pattern

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Direct dual-writing to OpenFGA and Redis within an HTTP handler causes silent authorization divergence when network failures, timeouts, or process terminations occur between the relational write and downstream calls.
```typescript
import { OpenFgaClient } from '@openfga/sdk';
import { redis } from '../infrastructure/redis';
import { db } from '../infrastructure/db';

export async function revokeDocumentAccess(userId: string, documentId: string) {
  // Anti-Pattern: Non-atomic dual-write prone to authorization drift
  await db.documentPermission.deleteMany({
    where: { userId, documentId },
  });

  const fgaClient = new OpenFgaClient({ /* config */ });
  
  // If this network call fails or worker crashes here, DB and OpenFGA diverge permanently
  await fgaClient.write({
    deletes: [{
      user: `user:${userId}`,
      relation: 'viewer',
      object: `document:${documentId}`,
    }],
  });

  // Cache invalidation failure leaves stale authorization grant in memory
  await redis.del(`auth:document:${documentId}:user:${userId}`);
}
```

#### Production Standard (Correct)
> **Standard**: Guarantees atomicity by persisting the OpenFGA intent within the primary database transaction. The CDC pipeline guarantees delivery to OpenFGA and invalidates the ReBAC cache deterministically.
```typescript
import { PrismaClient } from '@prisma/client';

export async function revokeDocumentAccess(
  prisma: PrismaClient,
  userId: string,
  documentId: string,
  correlationId: string
): Promise<void> {
  // Pattern: Atomic transactional outbox guarantees exactly-once CDC emission
  await prisma.$transaction(async (tx) => {
    await tx.documentPermission.deleteMany({
      where: { userId, documentId },
    });

    await tx.fgaOutboxEvent.create({
      data: {
        correlationId,
        operation: 'DELETE',
        user: `user:${userId}`,
        relation: 'viewer',
        object: `document:${documentId}`,
        createdAt: new Date(),
        status: 'PENDING',
      },
    });
  });
  // A CDC worker (e.g., Debezium/Kafka worker) reads fga_outbox_events, calls OpenFGA, and broadcasts cache invalidation
}
```

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 CDC-Driven Eventual ReBAC Cache Invalidation Standard

OpenFGA CDC-Driven Eventual ReBAC Cache Invalidation Standard defines an industrial-grade behavioral standard for security engineering. Eliminates authorization drift and stale permission evaluations by strictly forbidding direct dual-writes to OpenFGA and authorization caches during application requests. Enforces an atomic transactional outbox pattern paired with Change Data Capture (CDC) streaming to synchronize relational tuple mutations, OpenFGA writes, and distributed ReBAC cache evictions deterministically. 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: Dual-Writing Authorization Tuples and In-Memory/Redis Caches Directly from Application Request Handlers 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 DriftDual-Writing Authorization Tuples and In-Memory/Redis Caches Directly from Application Request HandlersCritical
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 persist authorization tuple modifications (e.g., grants, revokes, role assignments) in the same database transaction as the business entity via a dedicated outbox table (e.g., `fga_outbox_events`).

Engineers MUST ALWAYS persist authorization tuple modifications (e.g., grants, revokes, role assignments) in the same database transaction as the business entity via a dedicated outbox table (e.g., `fga_outbox_events`).

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 execute direct write/delete calls against OpenFGA APIs (`client.write`) or distributed ReBAC caches (e.g., Redis `del`/`unlink`) inside synchronous HTTP/RPC mutation handlers.

Engineers MUST NOT execute direct write/delete calls against OpenFGA APIs (`client.write`) or distributed ReBAC caches (e.g., Redis `del`/`unlink`) inside synchronous HTTP/RPC mutation handlers.

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 process authorization outbox events asynchronously via an idempotent CDC consumer (e.g., Debezium, Kafka Connect, or dedicated logical replication stream) before propagating to OpenFGA.

Services MUST process authorization outbox events asynchronously via an idempotent CDC consumer (e.g., Debezium, Kafka Connect, or dedicated logical replication stream) before propagating to OpenFGA.

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 include the database Log Sequence Number (LSN) or a monotonically increasing transaction timestamp in outbox events to prevent out-of-order cache invalidation races.

Code SHOULD include the database Log Sequence Number (LSN) or a monotonically increasing transaction timestamp in outbox events to prevent out-of-order cache invalidation races.

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 treat cached ReBAC checks as authoritative without validating cache lease TTLs or invalidation version vectors when high-integrity operations (e.g., privilege escalation, payments) are executed.

Components NEVER treat cached ReBAC checks as authoritative without validating cache lease TTLs or invalidation version vectors when high-integrity operations (e.g., privilege escalation, payments) are executed.

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 CDC-Driven Eventual ReBAC Cache Invalidation Standard critical for AI coding assistants?

Eliminates authorization drift and stale permission evaluations by strictly forbidding direct dual-writes to OpenFGA and authorization caches during application requests. Enforces an atomic transactional outbox pattern paired with Change Data Capture (CDC) streaming to synchronize relational tuple mutations, OpenFGA writes, and distributed ReBAC cache evictions deterministically. 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 (Dual-Writing Authorization Tuples and In-Memory/Redis Caches Directly from Application Request Handlers) 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