This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
securitycritical PriorityID: openfga-consistency-tokens-event-streams-production-standard

OpenFGA Consistency Token Propagation in Distributed Event Streams

Enforces deterministic read-after-write consistency for Relationship-Based Access Control (ReBAC) checks within distributed event-driven architectures. Mandates that OpenFGA write operations extract and propagate consistency tokens (Zanzibar zookies) through event metadata, requiring downstream asynchronous consumers to pass these tokens into subsequent authorization checks. This eradicates authorization race conditions and security bypasses caused by replication lag and out-of-order event consumption.

Prohibited Anti-Pattern: Unbounded Event-Driven Read-After-Write Race Conditions Leading to Unauthorized Access or False Denials

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: OpenFGA Consistency Token Propagation in Distributed Event Streams - Enforces deterministic read-after-write consistency for Relationship-Based Access Control (ReBAC) checks within distributed event-driven architectures. Mandates that OpenFGA write operations extract and propagate consistency tokens (Zanzibar zookies) through event metadata, requiring downstream asynchronous consumers to pass these tokens into subsequent authorization checks. This eradicates authorization race conditions and security bypasses caused by replication lag and out-of-order event consumption.
globs: src/events/**/*.{ts,js}, src/consumers/**/*.{ts,js}, src/producers/**/*.{ts,js}, src/services/auth/**/*.{ts,js}, src/middleware/**/*.{ts,js}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/openfga-consistency-tokens-event-streams-production-standard"
---

# OpenFGA Consistency Token Propagation in Distributed Event Streams

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Unbounded Event-Driven Read-After-Write Race Conditions Leading to Unauthorized Access or False Denials

## System Constraints
You are a Principal Security Architect enforcing OpenFGA consistency tokens across distributed event streams. You must ensure that any mutation creating, modifying, or revoking relationships captures OpenFGA's written consistency token and attaches it to outbound message envelopes. Downstream consumers executing ReBAC evaluations MUST supply this consistency token with HIGHER_CONSISTENCY or MINIMALLY_CONSISTENT_WITH invariants to prevent security bypasses stemming from database replication lag.

## Strict Guidelines
- Engineers MUST ALWAYS capture the `consistency_token` returned by OpenFGA `write` operations and inject it into outbound event metadata envelopes (e.g., CloudEvents extension attributes or Kafka headers).
- Engineers MUST NOT evaluate permissions in asynchronous event handlers or subsequent REST requests using default eventually consistent checks without specifying the contextual `consistency_token`.
- Services MUST configure OpenFGA `check` queries in event consumers to use `ConsistencyPreference.HIGHER_CONSISTENCY` when referencing a propagated `consistency_token`.
- Components NEVER drop or omit `consistency_token` fields when transforming, routing, or forwarding domain events across service boundaries.
- Code SHOULD implement circuit-breaking and fallback retry mechanisms with exponential backoff if an OpenFGA replica rejects a query due to not yet having replicated up to the specified consistency token.

## Bad vs Good Implementations
### Propagating and Checking OpenFGA Consistency Tokens Across Event Boundaries

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The producer ignores the consistency token returned by fgaClient.write. The consumer issues a standard check without specifying a consistency token, allowing replication lag in the OpenFGA storage layer to return an unauthorized 'false' response or leak stale access grants.
```typescript
import { OpenFgaClient } from '@openfga/sdk';
import { Producer } from 'kafkajs';

interface DocumentCreatedEvent {
  documentId: string;
  ownerId: string;
}

export async function handleDocumentCreationBad(
  fgaClient: OpenFgaClient,
  producer: Producer,
  documentId: string,
  ownerId: string
): Promise<void> {
  // Anti-Pattern: Writes to OpenFGA without retaining the consistency token
  await fgaClient.write({
    writes: [{
      user: `user:${ownerId}`,
      relation: 'owner',
      object: `document:${documentId}`
    }]
  });

  // Anti-Pattern: Publishing event with zero consistency metadata
  await producer.send({
    topic: 'documents.created',
    messages: [{
      key: documentId,
      value: JSON.stringify({ documentId, ownerId })
    }]
  });
}

export async function processEventBad(
  fgaClient: OpenFgaClient,
  event: DocumentCreatedEvent
): Promise<boolean> {
  // Anti-Pattern: Out-of-order or laggy replica check fails or yields stale authorization state
  const response = await fgaClient.check({
    user: `user:${event.ownerId}`,
    relation: 'can_edit',
    object: `document:${event.documentId}`
  });

  return response.allowed ?? false;
}
```

