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

OpenFGA ReBAC Transactional Outbox & Invalidation Barrier

Enforces dual-write prevention and cache-invalidation barriers when mutating domain entities alongside OpenFGA relationship tuples. Mandates that OpenFGA tuple updates and local read-cache evictions execute strictly via transactional outbox or Change Data Capture (CDC) pipelines to prevent stale authorization decisions and 'new enemy' security vulnerabilities.

Prohibited Anti-Pattern: Dual-Writing to Domain DB and OpenFGA API with Asynchronous Uncoordinated Cache Invalidation

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenFGA ReBAC Transactional Outbox & Invalidation Barrier - Enforces dual-write prevention and cache-invalidation barriers when mutating domain entities alongside OpenFGA relationship tuples. Mandates that OpenFGA tuple updates and local read-cache evictions execute strictly via transactional outbox or Change Data Capture (CDC) pipelines to prevent stale authorization decisions and 'new enemy' security vulnerabilities.
globs: src/modules/**/services/*.ts, src/infrastructure/authz/**/*.ts, src/infrastructure/database/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/openfga-rebac-zero-check-cache-invalidation-barrier"
---

# OpenFGA ReBAC Transactional Outbox & Invalidation Barrier

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Dual-Writing to Domain DB and OpenFGA API with Asynchronous Uncoordinated Cache Invalidation

## System Constraints
You are a Principal Security Architect enforcing Zanzibar-style authorization consistency. In applications relying on OpenFGA and local authorization decision caches (sub-millisecond zero-check barriers), domain data mutations and OpenFGA relationship tuple writes MUST NEVER be performed as non-atomic dual writes. You must reject direct, uncoordinated OpenFGA client mutations inside application request paths. Enforce transactional outbox patterns with monotonic watermarks (Zookies/consistency tokens) to guarantee that authorization caches are invalidated or updated atomically before subsequent requests can evaluate authorization checks.

## Strict Guidelines
- Engineers MUST ALWAYS write OpenFGA tuple mutations into a transactional outbox table within the exact same database transaction as the domain entity update.
- Engineers MUST NOT call `openFgaClient.write()` directly within HTTP mutation request handlers or uncommitted domain service routines.
- Services MUST publish transactional changelog events from the outbox via Change Data Capture (e.g., Debezium) or a dedicated reliable relay worker to write to OpenFGA and simultaneously issue cache invalidation barriers.
- Engineers MUST capture and propagate OpenFGA consistency tokens or sequence watermarks to local read-through caches to eliminate the 'new enemy' problem during cache evaluation.
- Authorization check layers MUST verify whether the requested entity version is newer than the cache watermark, forcing a direct OpenFGA check or cache refresh if the barrier condition is violated.

## Bad vs Good Implementations
### Dual-Write Vulnerability vs. Transactional Outbox Authorization Barrier

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Direct dual-writing to the domain database and the OpenFGA API creates split-brain state if either operation fails or the process crashes mid-flight. Furthermore, uncoordinated cache invalidation exposes a window where revoked users retain access through un-invalidated edge caches, violating Zanzibar consistency guarantees.
```typescript
import { OpenFgaClient } from '@openfga/sdk';
import { db } from '../db';
import { localAuthCache } from '../cache';

export async function revokeUserAccess(docId: string, userId: string, fga: OpenFgaClient): Promise<void> {
  // Anti-pattern: Non-atomic dual write and direct cache mutation
  await db.documentShare.delete({
    where: { documentId_userId: { documentId: docId, userId } }
  });

  // If this network call fails or server crashes, DB and OpenFGA diverge indefinitely
  await fga.write({
    deletes: [{
      user: `user:${userId}`,
      relation: 'viewer',
      object: `document:${docId}`
    }]
  });

  // Cache invalidation may race with incoming reads
  await localAuthCache.del(`auth:document:${docId}:user:${userId}`);
}
```

