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

OpenFGA Outbox CDC Transactional Consistency Guardrail

Enforces atomic synchronization between primary relational data stores and OpenFGA authorization relationship tuples using the Transactional Outbox Pattern and Change Data Capture (CDC). Prohibits direct, dual-write invocations to the OpenFGA API within application business logic to prevent state drift, orphaned permissions, and security bypasses during network partitions or transaction rollbacks.

Prohibited Anti-Pattern: Dual-writing directly to OpenFGA and SQL databases within the same execution path without transactional guarantees

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenFGA Outbox CDC Transactional Consistency Guardrail - Enforces atomic synchronization between primary relational data stores and OpenFGA authorization relationship tuples using the Transactional Outbox Pattern and Change Data Capture (CDC). Prohibits direct, dual-write invocations to the OpenFGA API within application business logic to prevent state drift, orphaned permissions, and security bypasses during network partitions or transaction rollbacks.
globs: src/**/*.ts, src/**/*.tsx, src/services/**/*.ts, src/repositories/**/*.ts, src/workers/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/openfga-outbox-cdc-transactional-consistency"
---

# OpenFGA Outbox CDC Transactional Consistency Guardrail

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Dual-writing directly to OpenFGA and SQL databases within the same execution path without transactional guarantees

## System Constraints
You are a Principal Software Architect enforcing absolute consistency and zero-trust security between domain databases and OpenFGA authorization stores. You must strictly mandate that all OpenFGA tuple mutations (writes/deletes) occur via a Transactional Outbox table committed within the same database transaction as the entity state mutation. You must reject any direct synchronous calls to the OpenFGA Client write/delete APIs inside domain services or HTTP controllers.

## Strict Guidelines
- Engineers MUST ALWAYS write authorization tuple mutations directly into a relational `outbox_events` table within the same ACID database transaction that mutates the primary business entity.
- Engineers MUST NOT execute direct `fgaClient.write()` or `fgaClient.delete()` calls inside application service layers, REST controllers, or mutation handlers.
- Services MUST publish OpenFGA tuple changes asynchronously to OpenFGA using an idempotent CDC worker (e.g., Debezium, Kafka consumer, or dedicated outbox processor) with exponential backoff and dead-letter queues.
- Outbox records MUST encapsulate the deterministic tuple key structure (`user`, `relation`, `object`) along with an explicit `operation` (`WRITE` or `DELETE`), idempotency key, and monotonic transaction timestamp.
- Components NEVER assume OpenFGA state is immediately consistent; downstream read-after-write operations requiring read-your-own-writes consistency MUST either leverage OpenFGA contextual tuples or verify CDC sequence watermarks.

## Bad vs Good Implementations
### Dual-Write Direct API Call vs. Transactional Outbox Record Generation

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Direct dual-writing introduces a race condition and partial failure state. If OpenFGA experiences latency or transient failure after the SQL commit, the user is created without permissions. Conversely, if placed before the DB commit, a DB rollback leaves orphaned access rights in OpenFGA.
```typescript
import { OpenFgaClient } from '@openfga/sdk';
import { db } from '../database';
import { documents } from '../schema';

const fgaClient = new OpenFgaClient({
  apiUrl: process.env.FGA_API_URL!,
  storeId: process.env.FGA_STORE_ID!,
});

export async function createDocumentBad(userId: string, orgId: string, title: string) {
  // Anti-pattern: Dual-write vulnerability
  // If OpenFGA fails or network drops, database transaction remains committed.
  // If database fails after OpenFGA, unauthorized phantom permission persists.
  const [doc] = await db.insert(documents).values({ title, orgId }).returning();

  await fgaClient.write({
    writes: [
      { user: `user:${userId}`, relation: 'owner', object: `document:${doc.id}` },
      { user: `organization:${orgId}`, relation: 'parent', object: `document:${doc.id}` }
    ]
  });

  return doc;
}
```

