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

OpenFGA ReBAC Sub-5ms Evaluation and Distributed Cache Invariants

Enforces deterministic sub-5ms tuple evaluation bounds and distributed cache coherence for OpenFGA Relationship-Based Access Control (ReBAC). Mandates in-memory single-flight deduplication, bounded contextual tuple payload sizing, and transactional write-token propagation to eliminate graph-traversal stampedes across distributed service boundaries.

Prohibited Anti-Pattern: Unbounded Remote ReBAC Evaluation with Cache Stampedes and Missing Consistency Tokens

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenFGA ReBAC Sub-5ms Evaluation and Distributed Cache Invariants - Enforces deterministic sub-5ms tuple evaluation bounds and distributed cache coherence for OpenFGA Relationship-Based Access Control (ReBAC). Mandates in-memory single-flight deduplication, bounded contextual tuple payload sizing, and transactional write-token propagation to eliminate graph-traversal stampedes across distributed service boundaries.
globs: src/auth/**/*.ts, src/security/**/*.ts, src/services/**/auth*.ts, src/middleware/authorize*.ts
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/openfga-rebac-latency-cache-invariants"
---

# OpenFGA ReBAC Sub-5ms Evaluation and Distributed Cache Invariants

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Unbounded Remote ReBAC Evaluation with Cache Stampedes and Missing Consistency Tokens

## System Constraints
You are a Principal Security Architect enforcing OpenFGA ReBAC Latency and Coherence Invariants. Authorization checks sit directly on the hot path of high-throughput services. You must reject any direct, un-memoized remote OpenFGA check invocations, unbounded graph depth checks, or calls lacking contextual consistency tokens that lead to authorization latency regressions or distributed state desynchronization.

## Strict Guidelines
- Engineers MUST ALWAYS implement local in-process memoization with single-flight request coalescing for repeated (user, relation, object) evaluation tuples within the same execution context.
- Engineers MUST propagate OpenFGA consistency tokens or transactional write timestamps in distributed request headers to satisfy Read-Your-Writes consistency without forcing global database synchronization.
- Engineers MUST NOT invoke OpenFGA remote evaluation within tight iterations; batch checks MUST be performed via `batchCheck` or scoped contextual tuples.
- Services MUST enforce strict client-side timeouts (max 15ms total budget, 5ms P99 target) with a deterministic fail-closed fallback or local fallback policy cache.
- Components NEVER accept unbounded contextual tuples in authorization middleware; all ephemeral claims must be strictly validated, bounded in length (max 20 tuples), and sanitized before serialization.

## Bad vs Good Implementations
### Naive OpenFGA Check vs. Coherent Single-Flight Cached Evaluator

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Issues an unbuffered HTTP round-trip directly in the critical request path without client timeouts, circuit breaking, single-flight coalescing, or consistency tokens. Under burst traffic, identical concurrent requests trigger stampedes and latency spikes exceeding 50ms.
```typescript
import { OpenFgaClient } from '@openfga/sdk';
import { Request, Response, NextFunction } from 'express';

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

// ANTI-PATTERN: Direct unmemoized network call in middleware without timeouts,
// consistency parameters, or protection against cache stampedes.
export async function authorizeDocumentAccess(req: Request, res: Response, next: NextFunction) {
  const userId = req.headers['x-user-id'] as string;
  const docId = req.params.docId;

  try {
    const response = await fgaClient.check({
      user: `user:${userId}`,
      relation: 'viewer',
      object: `document:${docId}`,
    });

    if (!response.allowed) {
      return res.status(403).json({ error: 'Access denied' });
    }
    return next();
  } catch (error) {
    return res.status(500).json({ error: 'Auth failed' });
  }
}
```

