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

OpenFGA CDC-Driven WAL Relation Invalidation and Cache Coherency Guardrail

Mandates that authorization decision caches and OpenFGA tuple projections derive invalidation events deterministically from PostgreSQL Write-Ahead Log (WAL) change data capture (CDC) streams. Prohibits synchronous application-tier dual-writes and unversioned TTL-only authorization caching that risk stale permit decisions after privilege revocation. Enforces transactional Log Sequence Number (LSN) watermarking to maintain strict monotonic read consistency across distributed authorization checks.

Prohibited Anti-Pattern: Dual-Write Application-Level Eviction and TTL Authorization Caching Allowing Revocation Bypass

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenFGA CDC-Driven WAL Relation Invalidation and Cache Coherency Guardrail - Mandates that authorization decision caches and OpenFGA tuple projections derive invalidation events deterministically from PostgreSQL Write-Ahead Log (WAL) change data capture (CDC) streams. Prohibits synchronous application-tier dual-writes and unversioned TTL-only authorization caching that risk stale permit decisions after privilege revocation. Enforces transactional Log Sequence Number (LSN) watermarking to maintain strict monotonic read consistency across distributed authorization checks.
globs: src/auth/**/*.{ts,tsx,go}, src/cdc/**/*.{ts,tsx,go}, src/services/authz/**/*.{ts,tsx,go}, src/infra/cache/**/*.{ts,tsx,go}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/openfga-cdc-wal-cache-invalidation-standard"
---

# OpenFGA CDC-Driven WAL Relation Invalidation and Cache Coherency Guardrail

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Dual-Write Application-Level Eviction and TTL Authorization Caching Allowing Revocation Bypass

## System Constraints
You are a Principal Software Architect enforcing the OpenFGA CDC-Driven Relation Invalidation Cache Coherency Standard. Mandate that application layers never perform dual-write cache busts on relational authorization mutations; authorization cache invalidation MUST be anchored to PostgreSQL WAL logical decoding streams using transactional LSN ordering. Any authorization check with cached grants must verify consistency against replication stream watermarks to prevent stale permits upon relation revocation.

## Strict Guidelines
- Engineers MUST NOT implement dual-write cache evictions inside application mutation handlers (e.g., executing DB UPDATE followed by redis.del()), as network partitions and transaction rollbacks produce stale cached permits.
- Services MUST ingest PostgreSQL logical decoding events (pgoutput/test_decoding or Debezium) to drive downstream OpenFGA relation tuple writes and Redis authorization cache invalidations.
- Engineers MUST incorporate the PostgreSQL Log Sequence Number (LSN) or commit timestamp into cached authorization keys or metadata to enforce monotonic ordering and reject out-of-order CDC delivery.
- Cached authorization checks MUST evaluate monotonic consistency tokens (e.g., minimum committed LSN) to prevent read-your-own-writes lag when evaluating newly updated relations.
- Components NEVER treat TTL expiry as the primary revocation mechanism for authorization decisions; authorization cache TTLs serve solely as a catastrophic fallback bound, while WAL-driven CDC provides the primary deterministic invalidation.

## Bad vs Good Implementations
### Dual-Write Application Invalidation vs. CDC WAL-Streamed Cache Coherency

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Direct dual-writing across DB, OpenFGA, and Redis breaks transactional integrity. If the Redis call fails, network stalls, or concurrent readers re-cache an in-flight read, a revoked user retains access indefinitely or until an uncoordinated TTL expires, leading to a critical authorization bypass vulnerability.
```typescript
import { Request, Response } from 'express';
import { db } from '../infra/db';
import { redis } from '../infra/redis';
import { fgaClient } from '../infra/openfga';

// ANTI-PATTERN: Application-level dual-write. If DB transaction succeeds but
// OpenFGA write or Redis invalidation fails, or if a race occurs between concurrent
// requests, the cache retains a stale 'ALLOWED' decision despite privilege revocation.
export async function revokeAccessHandler(req: Request, res: Response) {
  const { userId, documentId } = req.body;

  await db.transaction(async (trx) => {
    await trx('document_permissions')
      .where({ user_id: userId, document_id: documentId })
      .delete();
  });

  // Flawed: Network failure here leaves OpenFGA and cache stale
  await fgaClient.write({
    deletes: [{ user: `user:${userId}`, relation: 'viewer', object: `document:${documentId}` }]
  });

  // Flawed: Racing readers can re-populate Redis with stale data immediately before delete runs
  const cacheKey = `authz:check:user:${userId}:viewer:document:${documentId}`;
  await redis.del(cacheKey);

  return res.status(204).send();
}
```

