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

OpenFGA CDC-Driven Cache Invalidation Gatekeeper Standard

Enforces sub-millisecond zero-trust authorization check latency while eliminating authorization divergence between application data stores and distributed relationship graphs. Mandates transactional outbox capture for OpenFGA relationship tuples, causal consistency tokens for check queries, and monotonic CDC-driven cache evictions to prevent Time-of-Check to Time-of-Use (TOCTOU) authorization bypasses.

Prohibited Anti-Pattern: Dual-Write Desynchronization and Unbounded Cache Window Authorization Divergence

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenFGA CDC-Driven Cache Invalidation Gatekeeper Standard - Enforces sub-millisecond zero-trust authorization check latency while eliminating authorization divergence between application data stores and distributed relationship graphs. Mandates transactional outbox capture for OpenFGA relationship tuples, causal consistency tokens for check queries, and monotonic CDC-driven cache evictions to prevent Time-of-Check to Time-of-Use (TOCTOU) authorization bypasses.
globs: src/auth/**/*.{ts,tsx}, src/gateways/**/*.{ts,tsx}, src/services/**/*.{ts,tsx}, src/infrastructure/cdc/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/openfga-cdc-cache-invalidation-gatekeeper"
---

# OpenFGA CDC-Driven Cache Invalidation Gatekeeper Standard

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Dual-Write Desynchronization and Unbounded Cache Window Authorization Divergence

## System Constraints
You are a Principal Security Architect enforcing zero-trust authorization standards. You must strictly enforce the OpenFGA CDC-Driven Cache Invalidation Gatekeeper pattern. Mandate that all relationship mutations use transactional outbox patterns instead of application-level dual-writes. Prohibit raw TTL-only caching of authorization decisions. Require causal consistency tokens (LSN/monotonic version checkpoints) to prevent TOCTOU privilege leakage.

## Strict Guidelines
- Engineers MUST NEVER perform direct dual-writes to the primary application database and OpenFGA API within application business handlers.
- Engineers MUST persist OpenFGA tuple mutations within the same ACID transaction as the domain entity mutation using a transactional outbox table.
- Services MUST route relationship tuple writes exclusively through an ordered Transactional Change Data Capture (CDC) stream (e.g., Debezium/Kafka) before propagating updates to OpenFGA.
- Services MUST invalidate local L1 memory caches and distributed L2 Redis caches via monotonic CDC event sequence tokens to prevent stale authorization bypasses caused by out-of-order delivery.
- Engineers MUST pass causal consistency tokens (`consistency: ConsistencyPreference.HigherConsistency` or specific transaction snapshot tokens) when performing authorization checks following state mutations.
- Components NEVER evaluate cached authorization decisions if the caller requests causal consistency higher than the cached decision's committed checkpoint version.

## Bad vs Good Implementations
### Dual-Write & Blind Cache Invalidation vs. CDC Outbox with Causal Consistency Gatekeeper

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Direct dual-writes guarantee state divergence if the OpenFGA call fails after the DB commit. Blind cache key deletion is vulnerable to race conditions where a concurrent read repopulates the cache with stale authorization rights before OpenFGA acknowledges the write, creating an unauthorized access window.
```typescript
import { OpenFgaClient } from '@openfga/sdk';
import { Redis } from 'ioredis';
import { db } from './db';

const fga = new OpenFgaClient({ apiUrl: process.env.FGA_API_URL! });
const redis = new Redis();

export async function transferDocumentOwnership(docId: string, newOwnerId: string, oldOwnerId: string) {
  // ANTI-PATTERN: Dual-write to DB and OpenFGA without transactional atomicity
  await db.document.update({ where: { id: docId }, data: { ownerId: newOwnerId } });

  // Network failure here leaves DB and OpenFGA out-of-sync
  await fga.write({
    writes: [{ user: `user:${newOwnerId}`, relation: 'owner', object: `doc:${docId}` }],
    deletes: [{ user: `user:${oldOwnerId}`, relation: 'owner', object: `doc:${docId}` }],
  });

  // ANTI-PATTERN: Blind cache deletion race condition; concurrent reads can repopulate stale state
  await redis.del(`auth:doc:${docId}:user:${oldOwnerId}`);
  await redis.del(`auth:doc:${docId}:user:${newOwnerId}`);
}
```