#### Production Standard (Correct)
> **Standard**: Both the domain share revocation and the OpenFGA relationship change are encapsulated within a single relational database transaction via the Transactional Outbox pattern. An outbox processor reliably updates OpenFGA, issues targeted invalidations to distributed/local cache barriers, and prevents authorization state divergence.
```typescript
import { db, PrismaClient } from '../db';
import { createHash } from 'crypto';

export async function revokeUserAccess(docId: string, userId: string): Promise<void> {
  // Invariant Fix: Atomically write entity deletion and OpenFGA mutation outbox entry
  await db.$transaction(async (tx: PrismaClient) => {
    await tx.documentShare.delete({
      where: { documentId_userId: { documentId: docId, userId } }
    });

    const outboxPayload = {
      deletes: [{
        user: `user:${userId}`,
        relation: 'viewer',
        object: `document:${docId}`
      }],
      barrierKey: `document:${docId}`,
      version: Date.now()
    };

    await tx.authzOutbox.create({
      data: {
        aggregateType: 'document',
        aggregateId: docId,
        eventType: 'RELATIONSHIP_REVOKED',
        payload: outboxPayload,
        status: 'PENDING'
      }
    });
  });
  // Outbox consumer guarantees at-least-once delivery to OpenFGA and evicts authorization cache barriers with monotonic sequence checks
}
```

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 ReBAC Transactional Outbox & Invalidation Barrier

OpenFGA ReBAC Transactional Outbox & Invalidation Barrier defines an industrial-grade behavioral standard for security engineering. Enforces dual-write prevention and cache-invalidation barriers when mutating domain entities alongside OpenFGA relationship tuples. Mandates that OpenFGA tuple updates and local read-cache evictions execute strictly via transactional outbox or Change Data Capture (CDC) pipelines to prevent stale authorization decisions and 'new enemy' security vulnerabilities. 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 to Domain DB and OpenFGA API with Asynchronous Uncoordinated Cache 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 DriftDual-Writing to Domain DB and OpenFGA API with Asynchronous Uncoordinated Cache 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 write OpenFGA tuple mutations into a transactional outbox table within the exact same database transaction as the domain entity update.

Engineers MUST ALWAYS write OpenFGA tuple mutations into a transactional outbox table within the exact same database transaction as the domain entity update.

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 call `openFgaClient.write()` directly within HTTP mutation request handlers or uncommitted domain service routines.

Engineers MUST NOT call `openFgaClient.write()` directly within HTTP mutation request handlers or uncommitted domain service routines.

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 publish transactional changelog events from the outbox via Change Data Capture (e.g., Debezium) or a dedicated reliable relay worker to write to OpenFGA and simultaneously issue cache invalidation barriers.

Services MUST publish transactional changelog events from the outbox via Change Data Capture (e.g., Debezium) or a dedicated reliable relay worker to write to OpenFGA and simultaneously issue cache invalidation barriers.

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 capture and propagate OpenFGA consistency tokens or sequence watermarks to local read-through caches to eliminate the 'new enemy' problem during cache evaluation.

Engineers MUST capture and propagate OpenFGA consistency tokens or sequence watermarks to local read-through caches to eliminate the 'new enemy' problem during cache evaluation.

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

Authorization check layers MUST verify whether the requested entity version is newer than the cache watermark, forcing a direct OpenFGA check or cache refresh if the barrier condition is violated.

Authorization check layers MUST verify whether the requested entity version is newer than the cache watermark, forcing a direct OpenFGA check or cache refresh if the barrier condition is violated.

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 Transactional Outbox & Invalidation Barrier critical for AI coding assistants?

Enforces dual-write prevention and cache-invalidation barriers when mutating domain entities alongside OpenFGA relationship tuples. Mandates that OpenFGA tuple updates and local read-cache evictions execute strictly via transactional outbox or Change Data Capture (CDC) pipelines to prevent stale authorization decisions and 'new enemy' security vulnerabilities. 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 to Domain DB and OpenFGA API with Asynchronous Uncoordinated Cache 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