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

OpenFGA Real-Time CDC Authorization Cache Coherence Standard

Enforces sub-millisecond distributed cache invalidation for OpenFGA check evaluations via PostgreSQL Logical Decoding (CDC) or Debezium outbox streams. Guarantees that transactional relation-tuple mutations publish strongly-ordered invalidation events, preventing authorization read-after-write privilege desynchronization vulnerabilities.

Prohibited Anti-Pattern: Dual-Writing Cache Invalidations Directly in Application Handlers Without Transactional CDC

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenFGA Real-Time CDC Authorization Cache Coherence Standard - Enforces sub-millisecond distributed cache invalidation for OpenFGA check evaluations via PostgreSQL Logical Decoding (CDC) or Debezium outbox streams. Guarantees that transactional relation-tuple mutations publish strongly-ordered invalidation events, preventing authorization read-after-write privilege desynchronization vulnerabilities.
globs: src/auth/**/*.{ts,js}, src/fga/**/*.{ts,js}, src/cdc/**/*.{ts,js}, src/services/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/openfga-cdc-cache-coherence-standard"
---

# OpenFGA Real-Time CDC Authorization Cache Coherence Standard

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Dual-Writing Cache Invalidations Directly in Application Handlers Without Transactional CDC

## System Constraints
You are a Principal Security Architect enforcing the OpenFGA Real-Time CDC Authorization Cache Coherence Standard. Mandate that application tiers NEVER write directly to OpenFGA check caches without CDC synchronization, NEVER perform best-effort Redis invalidations inside HTTP handlers, and MUST leverage transactional outbox or PostgreSQL logical replication streams to publish deterministic eviction keys matching canonical OpenFGA tuple patterns.

## Strict Guidelines
- Engineers MUST ALWAYS invalidate distributed authorization caches via Change Data Capture (CDC) streams tied to the relation tuple transaction commit log (WAL) rather than inline best-effort HTTP handler calls.
- Engineers MUST NOT cache OpenFGA Check API responses using un-versioned or generic entity keys that do not account for transitive graph relations and context.
- Services MUST publish transactional outbox events or consume PostgreSQL pgoutput CDC events synchronously with relation tuple writes to eliminate read-after-write privilege drift windows.
- Cache eviction consumers MUST implement idempotent Lua scripts or pipeline bulk evictions in Redis using exact canonical tuple matchers (`fga:check:{user}:{relation}:{object}`).
- Services MUST enforce bounded TTLs (max 15-30 seconds) on OpenFGA Check evaluation caches as a secondary failsafe against dropped CDC stream partitions.

## Bad vs Good Implementations
### Dual-Write Best-Effort Invalidation vs CDC Logical Replication Stream Consumer

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Directly deleting cache entries inside the mutation handler is a dual-write anti-pattern. If the cache eviction fails, times out, or the worker dies between writes, the cache remains stale with elevated privileges. Furthermore, concurrent check evaluations can race and re-populate the cache with stale authorization reads.
```typescript
import { OpenFgaClient } from '@openfga/sdk';
import { Redis } from 'ioredis';

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

export async function revokeAccess(user: string, relation: string, document: string) {
  // Anti-Pattern: Inline write followed by non-transactional cache deletion
  // Fails if network blips or app crashes before redis.del, causing persistent privilege escalation
  await fga.write({
    deletes: [{ user, relation, object: document }]
  });

  // Application-level dual write is vulnerable to race conditions & partial failures
  const cacheKey = `fga:check:${user}:${relation}:${document}`;
  await redis.del(cacheKey);
}
```

