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

OpenFGA CDC Tuple Stream Watermark Monotonic Consistency Guardrail

Enforces strict read-your-writes monotonic consistency across distributed OpenFGA authorization checks fed by change data capture (CDC). Mandates that downstream permission evaluation gates block or supply contextual tuples until the OpenFGA consumer stream watermark catches up to the mutation's transactional log sequence number (LSN).

Prohibited Anti-Pattern: Stale Authorization Decisions Caused by Ungated Checks Against Lagging OpenFGA CDC Streams

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenFGA CDC Tuple Stream Watermark Monotonic Consistency Guardrail - Enforces strict read-your-writes monotonic consistency across distributed OpenFGA authorization checks fed by change data capture (CDC). Mandates that downstream permission evaluation gates block or supply contextual tuples until the OpenFGA consumer stream watermark catches up to the mutation's transactional log sequence number (LSN).
globs: src/auth/**/*.{ts,tsx}, src/middleware/**/*.{ts,tsx}, src/services/**/*.{ts,tsx}, src/repositories/**/*.{ts,tsx}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/openfga-cdc-watermark-consistency-invariant"
---

# OpenFGA CDC Tuple Stream Watermark Monotonic Consistency Guardrail

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Stale Authorization Decisions Caused by Ungated Checks Against Lagging OpenFGA CDC Streams

## System Constraints
You are a Principal Security Architect enforcing monotonic read-your-writes consistency across distributed authorization services. When mutations write to an authoritative database and stream to OpenFGA via CDC (Debezium/Kafka), permission checks must not evaluate against stale state. Mandate that every authorization evaluation triggered in the same causal chain either passes transactional contextual tuples or awaits the OpenFGA stream consumer watermark to match or exceed the mutation's Log Sequence Number (LSN) or transaction commit timestamp.

## Strict Guidelines
- Engineers MUST ALWAYS capture the database transaction commit watermark (e.g., PostgreSQL LSN or high-resolution commit timestamp) during resource or relationship mutations.
- Engineers MUST NOT issue bare `fgaClient.check()` calls immediately following a state mutation without verifying that the OpenFGA ingestion watermark is greater than or equal to the transaction watermark.
- Services MUST return the mutation watermark (e.g., `x-fga-watermark-lsn`) in response headers or distributed tracing context for causal propagation across client sessions.
- Code SHOULD inject ephemeral contextual tuples directly into `fgaClient.check()` as a fallback when CDC replication lag exceeds defined authorization SLA thresholds.
- Components NEVER assume OpenFGA state is synchronous with primary relational transactional commits.

## Bad vs Good Implementations
### Naive Post-Mutation Authorization Evaluation (Susceptible to Stale Read Flaws)

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Calling `fgaClient.check` right after committing a primary database change without verifying CDC replication introduces a critical race condition. High replication lag causes false permission denials or authorization bypasses.
```typescript
import { OpenFgaClient } from '@openfga/sdk';
import { db } from '../db';

export async function updateDocumentAccess(
  fgaClient: OpenFgaClient,
  documentId: string,
  userId: string,
  role: string
) {
  // 1. Mutate primary relational database (relies on CDC outbox/WAL to sync OpenFGA)
  await db.transaction(async (tx) => {
    await tx.insertInto('document_permissions').values({ documentId, userId, role }).execute();
  });

  // ANTI-PATTERN: Bare check immediately after commit.
  // If the CDC connector (e.g., Debezium) has >5ms replication lag,
  // this evaluation evaluates stale state, returning 403 Forbidden or false authorization.
  const { allowed } = await fgaClient.check({
    user: `user:${userId}`,
    relation: 'can_read',
    object: `document:${documentId}`
  });

  if (!allowed) {
    throw new Error('Access denied: permission sync failed');
  }

  return { success: true };
}
```

