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

OpenFGA CDC-Driven Distributed Consistency Cache Invalidation Standard

Mandates that OpenFGA authorization check caching layers derive invalidations strictly through transactional Change Data Capture (CDC) streams rather than application-layer dual writes. Guarantees sub-millisecond decision latency with causal consistency by binding monotonic transaction logs to distributed cache eviction pipelines.

Prohibited Anti-Pattern: Dual-Write Application-Level Cache Eviction for Authorization Tuples

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenFGA CDC-Driven Distributed Consistency Cache Invalidation Standard - Mandates that OpenFGA authorization check caching layers derive invalidations strictly through transactional Change Data Capture (CDC) streams rather than application-layer dual writes. Guarantees sub-millisecond decision latency with causal consistency by binding monotonic transaction logs to distributed cache eviction pipelines.
globs: src/**/*.ts, src/auth/**/*.ts, src/fga/**/*.ts, src/services/**/*.ts, src/workers/**/*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/openfga-cdc-cache-invalidation-standard"
---

# OpenFGA CDC-Driven Distributed Consistency Cache Invalidation Standard

> **Severity**: CRITICAL | **Category**: backend
> **Anti-Pattern Warning**: Dual-Write Application-Level Cache Eviction for Authorization Tuples

## System Constraints
You are a Principal Engineer enforcing the OpenFGA CDC-Driven Distributed Consistency Cache Invalidation Standard. You must reject any application-level dual-write cache eviction patterns for authorization decisions. Ensure all authorization check caching utilizes monotonic sequence numbers or consistency tokens sourced from transactional database WAL events via CDC pipelines.

## Strict Guidelines
- Engineers MUST NOT perform inline cache invalidation or cache updates within HTTP request handlers after writing OpenFGA relationship tuples.
- Engineers MUST emit OpenFGA tuple mutations via transactional storage (e.g., PostgreSQL with Transactional Outbox or direct WAL streaming) captured by CDC connectors.
- Code MUST partition CDC stream topics by canonical root entity key (`object_type:object_id`) to ensure strictly ordered event processing for any specific authorization context.
- Services MUST validate incoming authorization check requests against a consistency token or monotonic sequence/LSN to prevent read-after-write authorization bypass.
- Cache consumers MUST process CDC records idempotently using monotonic revision checking to ensure stale out-of-order deliveries do not resurrect or corrupt valid states.
- Components NEVER store indefinite TTLs for authorization cache entries; all entries MUST include a jittered safety TTL fallback regardless of CDC reliability guarantees.

## Bad vs Good Implementations
### Application Dual-Write Eviction vs. Monotonic CDC Stream Worker

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Directly mutating the cache after writing to OpenFGA causes split-brain scenarios: if the Redis command fails, the user retains unauthorized access indefinitely. It also races against concurrent read queries that can re-populate the cache with stale data before the distributed write fully propagates.
```typescript
import { OpenFgaClient } from '@openfga/sdk';
import { Redis } from 'ioredis';

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

// ANTI-PATTERN: Dual-write in business handler creates race conditions,
// stale caches on failure, and reads uncommitted or lagging replicas.
export async function revokeDocumentAccess(userId: string, docId: string) {
  await fga.write({
    deletes: [{
      user: `user:${userId}`,
      relation: 'viewer',
      object: `document:${docId}`,
    }],
  });

  // Flawed: If this network call fails or races against a concurrent Check query,
  // the cache is poisoned with stale permissions until key expiration.
  const cacheKey = `fga:check:user:${userId}:viewer:document:${docId}`;
  await redis.del(cacheKey);
}
```