#### Production Standard (Correct)
> **Standard**: Persists relationship mutations in the same ACID transaction via an outbox record, decoupling write execution through a reliable CDC worker. Authorization check queries evaluate causal consistency tokens, strictly falling back to high-consistency OpenFGA queries if cached data lags behind the required checkpoint.
```typescript
import { OpenFgaClient, ConsistencyPreference } from '@openfga/sdk';
import { Redis } from 'ioredis';
import { db } from './db';

const fga = new OpenFgaClient({ apiUrl: process.env.FGA_API_URL! });
const redis = new Redis();

export async function transferDocumentOwnership(docId: string, newOwnerId: string, oldOwnerId: string) {
  // Invariant 1: Atomic Transactional Outbox for entity and relationship graph changes
  const result = await db.$transaction(async (tx) => {
    const updatedDoc = await tx.document.update({
      where: { id: docId },
      data: { ownerId: newOwnerId },
      select: { id: true, version: true },
    });

    // OpenFGA tuple changes are written as transactional outbox events
    const outboxRecord = await tx.authorizationOutbox.create({
      data: {
        entityType: 'document',
        entityId: docId,
        targetVersion: updatedDoc.version,
        writes: JSON.stringify([{ user: `user:${newOwnerId}`, relation: 'owner', object: `doc:${docId}` }]),
        deletes: JSON.stringify([{ user: `user:${oldOwnerId}`, relation: 'owner', object: `doc:${docId}` }]),
      },
      select: { id: true, sequenceNum: true },
    });

    return { docVersion: updatedDoc.version, checkpointToken: outboxRecord.sequenceNum.toString() };
  });

  // Return causal consistency token to caller for immediate read-after-write checks
  return result;
}

// Invariant 2: Gatekeeper check with causal token check against cached state
export async function checkAccessGatekeeper(
  userId: string,
  docId: string,
  relation: string,
  minTokenRequired?: string
): Promise<boolean> {
  const cacheKey = `authz:v1:doc:${docId}:user:${userId}:${relation}`;
  const cached = await redis.hgetall(cacheKey);

  if (cached?.allowed !== undefined && cached?.token) {
    // Ensure cached decision meets or exceeds the required causal checkpoint
    if (!minTokenRequired || BigInt(cached.token) >= BigInt(minTokenRequired)) {
      return cached.allowed === 'true';
    }
  }

  // Cache miss or stale causal token: Query OpenFGA with explicit freshness guarantees
  const response = await fga.check({
    user: `user:${userId}`,
    relation,
    object: `doc:${docId}`,
    consistency: minTokenRequired
      ? ConsistencyPreference.HigherConsistency
      : ConsistencyPreference.MinimizeLatency,
  });

  const isAllowed = Boolean(response.allowed);
  // Populate cache with monotonic version tag
  if (minTokenRequired) {
    await redis.hmset(cacheKey, {
      allowed: String(isAllowed),
      token: minTokenRequired,
    });
    await redis.expire(cacheKey, 60);
  }

  return isAllowed;
}
```

Architectural Specification & Invariant Rationale

Architectural Invariant Design: OpenFGA CDC-Driven Cache Invalidation Gatekeeper Standard

OpenFGA CDC-Driven Cache Invalidation Gatekeeper Standard defines an industrial-grade behavioral standard for security engineering. Enforces sub-millisecond zero-trust authorization check latency while eliminating authorization divergence between application data stores and distributed relationship graphs. Mandates transactional outbox capture for OpenFGA relationship tuples, causal consistency tokens for check queries, and monotonic CDC-driven cache evictions to prevent Time-of-Check to Time-of-Use (TOCTOU) authorization bypasses. 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-Write Desynchronization and Unbounded Cache Window Authorization Divergence 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-Write Desynchronization and Unbounded Cache Window Authorization DivergenceCritical
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 NEVER perform direct dual-writes to the primary application database and OpenFGA API within application business handlers.

Engineers MUST NEVER perform direct dual-writes to the primary application database and OpenFGA API within application business 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.
2

Engineers MUST persist OpenFGA tuple mutations within the same ACID transaction as the domain entity mutation using a transactional outbox table.

Engineers MUST persist OpenFGA tuple mutations within the same ACID transaction as the domain entity mutation using a transactional outbox table.

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 relationship tuple writes exclusively through an ordered Transactional Change Data Capture (CDC) stream (e.g., Debezium/Kafka) before propagating updates to OpenFGA.

Services MUST route relationship tuple writes exclusively through an ordered Transactional Change Data Capture (CDC) stream (e.g., Debezium/Kafka) before propagating updates 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

Services MUST invalidate local L1 memory caches and distributed L2 Redis caches via monotonic CDC event sequence tokens to prevent stale authorization bypasses caused by out-of-order delivery.

Services MUST invalidate local L1 memory caches and distributed L2 Redis caches via monotonic CDC event sequence tokens to prevent stale authorization bypasses caused by out-of-order delivery.

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

Engineers MUST pass causal consistency tokens (`consistency

Engineers MUST pass causal consistency tokens (`consistency: ConsistencyPreference.HigherConsistency` or specific transaction snapshot tokens) when performing authorization checks following state mutations.

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 evaluate cached authorization decisions if the caller requests causal consistency higher than the cached decision's committed checkpoint version.

Components NEVER evaluate cached authorization decisions if the caller requests causal consistency higher than the cached decision's committed checkpoint version.

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 Cache Invalidation Gatekeeper Standard critical for AI coding assistants?

Enforces sub-millisecond zero-trust authorization check latency while eliminating authorization divergence between application data stores and distributed relationship graphs. Mandates transactional outbox capture for OpenFGA relationship tuples, causal consistency tokens for check queries, and monotonic CDC-driven cache evictions to prevent Time-of-Check to Time-of-Use (TOCTOU) authorization bypasses. 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-Write Desynchronization and Unbounded Cache Window Authorization Divergence) 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