#### Production Standard (Correct)
> **Standard**: The producer explicitly reads the consistency token emitted during the OpenFGA write and serializes it into the distributed event envelope. The consumer enforces HIGHER_CONSISTENCY passing that exact token, preventing read-after-write race conditions regardless of consumer ordering or replica synchronization lag.
```typescript
import { OpenFgaClient, ConsistencyPreference } from '@openfga/sdk';
import { Producer } from 'kafkajs';

interface DocumentEventEnvelope {
  documentId: string;
  ownerId: string;
  openFgaConsistencyToken: string;
  timestamp: string;
}

export async function handleDocumentCreationGood(
  fgaClient: OpenFgaClient,
  producer: Producer,
  documentId: string,
  ownerId: string
): Promise<void> {
  // Invariant: Capture the write response containing the consistency token
  const writeResult = await fgaClient.write({
    writes: [{
      user: `user:${ownerId}`,
      relation: 'owner',
      object: `document:${documentId}`
    }]
  });

  const consistencyToken = writeResult.writes?.[0]?.consistency_token;
  if (!consistencyToken) {
    throw new Error('Invariant Violation: OpenFGA write failed to emit consistency token');
  }

  const envelope: DocumentEventEnvelope = {
    documentId,
    ownerId,
    openFgaConsistencyToken: consistencyToken,
    timestamp: new Date().toISOString()
  };

  // Invariant: Propagate consistency token in event headers/envelope
  await producer.send({
    topic: 'documents.created',
    messages: [{
      key: documentId,
      value: JSON.stringify(envelope),
      headers: {
        'fga-consistency-token': consistencyToken
      }
    }]
  });
}

export async function processEventGood(
  fgaClient: OpenFgaClient,
  envelope: DocumentEventEnvelope
): Promise<boolean> {
  // Invariant: Supply consistency token with HIGHER_CONSISTENCY preference
  const response = await fgaClient.check({
    user: `user:${envelope.ownerId}`,
    relation: 'can_edit',
    object: `document:${envelope.documentId}`,
    consistency: ConsistencyPreference.HIGHER_CONSISTENCY
  }, {
    consistencyToken: envelope.openFgaConsistencyToken
  });

  return response.allowed ?? false;
}
```

Recommended Agent Skills (askills.dev)

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

Architectural Specification & Invariant Rationale

Architectural Invariant Design: OpenFGA Consistency Token Propagation in Distributed Event Streams

OpenFGA Consistency Token Propagation in Distributed Event Streams defines an industrial-grade behavioral standard for security engineering. Enforces deterministic read-after-write consistency for Relationship-Based Access Control (ReBAC) checks within distributed event-driven architectures. Mandates that OpenFGA write operations extract and propagate consistency tokens (Zanzibar zookies) through event metadata, requiring downstream asynchronous consumers to pass these tokens into subsequent authorization checks. This eradicates authorization race conditions and security bypasses caused by replication lag and out-of-order event consumption. 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 Event-Driven Read-After-Write Race Conditions Leading to Unauthorized Access or False Denials 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 Event-Driven Read-After-Write Race Conditions Leading to Unauthorized Access or False DenialsCritical
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 `consistency_token` returned by OpenFGA `write` operations and inject it into outbound event metadata envelopes (e.g., CloudEvents extension attributes or Kafka headers).

Engineers MUST ALWAYS capture the `consistency_token` returned by OpenFGA `write` operations and inject it into outbound event metadata envelopes (e.g., CloudEvents extension attributes or Kafka headers).

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 evaluate permissions in asynchronous event handlers or subsequent REST requests using default eventually consistent checks without specifying the contextual `consistency_token`.

Engineers MUST NOT evaluate permissions in asynchronous event handlers or subsequent REST requests using default eventually consistent checks without specifying the contextual `consistency_token`.

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 configure OpenFGA `check` queries in event consumers to use `ConsistencyPreference.HIGHER_CONSISTENCY` when referencing a propagated `consistency_token`.

Services MUST configure OpenFGA `check` queries in event consumers to use `ConsistencyPreference.HIGHER_CONSISTENCY` when referencing a propagated `consistency_token`.

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

Components NEVER drop or omit `consistency_token` fields when transforming, routing, or forwarding domain events across service boundaries.

Components NEVER drop or omit `consistency_token` fields when transforming, routing, or forwarding domain events across service boundaries.

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

Code SHOULD implement circuit-breaking and fallback retry mechanisms with exponential backoff if an OpenFGA replica rejects a query due to not yet having replicated up to the specified consistency token.

Code SHOULD implement circuit-breaking and fallback retry mechanisms with exponential backoff if an OpenFGA replica rejects a query due to not yet having replicated up to the specified consistency token.

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 Consistency Token Propagation in Distributed Event Streams critical for AI coding assistants?

Enforces deterministic read-after-write consistency for Relationship-Based Access Control (ReBAC) checks within distributed event-driven architectures. Mandates that OpenFGA write operations extract and propagate consistency tokens (Zanzibar zookies) through event metadata, requiring downstream asynchronous consumers to pass these tokens into subsequent authorization checks. This eradicates authorization race conditions and security bypasses caused by replication lag and out-of-order event consumption. 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 Event-Driven Read-After-Write Race Conditions Leading to Unauthorized Access or False Denials) 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