#### Production Standard (Correct)
> **Standard**: Decouples cache invalidation from write requests by tailing the PostgreSQL WAL / OpenFGA storage engine CDC stream. Invalidation events are strictly ordered by LSN (Log Sequence Number), ensuring deterministic sub-millisecond cache eviction even across system failures or concurrent mutations.
```typescript
import { Redis } from 'ioredis';
import { z } from 'zod';

const cdcTuplePayloadSchema = z.object({
  op: z.enum(['c', 'u', 'd']),
  before: z.object({ user: z.string(), relation: z.string(), object: z.string() }).nullable(),
  after: z.object({ user: z.string(), relation: z.string(), object: z.string() }).nullable(),
  lsn: z.string(),
  commit_time: z.number()
});

type CDCTuplePayload = z.infer<typeof cdcTuplePayloadSchema>;

export class FgaCdcCacheInvalidator {
  constructor(private readonly redis: Redis) {}

  public async handleLogicalReplicationBatch(events: CDCTuplePayload[]): Promise<void> {
    const pipeline = this.redis.pipeline();

    for (const raw of events) {
      const event = cdcTuplePayloadSchema.parse(raw);
      const target = event.op === 'd' ? event.before : event.after;
      if (!target) continue;

      // Evict specific check key and broadcast eviction tag across distributed nodes
      const checkKey = `fga:check:${target.user}:${target.relation}:${target.object}`;
      const wildcardKey = `fga:check:*:${target.object}`;

      pipeline.del(checkKey);
      pipeline.publish('fga:cache:evict', JSON.stringify({
        user: target.user,
        relation: target.relation,
        object: target.object,
        lsn: event.lsn
      }));
    }

    await pipeline.exec();
  }
}
```

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 Real-Time CDC Authorization Cache Coherence Standard

OpenFGA Real-Time CDC Authorization Cache Coherence Standard defines an industrial-grade behavioral standard for security engineering. Enforces sub-millisecond distributed cache invalidation for OpenFGA check evaluations via PostgreSQL Logical Decoding (CDC) or Debezium outbox streams. Guarantees that transactional relation-tuple mutations publish strongly-ordered invalidation events, preventing authorization read-after-write privilege desynchronization 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 Cache Invalidations Directly in Application Handlers Without Transactional CDC 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 Cache Invalidations Directly in Application Handlers Without Transactional CDCCritical
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 invalidate distributed authorization caches via Change Data Capture (CDC) streams tied to the relation tuple transaction commit log (WAL) rather than inline best-effort HTTP handler calls.

Engineers MUST ALWAYS invalidate distributed authorization caches via Change Data Capture (CDC) streams tied to the relation tuple transaction commit log (WAL) rather than inline best-effort HTTP handler calls.

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 cache OpenFGA Check API responses using un-versioned or generic entity keys that do not account for transitive graph relations and context.

Engineers MUST NOT cache OpenFGA Check API responses using un-versioned or generic entity keys that do not account for transitive graph relations and context.

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 transactional outbox events or consume PostgreSQL pgoutput CDC events synchronously with relation tuple writes to eliminate read-after-write privilege drift windows.

Services MUST publish transactional outbox events or consume PostgreSQL pgoutput CDC events synchronously with relation tuple writes to eliminate read-after-write privilege drift windows.

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

Cache eviction consumers MUST implement idempotent Lua scripts or pipeline bulk evictions in Redis using exact canonical tuple matchers (`fga

Cache eviction consumers MUST implement idempotent Lua scripts or pipeline bulk evictions in Redis using exact canonical tuple matchers (`fga:check:{user}:{relation}:{object}`).

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

Services MUST enforce bounded TTLs (max 15-30 seconds) on OpenFGA Check evaluation caches as a secondary failsafe against dropped CDC stream partitions.

Services MUST enforce bounded TTLs (max 15-30 seconds) on OpenFGA Check evaluation caches as a secondary failsafe against dropped CDC stream partitions.

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 Real-Time CDC Authorization Cache Coherence Standard critical for AI coding assistants?

Enforces sub-millisecond distributed cache invalidation for OpenFGA check evaluations via PostgreSQL Logical Decoding (CDC) or Debezium outbox streams. Guarantees that transactional relation-tuple mutations publish strongly-ordered invalidation events, preventing authorization read-after-write privilege desynchronization 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 Cache Invalidations Directly in Application Handlers Without Transactional CDC) 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