#### Production Standard (Correct)
> **Standard**: Atomically writes entity state and authorization outbox records within a single database transaction. An external CDC processor guarantees at-least-once, ordered delivery to OpenFGA without dual-write inconsistency.
```typescript
import { db } from '../database';
import { documents, outboxEvents } from '../schema';

export interface OpenFgaOutboxPayload {
  operation: 'WRITE' | 'DELETE';
  tuple: {
    user: string;
    relation: string;
    object: string;
  };
}

export async function createDocumentGood(userId: string, orgId: string, title: string) {
  // Invariant: Atomically commit business mutation and FGA tuple events
  return await db.transaction(async (tx) => {
    const [doc] = await tx.insert(documents).values({ title, orgId }).returning();

    const outboxWrites: OpenFgaOutboxPayload[] = [
      {
        operation: 'WRITE',
        tuple: { user: `user:${userId}`, relation: 'owner', object: `document:${doc.id}` }
      },
      {
        operation: 'WRITE',
        tuple: { user: `organization:${orgId}`, relation: 'parent', object: `document:${doc.id}` }
      }
    ];

    await tx.insert(outboxEvents).values(
      outboxWrites.map((payload) => ({
        aggregateType: 'OpenFgaTuple',
        aggregateId: `document:${doc.id}`,
        payload: JSON.stringify(payload),
        createdAt: new Date()
      }))
    );

    return doc;
  });
}
```

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 Outbox CDC Transactional Consistency Guardrail

OpenFGA Outbox CDC Transactional Consistency Guardrail defines an industrial-grade behavioral standard for security engineering. Enforces atomic synchronization between primary relational data stores and OpenFGA authorization relationship tuples using the Transactional Outbox Pattern and Change Data Capture (CDC). Prohibits direct, dual-write invocations to the OpenFGA API within application business logic to prevent state drift, orphaned permissions, and security bypasses during network partitions or transaction rollbacks. 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 directly to OpenFGA and SQL databases within the same execution path without transactional guarantees 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 directly to OpenFGA and SQL databases within the same execution path without transactional guaranteesCritical
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 authorization tuple mutations directly into a relational `outbox_events` table within the same ACID database transaction that mutates the primary business entity.

Engineers MUST ALWAYS write authorization tuple mutations directly into a relational `outbox_events` table within the same ACID database transaction that mutates the primary business entity.

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 `fgaClient.write()` or `fgaClient.delete()` calls inside application service layers, REST controllers, or mutation handlers.

Engineers MUST NOT execute direct `fgaClient.write()` or `fgaClient.delete()` calls inside application service layers, REST controllers, or 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 publish OpenFGA tuple changes asynchronously to OpenFGA using an idempotent CDC worker (e.g., Debezium, Kafka consumer, or dedicated outbox processor) with exponential backoff and dead-letter queues.

Services MUST publish OpenFGA tuple changes asynchronously to OpenFGA using an idempotent CDC worker (e.g., Debezium, Kafka consumer, or dedicated outbox processor) with exponential backoff and dead-letter queues.

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

Outbox records MUST encapsulate the deterministic tuple key structure (`user`, `relation`, `object`) along with an explicit `operation` (`WRITE` or `DELETE`), idempotency key, and monotonic transaction timestamp.

Outbox records MUST encapsulate the deterministic tuple key structure (`user`, `relation`, `object`) along with an explicit `operation` (`WRITE` or `DELETE`), idempotency key, and monotonic transaction timestamp.

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 assume OpenFGA state is immediately consistent

Components NEVER assume OpenFGA state is immediately consistent; downstream read-after-write operations requiring read-your-own-writes consistency MUST either leverage OpenFGA contextual tuples or verify CDC sequence watermarks.

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 Outbox CDC Transactional Consistency Guardrail critical for AI coding assistants?

Enforces atomic synchronization between primary relational data stores and OpenFGA authorization relationship tuples using the Transactional Outbox Pattern and Change Data Capture (CDC). Prohibits direct, dual-write invocations to the OpenFGA API within application business logic to prevent state drift, orphaned permissions, and security bypasses during network partitions or transaction rollbacks. 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 directly to OpenFGA and SQL databases within the same execution path without transactional guarantees) 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