#### Production Standard (Correct)
> **Standard**: Invalidations are driven entirely by ordered transaction log streams (CDC). Monotonic Log Sequence Numbers (LSN) guarantee that older events cannot overwrite newer invalidations, eliminating dual-write failures and keeping caching provably consistent with the database log.
```typescript
import { Redis } from 'ioredis';

interface TupleMutationCDCEvent {
  eventId: string;
  lsn: string;
  operation: 'INSERT' | 'DELETE';
  tuple: {
    user: string;
    relation: string;
    object: string;
  };
  committedAt: number;
}

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

  // PRODUCTION RULE: Process CDC events ordered deterministically by object partition key
  public async processBatch(events: TupleMutationCDCEvent[]): Promise<void> {
    const pipeline = this.redis.pipeline();

    for (const event of events) {
      const { user, relation, object } = event.tuple;
      const exactCheckKey = `fga:decision:${user}:${relation}:${object}`;
      const entityWildcardKey = `fga:idx:${object}`;
      const versionKey = `fga:ver:${object}`;

      // Increment monotonic entity epoch and evict cached decision key atomically
      const luaScript = `
        local currentLsn = redis.call('HGET', KEYS[1], 'last_lsn')
        if not currentLsn or ARGV[1] > currentLsn then
          redis.call('HSET', KEYS[1], 'last_lsn', ARGV[1], 'epoch', ARGV[2])
          redis.call('DEL', KEYS[2])
          redis.call('DEL', KEYS[3])
          return 1
        end
        return 0
      `;

      pipeline.eval(
        luaScript,
        3,
        versionKey,
        exactCheckKey,
        entityWildcardKey,
        event.lsn,
        event.committedAt.toString()
      );
    }

    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 CDC-Driven Distributed Consistency Cache Invalidation Standard

OpenFGA CDC-Driven Distributed Consistency Cache Invalidation Standard defines an industrial-grade behavioral standard for backend engineering. Mandates that OpenFGA authorization check caching layers derive invalidations strictly through transactional Change Data Capture (CDC) streams rather than application-layer dual writes. Guarantees sub-millisecond decision latency with causal consistency by binding monotonic transaction logs to distributed cache eviction pipelines. 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 Cache Eviction for Authorization Tuples 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 Cache Eviction for Authorization TuplesCritical
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 perform inline cache invalidation or cache updates within HTTP request handlers after writing OpenFGA relationship tuples.

Engineers MUST NOT perform inline cache invalidation or cache updates within HTTP request handlers after writing OpenFGA relationship tuples.

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 emit OpenFGA tuple mutations via transactional storage (e.g., PostgreSQL with Transactional Outbox or direct WAL streaming) captured by CDC connectors.

Engineers MUST emit OpenFGA tuple mutations via transactional storage (e.g., PostgreSQL with Transactional Outbox or direct WAL streaming) captured by CDC connectors.

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

Code MUST partition CDC stream topics by canonical root entity key (`object_type

Code MUST partition CDC stream topics by canonical root entity key (`object_type:object_id`) to ensure strictly ordered event processing for any specific authorization 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.
4

Services MUST validate incoming authorization check requests against a consistency token or monotonic sequence/LSN to prevent read-after-write authorization bypass.

Services MUST validate incoming authorization check requests against a consistency token or monotonic sequence/LSN to prevent read-after-write authorization bypass.

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

Cache consumers MUST process CDC records idempotently using monotonic revision checking to ensure stale out-of-order deliveries do not resurrect or corrupt valid states.

Cache consumers MUST process CDC records idempotently using monotonic revision checking to ensure stale out-of-order deliveries do not resurrect or corrupt valid states.

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

Components NEVER store indefinite TTLs for authorization cache entries

Components NEVER store indefinite TTLs for authorization cache entries; all entries MUST include a jittered safety TTL fallback regardless of CDC reliability guarantees.

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 Distributed Consistency Cache Invalidation Standard critical for AI coding assistants?

Mandates that OpenFGA authorization check caching layers derive invalidations strictly through transactional Change Data Capture (CDC) streams rather than application-layer dual writes. Guarantees sub-millisecond decision latency with causal consistency by binding monotonic transaction logs to distributed cache eviction pipelines. 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 Cache Eviction for Authorization Tuples) 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