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

OpenFGA CDC Outbox Transactional Consistency and Cache Invalidation

Enforces strict transactional consistency between primary entity mutations and external OpenFGA relationship tuples using the Transactional Outbox pattern with Change Data Capture (CDC). Prevents dual-write race conditions, authorization drift, split-brain permission states, and stale cache authorization bypass vulnerabilities.

Prohibited Anti-Pattern: Dual-Writing Inline OpenFGA Tuples within HTTP Handlers Causing Phantom Permissions and Cache Desynchronization

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenFGA CDC Outbox Transactional Consistency and Cache Invalidation - Enforces strict transactional consistency between primary entity mutations and external OpenFGA relationship tuples using the Transactional Outbox pattern with Change Data Capture (CDC). Prevents dual-write race conditions, authorization drift, split-brain permission states, and stale cache authorization bypass vulnerabilities.
globs: src/**/*.service.ts, src/**/*.repository.ts, src/**/*.consumer.ts, src/**/authz/**/*.ts, src/**/events/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/openfga-cdc-outbox-cache-invalidation-pattern"
---

# OpenFGA CDC Outbox Transactional Consistency and Cache Invalidation

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Dual-Writing Inline OpenFGA Tuples within HTTP Handlers Causing Phantom Permissions and Cache Desynchronization

## System Constraints
You are a Principal Software Architect enforcing enterprise-grade zero-trust authorization architectures using OpenFGA (Zanzibar). You must reject any direct, non-transactional writes to OpenFGA within business domain services. You mandate that all OpenFGA relationship tuple mutations and authorization cache invalidations occur via a transactional outbox table processed through Change Data Capture (CDC) with idempotent processing and monotonic ordering.

## Strict Guidelines
- Engineers MUST NEVER perform direct inline calls to `openfgaClient.write()` or `openfgaClient.writeTuples()` within primary business application services or HTTP request lifecycles.
- Engineers MUST ALWAYS persist domain mutations and authorization tuple mutation events inside the same database transaction using the Transactional Outbox pattern.
- Outbox event payloads MUST include monotonic sequence numbers or strict transaction timestamps, the full tuple key (user, relation, object), operation type ('WRITE' | 'DELETE'), and entity correlation identifiers.
- CDC consumer workers MUST execute OpenFGA tuple updates idempotently and verify monotonic ordering using conditional writes or conflict detection tokens.
- Authorization decision caches (PEP caches) MUST be invalidated atomically within the CDC event processing loop before acknowledging the outbox message.
- CDC consumers MUST route irrecoverable OpenFGA write failures to a Dead Letter Queue (DLQ) and trigger an alert rather than silently dropping tuple state mutations.
- Services MUST query OpenFGA using contextual tuples or transactional consistency tokens (such as Zookies/Zanzibar consistency tokens) when read-after-write consistency is mandatory.

## Bad vs Good Implementations
### Dual-Write Vulnerability vs. CDC Outbox Pattern with Atomic Invalidation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: If the OpenFGA network call fails after the database transaction commits, the application enters an unrecoverable split-brain authorization state. The database marks the new user as owner, but OpenFGA grants access to the previous owner. Furthermore, cache invalidation is tied to network success, leaving stale authorization tokens in memory.
```typescript
import { Injectable } from '@nestjs/common';
import { OpenFgaClient } from '@openfga/sdk';
import { EntityManager } from 'typeorm';
import { DocumentEntity } from './document.entity';

@Injectable()
export class DocumentService {
  constructor(
    private readonly entityManager: EntityManager,
    private readonly fgaClient: OpenFgaClient,
    private readonly cache: CacheManager,
  ) {}

  async transferOwnership(documentId: string, currentOwnerId: string, newOwnerId: string): Promise<void> {
    // ANTI-PATTERN: Dual-write disaster.
    // 1. Database commits successfully.
    await this.entityManager.transaction(async (tx) => {
      await tx.update(DocumentEntity, { id: documentId }, { ownerId: newOwnerId });
    });

    // 2. OpenFGA API call fails or network partitions -> Split-Brain authorization.
    // Previous owner still retains access in OpenFGA; new owner is denied.
    await this.fgaClient.write({
      deletes: [{ user: `user:${currentOwnerId}`, relation: 'owner', object: `doc:${documentId}` }],
      writes: [{ user: `user:${newOwnerId}`, relation: 'owner', object: `doc:${documentId}` }],
    });

    // 3. Cache invalidation skipped if OpenFGA call throws
    await this.cache.del(`authz:doc:${documentId}:user:${currentOwnerId}`);
  }
}
```