#### Production Standard (Correct)
> **Standard**: Captures the PostgreSQL transaction WAL LSN, waits for the CDC pipeline to process events up to that watermark, and provides contextual tuples as a deterministic fail-safe if replication lags. This guarantees monotonic read-your-writes consistency without authorization race conditions.
```typescript
import { OpenFgaClient, ClientCheckRequest } from '@openfga/sdk';
import { db } from '../db';
import { cdcWatermarkTracker } from '../auth/watermark-tracker';

interface MutationResult {
  success: boolean;
  watermarkLsn: string;
}

export async function updateDocumentAccess(
  fgaClient: OpenFgaClient,
  documentId: string,
  userId: string,
  role: string
): Promise<MutationResult> {
  // 1. Transactionally record mutation and capture write watermark (PostgreSQL LSN)
  const watermarkLsn = await db.transaction(async (tx) => {
    await tx.insertInto('document_permissions').values({ documentId, userId, role }).execute();
    const res = await tx.raw<{ pg_current_wal_lsn: string }>('SELECT pg_current_wal_lsn()::text;');
    return res.rows[0].pg_current_wal_lsn;
  });

  // 2. Monotonic guard: Ensure CDC consumer has reached or surpassed this LSN
  const isWatermarkCurrent = await cdcWatermarkTracker.waitForWatermark({
    requiredLsn: watermarkLsn,
    timeoutMs: 1500
  });

  const checkPayload: ClientCheckRequest = {
    user: `user:${userId}`,
    relation: 'can_read',
    object: `document:${documentId}`
  };

  // 3. Fallback: If CDC lags, supply contextual tuple to guarantee read-your-writes consistency
  if (!isWatermarkCurrent) {
    checkPayload.contextualTuples = [
      {
        user: `user:${userId}`,
        relation: role,
        object: `document:${documentId}`
      }
    ];
  }

  const { allowed } = await fgaClient.check(checkPayload);
  if (!allowed) {
    throw new Error('Access denied: permission failed authorization invariant');
  }

  return { success: true, watermarkLsn };
}
```

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 Tuple Stream Watermark Monotonic Consistency Guardrail

OpenFGA CDC Tuple Stream Watermark Monotonic Consistency Guardrail defines an industrial-grade behavioral standard for security engineering. Enforces strict read-your-writes monotonic consistency across distributed OpenFGA authorization checks fed by change data capture (CDC). Mandates that downstream permission evaluation gates block or supply contextual tuples until the OpenFGA consumer stream watermark catches up to the mutation's transactional log sequence number (LSN). 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: Stale Authorization Decisions Caused by Ungated Checks Against Lagging OpenFGA CDC Streams 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 DriftStale Authorization Decisions Caused by Ungated Checks Against Lagging OpenFGA CDC StreamsCritical
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 capture the database transaction commit watermark (e.g., PostgreSQL LSN or high-resolution commit timestamp) during resource or relationship mutations.

Engineers MUST ALWAYS capture the database transaction commit watermark (e.g., PostgreSQL LSN or high-resolution commit timestamp) during resource or relationship 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.
2

Engineers MUST NOT issue bare `fgaClient.check()` calls immediately following a state mutation without verifying that the OpenFGA ingestion watermark is greater than or equal to the transaction watermark.

Engineers MUST NOT issue bare `fgaClient.check()` calls immediately following a state mutation without verifying that the OpenFGA ingestion watermark is greater than or equal to the transaction watermark.

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 return the mutation watermark (e.g., `x-fga-watermark-lsn`) in response headers or distributed tracing context for causal propagation across client sessions.

Services MUST return the mutation watermark (e.g., `x-fga-watermark-lsn`) in response headers or distributed tracing context for causal propagation across client sessions.

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 inject ephemeral contextual tuples directly into `fgaClient.check()` as a fallback when CDC replication lag exceeds defined authorization SLA thresholds.

Code SHOULD inject ephemeral contextual tuples directly into `fgaClient.check()` as a fallback when CDC replication lag exceeds defined authorization SLA thresholds.

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 synchronous with primary relational transactional commits.

Components NEVER assume OpenFGA state is synchronous with primary relational transactional commits.

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 Tuple Stream Watermark Monotonic Consistency Guardrail critical for AI coding assistants?

Enforces strict read-your-writes monotonic consistency across distributed OpenFGA authorization checks fed by change data capture (CDC). Mandates that downstream permission evaluation gates block or supply contextual tuples until the OpenFGA consumer stream watermark catches up to the mutation's transactional log sequence number (LSN). 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 (Stale Authorization Decisions Caused by Ungated Checks Against Lagging OpenFGA CDC Streams) 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