#### Production Standard (Correct)
> **Standard**: Decoupling mutations from invalidations via PostgreSQL WAL CDC guarantees that OpenFGA and cache invalidations only occur for committed transactions. The LSN fence ensures strictly monotonic updates, eliminating race conditions, partial failures, and split-brain authorization states.
```typescript
import { ConsumerGroup, KafkaMessage } from 'kafkajs';
import { redis } from '../infra/redis';
import { fgaClient } from '../infra/openfga';

interface WalChangeEvent {
  lsn: string;
  table: string;
  op: 'INSERT' | 'UPDATE' | 'DELETE';
  before?: { user_id: string; document_id: string; role: string };
  after?: { user_id: string; document_id: string; role: string };
}

// PRODUCTION INVARIANT: Invalidation and OpenFGA synchronization are driven
// strictly by the PostgreSQL WAL stream. LSN fencing prevents out-of-order updates.
export async function processWalAuthorizationEvent(message: KafkaMessage): Promise<void> {
  if (!message.value) return;
  const event: WalChangeEvent = JSON.parse(message.value.toString());
  if (event.table !== 'document_permissions') return;

  const target = event.op === 'DELETE' ? event.before! : event.after!;
  const user = `user:${target.user_id}`;
  const relation = target.role;
  const object = `document:${target.document_id}`;
  const cacheKey = `authz:check:${user}:${relation}:${object}`;
  const eventLsn = BigInt(event.lsn);

  // Monotonic LSN fencing: avoid overwriting if a newer WAL event was already applied
  const lastSeenLsnStr = await redis.get(`authz:lsn:${object}`);
  if (lastSeenLsnStr && BigInt(lastSeenLsnStr) >= eventLsn) {
    return;
  }

  if (event.op === 'DELETE') {
    await fgaClient.write({
      deletes: [{ user, relation, object }]
    });
  } else if (event.op === 'INSERT') {
    await fgaClient.write({
      writes: [{ user, relation, object }]
    });
  }

  // Atomic pipeline: Evict cache and update the high-watermark LSN for this entity
  await redis.pipeline()
    .del(cacheKey)
    .set(`authz:lsn:${object}`, eventLsn.toString())
    .exec();
}
```

Recommended Agent Skills (askills.dev)

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

Architectural Specification & Invariant Rationale

Architectural Invariant Design: OpenFGA CDC-Driven WAL Relation Invalidation and Cache Coherency Guardrail

OpenFGA CDC-Driven WAL Relation Invalidation and Cache Coherency Guardrail defines an industrial-grade behavioral standard for security engineering. Mandates that authorization decision caches and OpenFGA tuple projections derive invalidation events deterministically from PostgreSQL Write-Ahead Log (WAL) change data capture (CDC) streams. Prohibits synchronous application-tier dual-writes and unversioned TTL-only authorization caching that risk stale permit decisions after privilege revocation. Enforces transactional Log Sequence Number (LSN) watermarking to maintain strict monotonic read consistency across distributed authorization checks. 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 Application-Level Eviction and TTL Authorization Caching Allowing Revocation Bypass 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 Application-Level Eviction and TTL Authorization Caching Allowing Revocation BypassCritical
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 NOT implement dual-write cache evictions inside application mutation handlers (e.g., executing DB UPDATE followed by redis.del()), as network partitions and transaction rollbacks produce stale cached permits.

Engineers MUST NOT implement dual-write cache evictions inside application mutation handlers (e.g., executing DB UPDATE followed by redis.del()), as network partitions and transaction rollbacks produce stale cached permits.

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

Services MUST ingest PostgreSQL logical decoding events (pgoutput/test_decoding or Debezium) to drive downstream OpenFGA relation tuple writes and Redis authorization cache invalidations.

Services MUST ingest PostgreSQL logical decoding events (pgoutput/test_decoding or Debezium) to drive downstream OpenFGA relation tuple writes and Redis authorization cache invalidations.

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

Engineers MUST incorporate the PostgreSQL Log Sequence Number (LSN) or commit timestamp into cached authorization keys or metadata to enforce monotonic ordering and reject out-of-order CDC delivery.

Engineers MUST incorporate the PostgreSQL Log Sequence Number (LSN) or commit timestamp into cached authorization keys or metadata to enforce monotonic ordering and reject out-of-order CDC 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.
4

Cached authorization checks MUST evaluate monotonic consistency tokens (e.g., minimum committed LSN) to prevent read-your-own-writes lag when evaluating newly updated relations.

Cached authorization checks MUST evaluate monotonic consistency tokens (e.g., minimum committed LSN) to prevent read-your-own-writes lag when evaluating newly updated relations.

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 treat TTL expiry as the primary revocation mechanism for authorization decisions

Components NEVER treat TTL expiry as the primary revocation mechanism for authorization decisions; authorization cache TTLs serve solely as a catastrophic fallback bound, while WAL-driven CDC provides the primary deterministic invalidation.

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 WAL Relation Invalidation and Cache Coherency Guardrail critical for AI coding assistants?

Mandates that authorization decision caches and OpenFGA tuple projections derive invalidation events deterministically from PostgreSQL Write-Ahead Log (WAL) change data capture (CDC) streams. Prohibits synchronous application-tier dual-writes and unversioned TTL-only authorization caching that risk stale permit decisions after privilege revocation. Enforces transactional Log Sequence Number (LSN) watermarking to maintain strict monotonic read consistency across distributed authorization checks. 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 Application-Level Eviction and TTL Authorization Caching Allowing Revocation Bypass) 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