#### Production Standard (Correct)
> **Standard**: By persisting tuple mutations to an AuthzOutbox table within the exact same database transaction as the domain entity update, atomicity is guaranteed. The dedicated CDC worker reliably syncs changes to OpenFGA, atomically clears authorization decision caches, and uses a Dead Letter Queue (DLQ) for fault isolation.
```typescript
import { Injectable } from '@nestjs/common';
import { EntityManager } from 'typeorm';
import { DocumentEntity } from './document.entity';
import { AuthzOutboxEntity } from './authz-outbox.entity';

@Injectable()
export class DocumentService {
  constructor(private readonly entityManager: EntityManager) {}

  async transferOwnership(documentId: string, currentOwnerId: string, newOwnerId: string): Promise<void> {
    await this.entityManager.transaction(async (tx) => {
      // 1. Mutate primary domain state
      await tx.update(DocumentEntity, { id: documentId }, { ownerId: newOwnerId });

      // 2. Write authorization intent into Outbox within the SAME transaction
      const outboxTuples: Partial<AuthzOutboxEntity>[] = [
        {
          aggregateId: `doc:${documentId}`,
          operation: 'DELETE',
          user: `user:${currentOwnerId}`,
          relation: 'owner',
          object: `doc:${documentId}`,
          createdAt: new Date(),
        },
        {
          aggregateId: `doc:${documentId}`,
          operation: 'WRITE',
          user: `user:${newOwnerId}`,
          relation: 'owner',
          object: `doc:${documentId}`,
          createdAt: new Date(),
        },
      ];

      await tx.insert(AuthzOutboxEntity, outboxTuples);
    });
  }
}

// CDC / Outbox Consumer: Synchronizes OpenFGA and invalidates PEP cache
export class AuthzOutboxConsumer {
  constructor(
    private readonly fgaClient: OpenFgaClient,
    private readonly cache: CacheManager,
    private readonly dlq: DeadLetterQueueProducer,
  ) {}

  async processOutboxBatch(events: AuthzOutboxEntity[]): Promise<void> {
    for (const event of events) {
      try {
        if (event.operation === 'WRITE') {
          await this.fgaClient.write({
            writes: [{ user: event.user, relation: event.relation, object: event.object }],
          });
        } else {
          await this.fgaClient.write({
            deletes: [{ user: event.user, relation: event.relation, object: event.object }],
          });
        }

        // Atomically invalidate authorization decision caches
        await this.cache.del(`authz:${event.object}:${event.user}`);
      } catch (error) {
        await this.dlq.publish('authz-cdc-dlq', { event, error: (error as Error).message });
        throw error; // Re-throw to pause partition or trigger exponential backoff
      }
    }
  }
}
```

Recommended Agent Skills (askills.dev)

Ready-to-use executable skill functions tailored to this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: OpenFGA CDC Outbox Transactional Consistency and Cache Invalidation

OpenFGA CDC Outbox Transactional Consistency and Cache Invalidation defines an industrial-grade behavioral standard for security engineering. Enforces strict transactional consistency between primary entity mutations and external OpenFGA relationship tuples using the Transactional Outbox pattern with Change Data Capture (CDC). Prevents dual-write race conditions, authorization drift, split-brain permission states, and stale cache authorization bypass 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 Inline OpenFGA Tuples within HTTP Handlers Causing Phantom Permissions and Cache Desynchronization 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 Inline OpenFGA Tuples within HTTP Handlers Causing Phantom Permissions and Cache DesynchronizationCritical
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 inline calls to `openfgaClient.write()` or `openfgaClient.writeTuples()` within primary business application services or HTTP request lifecycles.

Engineers MUST NEVER perform direct inline calls to `openfgaClient.write()` or `openfgaClient.writeTuples()` within primary business application services or HTTP request lifecycles.

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 ALWAYS persist domain mutations and authorization tuple mutation events inside the same database transaction using the Transactional Outbox pattern.

Engineers MUST ALWAYS persist domain mutations and authorization tuple mutation events inside the same database transaction using the Transactional Outbox pattern.

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

Outbox event payloads MUST include monotonic sequence numbers or strict transaction timestamps, the full tuple key (user, relation, object), operation type ('WRITE' | 'DELETE'), and entity correlation identifiers.

Outbox event payloads MUST include monotonic sequence numbers or strict transaction timestamps, the full tuple key (user, relation, object), operation type ('WRITE' | 'DELETE'), and entity correlation identifiers.

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

CDC consumer workers MUST execute OpenFGA tuple updates idempotently and verify monotonic ordering using conditional writes or conflict detection tokens.

CDC consumer workers MUST execute OpenFGA tuple updates idempotently and verify monotonic ordering using conditional writes or conflict detection 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

Authorization decision caches (PEP caches) MUST be invalidated atomically within the CDC event processing loop before acknowledging the outbox message.

Authorization decision caches (PEP caches) MUST be invalidated atomically within the CDC event processing loop before acknowledging the outbox message.

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

CDC consumers MUST route irrecoverable OpenFGA write failures to a Dead Letter Queue (DLQ) and trigger an alert rather than silently dropping tuple state mutations.

CDC consumers MUST route irrecoverable OpenFGA write failures to a Dead Letter Queue (DLQ) and trigger an alert rather than silently dropping tuple 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.
7

Services MUST query OpenFGA using contextual tuples or transactional consistency tokens (such as Zookies/Zanzibar consistency tokens) when read-after-write consistency is mandatory.

Services MUST query OpenFGA using contextual tuples or transactional consistency tokens (such as Zookies/Zanzibar consistency tokens) when read-after-write consistency is mandatory.

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 Outbox Transactional Consistency and Cache Invalidation critical for AI coding assistants?

Enforces strict transactional consistency between primary entity mutations and external OpenFGA relationship tuples using the Transactional Outbox pattern with Change Data Capture (CDC). Prevents dual-write race conditions, authorization drift, split-brain permission states, and stale cache authorization bypass 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 Inline OpenFGA Tuples within HTTP Handlers Causing Phantom Permissions and Cache Desynchronization) 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