#### Production Standard (Correct)
> **Standard**: Implements single-flight request coalescing to prevent identical concurrent graph evaluations, enforces an AbortController with a deterministic 15ms ceiling, selects latency vs. consistency preferences based on client write-tokens, and guarantees fail-closed security semantics.
```typescript
import { OpenFgaClient, ConsistencyPreference } from '@openfga/sdk';
import { Request, Response, NextFunction } from 'express';

interface CheckOptions {
  consistencyToken?: string;
  timeoutMs?: number;
}

export class CoherentFgaEvaluator {
  private readonly client: OpenFgaClient;
  private readonly inFlightChecks = new Map<string, Promise<boolean>>();

  constructor(client: OpenFgaClient) {
    this.client = client;
  }

  public async checkAllowed(
    user: string,
    relation: string,
    object: string,
    options: CheckOptions = {}
  ): Promise<boolean> {
    const cacheKey = `${user}#${relation}@${object}:${options.consistencyToken ?? 'default'}`;
    
    const inFlight = this.inFlightChecks.get(cacheKey);
    if (inFlight) {
      return inFlight;
    }

    const timeoutMs = options.timeoutMs ?? 15;
    const checkPromise = (async () => {
      const controller = new AbortController();
      const timer = setTimeout(() => controller.abort(), timeoutMs);

      try {
        const result = await this.client.check(
          {
            user,
            relation,
            object,
            consistency: options.consistencyToken 
              ? ConsistencyPreference.HigherConsistency 
              : ConsistencyPreference.MinimizeLatency,
          },
          { signal: controller.signal }
        );
        return result.allowed ?? false;
      } catch (err: unknown) {
        // Fail-closed invariant on timeout or evaluation failure
        return false;
      } finally {
        clearTimeout(timer);
        this.inFlightChecks.delete(cacheKey);
      }
    })();

    this.inFlightChecks.set(cacheKey, checkPromise);
    return checkPromise;
  }
}

export function createAuthMiddleware(evaluator: CoherentFgaEvaluator) {
  return async (req: Request, res: Response, next: NextFunction) => {
    const userId = req.headers['x-user-id'] as string;
    const consistencyToken = req.headers['x-fga-token'] as string | undefined;
    const docId = req.params.docId;

    if (!userId || !docId) {
      return res.status(401).json({ error: 'Unauthorized' });
    }

    const isAllowed = await evaluator.checkAllowed(
      `user:${userId}`,
      'viewer',
      `document:${docId}`,
      { consistencyToken, timeoutMs: 15 }
    );

    if (!isAllowed) {
      return res.status(403).json({ error: 'Access denied' });
    }

    return next();
  };
}
```

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 ReBAC Sub-5ms Evaluation and Distributed Cache Invariants

OpenFGA ReBAC Sub-5ms Evaluation and Distributed Cache Invariants defines an industrial-grade behavioral standard for security engineering. Enforces deterministic sub-5ms tuple evaluation bounds and distributed cache coherence for OpenFGA Relationship-Based Access Control (ReBAC). Mandates in-memory single-flight deduplication, bounded contextual tuple payload sizing, and transactional write-token propagation to eliminate graph-traversal stampedes across distributed service boundaries. 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: Unbounded Remote ReBAC Evaluation with Cache Stampedes and Missing Consistency Tokens 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 DriftUnbounded Remote ReBAC Evaluation with Cache Stampedes and Missing Consistency TokensCritical
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 implement local in-process memoization with single-flight request coalescing for repeated (user, relation, object) evaluation tuples within the same execution context.

Engineers MUST ALWAYS implement local in-process memoization with single-flight request coalescing for repeated (user, relation, object) evaluation tuples within the same execution 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.
2

Engineers MUST propagate OpenFGA consistency tokens or transactional write timestamps in distributed request headers to satisfy Read-Your-Writes consistency without forcing global database synchronization.

Engineers MUST propagate OpenFGA consistency tokens or transactional write timestamps in distributed request headers to satisfy Read-Your-Writes consistency without forcing global database synchronization.

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 NOT invoke OpenFGA remote evaluation within tight iterations

Engineers MUST NOT invoke OpenFGA remote evaluation within tight iterations; batch checks MUST be performed via `batchCheck` or scoped contextual 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.
4

Services MUST enforce strict client-side timeouts (max 15ms total budget, 5ms P99 target) with a deterministic fail-closed fallback or local fallback policy cache.

Services MUST enforce strict client-side timeouts (max 15ms total budget, 5ms P99 target) with a deterministic fail-closed fallback or local fallback policy cache.

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 accept unbounded contextual tuples in authorization middleware

Components NEVER accept unbounded contextual tuples in authorization middleware; all ephemeral claims must be strictly validated, bounded in length (max 20 tuples), and sanitized before serialization.

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 ReBAC Sub-5ms Evaluation and Distributed Cache Invariants critical for AI coding assistants?

Enforces deterministic sub-5ms tuple evaluation bounds and distributed cache coherence for OpenFGA Relationship-Based Access Control (ReBAC). Mandates in-memory single-flight deduplication, bounded contextual tuple payload sizing, and transactional write-token propagation to eliminate graph-traversal stampedes across distributed service boundaries. 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 (Unbounded Remote ReBAC Evaluation with Cache Stampedes and Missing Consistency Tokens) 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