Skip to content

SpiceDB vs Auth0 FGA: Relationship-Based Authorization Compared

SpiceDB vs Auth0 FGA (OpenFGA): when ZedTokens, self-hosting or AuthZed's managed SpiceDB beat the default, plus list queries, outbox sync and pricing.

Ayhan Sipahi Ayhan Sipahi

SpiceDB and Auth0 FGA are the two leading Zanzibar-inspired authorization systems, but they make different trade-offs. SpiceDB is a gRPC-first engine that you self-host or buy as a managed service from AuthZed. Every write returns a ZedToken, and later reads can demand data at least that fresh. Auth0 FGA is a REST-first managed service built on OpenFGA. It can bypass its cache per request, but it has no such token.

For most teams the default is Auth0 FGA, or self-hosted OpenFGA when an enterprise contract with Okta is not an option. One requirement flips that default to SpiceDB: many hot-path checks must never run against an ACL older than the content they guard (Zanzibar’s New Enemy problem), and you cannot afford a cache bypass on each of them. Both systems can make a committed revocation visible on the next read by skipping the cache. SpiceDB can also bind a check to a ZedToken stored with the resource. A token marks a revision of the whole datastore, so a check bound to it sees every revocation committed before the resource last changed, folder and group removals included, and still avoids full consistency. The cache bypass stays necessary only to show an indirect revocation at once on content that has not changed since. Hosting is the other fork: authorization data that cannot leave infrastructure you control means self-hosting, where OpenFGA and SpiceDB are both open source and the same ordering question picks between them. Schema syntax, API ergonomics, and published scale ceilings matter less than those two.

Note

This is Part 3 of the External Authorization Systems series. Part 1 covers the full platform landscape, and Part 2 focuses on AWS Cognito + Verified Permissions for SaaS.

Google Zanzibar Heritage#

Both SpiceDB and Auth0 FGA trace their design back to the same source: Google’s Zanzibar paper, published at USENIX ATC 2019. Zanzibar is Google’s internal authorization system that powers permissions for Drive, Calendar, Cloud, Maps, Photos, and YouTube. It handles trillions of access control lists and millions of authorization requests per second with 95th-percentile latency under 10 milliseconds.

The Zanzibar paper introduced several concepts that both systems implement:

  • Relationship tuples: The atomic unit of authorization data, written as (user, relation, object). “User X is editor of Document Y” becomes a tuple.
  • Namespace configuration: A schema that defines what types of objects exist and what relations they can have.
  • Relation rewriting: Computing permissions by traversing and combining relationships. “Can view” might mean “is a viewer OR is an editor OR is an owner.”
  • Consistency tokens: Mechanisms to ensure that permission checks reflect recent writes (Zanzibar calls these “zookies”).

Where SpiceDB and Auth0 FGA diverge is in how faithfully they implement these concepts and what trade-offs they make around consistency, deployment, and API design.

SpiceDB implements the full Zanzibar consistency model, including at_least_as_fresh and fully_consistent semantics. Auth0 FGA (via OpenFGA) offers a per-request cache bypass, HIGHER_CONSISTENCY, and no token-based mode.

Schema Comparison#

The schema is where you model your authorization logic. Both systems use a declarative language for defining types, relations, and permissions, but the syntax and capabilities differ.

SpiceDB Schema Language#

SpiceDB uses its own schema language with definition blocks, relation declarations, and permission computations. Relations define what types of subjects can be assigned. Permissions define computed access by combining relations with set operations.

// SpiceDB schema: document management with organizations
definition user {}

definition organization {
    relation admin: user
    relation member: user

    permission manage = admin
}

definition folder {
    relation viewer: user | organization#member
    relation editor: user | organization#admin

    permission view = viewer + editor
    permission edit = editor
}

definition document {
    relation parent_folder: folder
    relation owner: user
    relation editor: user
    relation viewer: user

    permission view = viewer + editor + owner + parent_folder->view
    permission edit = editor + owner + parent_folder->edit
    permission delete = owner
}

Key features of the SpiceDB schema:

  • Arrow operator (->): Follows relationships across objects. parent_folder->view means “anyone who can view the parent folder can also view this document.”
  • Union (+): Combines multiple relations. viewer + editor + owner means any of those relations grants the permission.
  • Intersection (&) and exclusion (-): Support for AND and NOT logic in permission computation.
  • Subject relations (organization#member): References subjects through their relations, not just their identity.

OpenFGA DSL (Auth0 FGA)#

Auth0 FGA uses the OpenFGA DSL, which has a different syntax but models similar concepts. Types replace definitions, and the define keyword declares both relations and permissions.

model
  schema 1.1

type user

type organization
  relations
    define admin: [user]
    define member: [user]
    define manage: admin

type folder
  relations
    define viewer: [user, organization#member]
    define editor: [user, organization#admin]
    define view: viewer or editor
    define edit: editor

type document
  relations
    define parent_folder: [folder]
    define owner: [user]
    define editor: [user]
    define viewer: [user]
    define view: viewer or editor or owner or view from parent_folder
    define edit: editor or owner or edit from parent_folder
    define delete: owner

Key features of the OpenFGA DSL:

  • from keyword: Equivalent to SpiceDB’s arrow operator. view from parent_folder follows the parent_folder relation and checks view permission.
  • or / and / but not: Set operations expressed with keywords rather than symbols.
  • Type restrictions in brackets: [user, organization#member] specifies which subject types are allowed in a relation.
  • No separate permission keyword: Relations and permissions use the same define syntax. The distinction is implicit: relations that reference [type] are assignable; those that reference other relations are computed.

Schema Comparison Table#

FeatureSpiceDBOpenFGA (Auth0 FGA)
Type definitiondefinition keywordtype keyword
Relation declarationrelation name: typedefine name: [type]
Permission computationpermission name = exprdefine name: expr
Follow relationships-> (arrow)from keyword
Union+or
Intersection&and
Exclusion-but not
Caveats/conditionsCaveatsConditions
Wildcard accessuser:*user:*
Playgroundplay.authzed.complay.fga.dev

At the schema level, both model the same authorization logic, and the difference is mostly syntax. The choice between the systems is made elsewhere: in consistency, hosting, and cost, covered below.

Architecture Differences#

The architectural differences between SpiceDB and Auth0 FGA reflect their different design philosophies: self-hosted flexibility versus managed simplicity.

Auth0 FGA Architecture

Application

REST API
HTTPS

Auth0 FGA
Managed Service

Managed Store
Multi-Region

SpiceDB Architecture

Application

gRPC API
Port 50051

SpiceDB Engine

PostgreSQL /
CockroachDB /
MySQL

SpiceDB#

  • Protocol: gRPC-first with an optional HTTP/REST gateway. gRPC is the primary integration path and offers better performance characteristics (HTTP/2, binary protocol, streaming).
  • Deployment: Self-hosted on Kubernetes, Docker, or bare metal. Authzed offers a managed service for teams that prefer not to run infrastructure.
  • Storage backends: PostgreSQL, CockroachDB, MySQL, or Memdb (in-memory for testing). CockroachDB enables horizontally scaled deployments with strong consistency.
  • Scaling: Horizontal scaling via multiple SpiceDB instances backed by a shared datastore. Cache layers reduce datastore load for read-heavy workloads.

Auth0 FGA#

  • Protocol: REST-first (HTTPS). SDKs abstract the REST calls, but the underlying API is HTTP/JSON.
  • Deployment: Fully managed SaaS. No self-hosting option for Auth0 FGA itself, though you can self-host OpenFGA (the open-source engine) if needed.
  • Storage: Managed by Okta. Multi-region deployment in US, EU, and Australia. Private cloud deployment available on AWS.
  • Scaling: Managed scaling handled by the platform. The product page cites billions of authorization tuples and millions of requests per second. Those describe the platform design envelope; your own quotas come from your plan. The enterprise plan lists 500 Check requests per second and 10 million tuples, with more tuples available to purchase.

Architecture Comparison Table#

AspectSpiceDBAuth0 FGA
Primary protocolgRPCREST (HTTPS)
Self-hostingYes (open-source)No (OpenFGA is open-source)
Managed optionAuthzedAuth0 FGA
StoragePostgreSQL, CockroachDB, MySQLManaged (opaque)
Multi-regionVia CockroachDB or infra setupBuilt-in (US, EU, AU)
SLADepends on your infra99.99% (vendor-documented)
Open sourceSpiceDB (Apache 2.0)OpenFGA (Apache 2.0)

Code Examples#

The following examples implement the same scenario in both systems: a document management application where users can be assigned as owners, editors, or viewers, and permissions flow through folder hierarchies.

SpiceDB with TypeScript#

SpiceDB uses the @authzed/authzed-node client library, which communicates over gRPC.

import { v1 } from "@authzed/authzed-node";

// Initialize the SpiceDB client (gRPC); .promises exposes async methods
const client = v1.NewClient(
  "spicedb-preshared-key",
  "localhost:50051",
  v1.ClientSecurity.INSECURE_LOCALHOST_ALLOWED
).promises;

// --- Write relationships ---
const writeResponse = await client.writeRelationships(
  v1.WriteRelationshipsRequest.create({
    updates: [
      {
        operation: v1.RelationshipUpdate_Operation.TOUCH,
        relationship: {
          resource: { objectType: "document", objectId: "doc-roadmap" },
          relation: "editor",
          subject: {
            object: { objectType: "user", objectId: "alice" },
          },
        },
      },
      {
        operation: v1.RelationshipUpdate_Operation.TOUCH,
        relationship: {
          resource: { objectType: "document", objectId: "doc-roadmap" },
          relation: "viewer",
          subject: {
            object: { objectType: "user", objectId: "bob" },
          },
        },
      },
    ],
  })
);

// writeResponse.writtenAt contains the ZedToken for consistency
const zedToken = writeResponse.writtenAt;
if (!zedToken) throw new Error("SpiceDB returned no ZedToken");

// --- Check permission ---
const checkResult = await client.checkPermission(
  v1.CheckPermissionRequest.create({
    consistency: {
      requirement: {
        oneofKind: "atLeastAsFresh",
        atLeastAsFresh: zedToken, // Ensure this read reflects our write
      },
    },
    resource: { objectType: "document", objectId: "doc-roadmap" },
    permission: "edit",
    subject: {
      object: { objectType: "user", objectId: "alice" },
    },
  })
);

const canEdit =
  checkResult.permissionship ===
  v1.CheckPermissionResponse_Permissionship.HAS_PERMISSION;
// canEdit === true (alice is an editor)

// --- Lookup resources ---
// Find all documents that bob can view
const lookupResults = await client.lookupResources(
  v1.LookupResourcesRequest.create({
    consistency: {
      requirement: {
        oneofKind: "atLeastAsFresh",
        atLeastAsFresh: zedToken,
      },
    },
    resourceObjectType: "document",
    permission: "view",
    subject: {
      object: { objectType: "user", objectId: "bob" },
    },
  })
);

// The promise form collects the gRPC stream into an array when it closes
const accessibleDocs = lookupResults.map((r) => r.resourceObjectId);
// accessibleDocs includes "doc-roadmap" (bob is a viewer)

Auth0 FGA with TypeScript#

Auth0 FGA uses the @openfga/sdk client library, which communicates over REST.

import { OpenFgaClient, ConsistencyPreference } from "@openfga/sdk";

// Initialize the OpenFGA client (REST)
const fgaClient = new OpenFgaClient({
  apiUrl: process.env.FGA_API_URL!,  // e.g., https://api.us1.fga.dev
  storeId: process.env.FGA_STORE_ID!,
  authorizationModelId: process.env.FGA_MODEL_ID!,
  credentials: {
    method: "client_credentials",
    config: {
      clientId: process.env.FGA_CLIENT_ID!,
      clientSecret: process.env.FGA_CLIENT_SECRET!,
      apiTokenIssuer: "fga.us.auth0.com",
      apiAudience: "https://api.us1.fga.dev/",
    },
  },
});

// --- Write tuples ---
await fgaClient.write({
  writes: [
    {
      user: "user:alice",
      relation: "editor",
      object: "document:doc-roadmap",
    },
    {
      user: "user:bob",
      relation: "viewer",
      object: "document:doc-roadmap",
    },
  ],
});

// --- Check permission ---
const { allowed } = await fgaClient.check({
  user: "user:alice",
  relation: "edit",
  object: "document:doc-roadmap",
}, {
  consistency: ConsistencyPreference.HigherConsistency,
});
// allowed === true (alice is an editor, edit = editor or owner)

// --- List objects ---
// Find all documents that bob can view
const { objects } = await fgaClient.listObjects({
  user: "user:bob",
  relation: "view",
  type: "document",
}, {
  consistency: ConsistencyPreference.HigherConsistency,
});
// objects includes "document:doc-roadmap" (bob is a viewer)

Side-by-Side API Comparison#

OperationSpiceDBAuth0 FGA (OpenFGA)
Write relationshipswriteRelationships (gRPC)write (REST)
Check permissioncheckPermission (gRPC)check (REST)
Find accessible resourceslookupResources (streaming gRPC)listObjects (REST)
Find users with accesslookupSubjects (streaming gRPC)listUsers (REST)
Read relationshipsreadRelationships (streaming gRPC)read (REST)
Delete relationshipswriteRelationships with DELETE opwrite with deletes array
Consistency controlZedToken per requestHIGHER_CONSISTENCY flag

The Dual-Write Problem#

Both SpiceDB and Auth0 FGA are external stores. Your application data lives in your database. Authorization relationships live in the authorization system. Keeping these two in sync is the dual-write problem, and it is the most underestimated operational challenge of relationship-based authorization.

The Problem#

Consider creating a document with an owner:

  1. Application writes the document record to PostgreSQL
  2. Application writes user:alice is owner of document:doc-123 to SpiceDB (or Auth0 FGA)
  3. If step 2 fails, the document exists but has no authorization data

The reverse is equally dangerous: if step 1 fails but step 2 succeeds, the authorization system references a document that does not exist.

Application

App Database

SpiceDB /
Auth0 FGA

There is no distributed transaction between your database and the authorization system. You need a pattern to handle this.

Transactional Outbox Pattern#

The most reliable solution is the transactional outbox pattern. Write both the application data and the authorization event to the same database in a single transaction. A separate worker process then reads the outbox and syncs to the authorization store.

The worker is where this pattern goes wrong. If two workers pick up a grant and a revoke for the same document and apply them in the wrong order, the revoked relationship is written back. The revoked user keeps access, the outcome the consistency section below guards against, and unlike a stale cache read it does not heal on its own. A worker that keeps the authorization store correct needs five properties:

  • Both directions: grants become TOUCH events and revocations become DELETE events.
  • Idempotent operations: a retried event must not fail or double-apply. SpiceDB’s TOUCH upserts, and its DELETE is a no-op when the relationship does not exist. OpenFGA rejects duplicate writes by default; from v1.10.0 it accepts on_duplicate: "ignore" on writes and on_missing: "ignore" on deletes.
  • Ordering per resource: a newer event for a document waits until every older event for that document is done.
  • Locked claims: FOR UPDATE SKIP LOCKED plus a lease, so parallel workers never claim the same event and a crashed worker’s events come back.
  • Retry with backoff: a failed event stays pending with a later next_attempt_at, and turns dead after a fixed number of attempts.
CREATE TABLE authz_outbox (
  id              bigserial   PRIMARY KEY,
  resource_key    text        NOT NULL,  -- e.g. document:doc-123
  op              text        NOT NULL CHECK (op IN ('TOUCH', 'DELETE')),
  payload         jsonb       NOT NULL,
  status          text        NOT NULL DEFAULT 'pending',  -- pending, done, dead
  attempts        integer     NOT NULL DEFAULT 0,
  next_attempt_at timestamptz NOT NULL DEFAULT now(),
  locked_until    timestamptz,
  last_error      text,
  processed_at    timestamptz
);

CREATE INDEX authz_outbox_pending ON authz_outbox (resource_key, id)
  WHERE status = 'pending';
interface Relationship {
  resource: { type: string; id: string };
  relation: string;
  subject: { type: string; id: string };
}

type AuthzOp = "TOUCH" | "DELETE";

// Any Postgres client with a query(text, values) method
interface Queryable {
  query<R = unknown>(text: string, values?: unknown[]): Promise<{ rows: R[] }>;
}

interface Database extends Queryable {
  transaction<T>(fn: (tx: Queryable) => Promise<T>): Promise<T>;
}

// Adapter over SpiceDB or OpenFGA; both operations must be idempotent
interface AuthzWriter {
  apply(op: AuthzOp, rel: Relationship, signal: AbortSignal): Promise<void>;
}

async function enqueue(tx: Queryable, op: AuthzOp, rel: Relationship): Promise<void> {
  await tx.query(
    "INSERT INTO authz_outbox (resource_key, op, payload) VALUES ($1, $2, $3)",
    [`${rel.resource.type}:${rel.resource.id}`, op, JSON.stringify(rel)]
  );
}

export async function createDocument(
  db: Database,
  doc: { id: string; title: string; ownerId: string }
): Promise<void> {
  await db.transaction(async (tx) => {
    await tx.query(
      "INSERT INTO documents (id, title, owner_id) VALUES ($1, $2, $3)",
      [doc.id, doc.title, doc.ownerId]
    );
    await enqueue(tx, "TOUCH", {
      resource: { type: "document", id: doc.id },
      relation: "owner",
      subject: { type: "user", id: doc.ownerId },
    });
  });
}

export async function revokeViewer(
  db: Database,
  docId: string,
  userId: string
): Promise<void> {
  await db.transaction(async (tx) => {
    // Every change to an existing document takes this lock first,
    // so its events commit in outbox id order
    await tx.query("SELECT 1 FROM documents WHERE id = $1 FOR UPDATE", [docId]);
    await tx.query(
      "DELETE FROM document_shares WHERE document_id = $1 AND user_id = $2",
      [docId, userId]
    );
    await enqueue(tx, "DELETE", {
      resource: { type: "document", id: docId },
      relation: "viewer",
      subject: { type: "user", id: userId },
    });
  });
}

const LEASE_SECONDS = 30;
const CALL_TIMEOUT_MS = 10_000;
// Start no new call after this point, so every call ends inside the lease
const START_CUTOFF_MS = LEASE_SECONDS * 1000 - 2 * CALL_TIMEOUT_MS;
const MAX_ATTEMPTS = 10;

// Claim the oldest pending event per resource. A newer event for the same
// resource waits until every older one is done or dead. A non-null $3
// limits the claim to one resource.
const CLAIM_SQL = `
  UPDATE authz_outbox o
     SET locked_until = now() + make_interval(secs => $2)
   WHERE o.id IN (
     SELECT c.id FROM authz_outbox c
      WHERE c.status = 'pending'
        AND c.next_attempt_at <= now()
        AND (c.locked_until IS NULL OR c.locked_until < now())
        AND ($3::text IS NULL OR c.resource_key = $3)
        AND NOT EXISTS (
          SELECT 1 FROM authz_outbox e
           WHERE e.resource_key = c.resource_key
             AND e.status = 'pending'
             AND e.id < c.id)
      ORDER BY c.id
      LIMIT $1
      FOR UPDATE SKIP LOCKED)
  RETURNING o.id, o.op, o.payload, o.attempts`;

const DONE_SQL = `
  UPDATE authz_outbox
     SET status = 'done', locked_until = NULL, processed_at = now()
   WHERE id = $1`;

// Exponential backoff capped at 5 minutes; dead rows need an alert
const FAIL_SQL = `
  UPDATE authz_outbox
     SET attempts = attempts + 1,
         last_error = $2,
         locked_until = NULL,
         status = CASE WHEN attempts + 1 >= $3 THEN 'dead' ELSE 'pending' END,
         next_attempt_at = now() + make_interval(secs => least(power(2, attempts + 1), 300))
   WHERE id = $1`;

interface OutboxRow {
  id: string; // bigserial
  op: AuthzOp;
  payload: Relationship;
  attempts: number;
}

export async function processOutbox(
  db: Queryable,
  authz: AuthzWriter,
  batchSize = 20,
  resourceKey: string | null = null
): Promise<number> {
  // Measured before the claim, so it never runs ahead of the lease
  const started = performance.now();
  const { rows } = await db.query<OutboxRow>(CLAIM_SQL, [
    batchSize,
    LEASE_SECONDS,
    resourceKey,
  ]);

  let handled = 0;
  for (const row of rows) {
    // Unhandled rows keep their lease, expire, and are claimed again in order
    if (performance.now() - started > START_CUTOFF_MS) break;
    try {
      await authz.apply(row.op, row.payload, AbortSignal.timeout(CALL_TIMEOUT_MS));
      await db.query(DONE_SQL, [row.id]);
    } catch (error) {
      const message = error instanceof Error ? error.message : String(error);
      await db.query(FAIL_SQL, [row.id, message, MAX_ATTEMPTS]);
    }
    handled++;
  }
  return handled;
}

Three details carry the ordering guarantee. The NOT EXISTS clause hides an event while an older pending event for the same resource exists, even if another worker holds that older one. The FOR UPDATE on the document row in revokeViewer makes two concurrent changes to one document commit one after the other, so their outbox ids follow commit order. That holds only if every function that enqueues an event for an existing document, grants included, takes the same SELECT ... FOR UPDATE on the document row before it inserts into the outbox. The worker starts a call only while the lease has room for that call to finish, so a slow batch stops early. Another worker can then reclaim an event only after its previous holder is done with it, so it never applies a newer event first, as long as a call that timed out did not still commit on the server. AbortSignal.timeout cancels the request on the client only. Pass the same deadline to the server as well (a gRPC deadline for SpiceDB), so the server cancels the call when the deadline passes, which narrows the window in which a timed-out write can still commit. A dead row means the authorization store may disagree with the application for that resource. Because both operations are idempotent, re-enqueueing the resource’s current state repairs it.

The outbox also creates a visible delay. Between the commit and the worker run, the owner tuple does not exist, so the user who just created a document fails a permission check on it. Two mitigations work together. Right after the transaction commits, call processOutbox(db, authz, 1, resourceKey) with the new document’s key. The filter claims only that document’s event, so the usual case finishes within the request and the poller only handles failures. And let the create endpoint return the document it just wrote without a check, since the caller is its owner by construction; later reads go through the authorization system.

Application

DB Transaction

App Table

Outbox Table

Async Worker

SpiceDB /
Auth0 FGA

Alternative Approaches#

Change Data Capture (CDC): Use Debezium or a similar tool to capture database changes and propagate them to the authorization store. More complex to set up but decouples the application from the sync mechanism entirely.

Reconciliation jobs: Accept brief inconsistency and run periodic jobs to compare application state with authorization state, fixing any drift. This is the simplest approach but introduces a window where permissions may be wrong.

Warning

Budget meaningful engineering time for synchronization. The dual-write problem is the most commonly underestimated cost of adopting external authorization systems. AuthZed has published detailed guidance on this topic based on their experience with Google Zanzibar and SpiceDB at scale.

Consistency Models#

Consistency is where SpiceDB and Auth0 FGA differ most significantly. It directly affects whether a recently revoked permission is still honored; the Zanzibar paper calls this the “New Enemy Problem”.

ZedTokens (SpiceDB)#

SpiceDB implements the full Zanzibar consistency model through ZedTokens (the equivalent of Zanzibar’s “zookies”). Every write operation returns a ZedToken. Passing this token on subsequent reads guarantees that the read reflects at least that write.

SpiceDB offers four consistency modes per request:

ModeBehaviorRecommended use
minimize_latencyPrefers data most likely to be cached, may serve stale resultsReads where brief staleness is acceptable; also what a read request gets when it names no mode
at_least_as_freshData is at least as fresh as a given ZedTokenChecks on a resource whose ZedToken you stored with it
at_exact_snapshotData is exactly at a given ZedTokenSeveral pages or bulk checks that must see one revision
fully_consistentBypasses caches, reads the latest data in the datastoreChecks with no stored token where staleness is unacceptable

The default is the same in both systems. A SpiceDB read without a mode uses minimize_latency, and an OpenFGA query without one uses MINIMIZE_LATENCY. SpiceDB writes default to fully_consistent.

The mode that sets SpiceDB apart is at_least_as_fresh with a token stored per resource. AuthZed’s consistency docs recommend updating a resource’s stored ZedToken whenever the resource is created, deleted or changed, or its access changes, and saving it next to the content in the application database. A check on that resource then passes the stored token. It sees every ACL change committed before the resource’s last recorded update, which closes the New Enemy ordering gap: content written after a revocation on that resource is never checked against the ACL from before it. The check still reads from cache whenever the cache is fresh enough, so it does not pay for full consistency.

The token has to come from somewhere. Code that checks access after a revocation usually does not hold the revocation’s own ZedToken, and without one the only safe choice is fully_consistent, the same cache bypass OpenFGA offers. With the outbox pattern above, the SpiceDB adapter can save writtenAt from each write onto the resource row. A content edit that writes no relationship returns no writtenAt. For that case, AuthZed’s docs say to request a new token with a fully consistent check and store it with the new content; the checkedAt field of that CheckPermission response is the token to save.

A token marks a revision of the whole datastore, so one taken at a content change covers every revocation committed before it, folder and group removals included. In the schema above, access also arrives through parent_folder->view and organization#member. What the stored token does not cover is a removal through one of those paths after the document’s last change. Until the document changes again, a check with that token can still show the existing content to the removed user. Checks that must reflect such a removal at once need fully_consistent, or the new token written onto every child row the change affects.

// SpiceDB: per-request consistency control
// Fast check for UI rendering (may use cache)
const uiCheck = await client.checkPermission(
  v1.CheckPermissionRequest.create({
    consistency: {
      requirement: { oneofKind: "minimizeLatency", minimizeLatency: true },
    },
    resource: { objectType: "document", objectId: "doc-123" },
    permission: "view",
    subject: { object: { objectType: "user", objectId: "alice" } },
  })
);

// Check bounded by the token saved on the document row
// (storedToken is the string read from that row)
const docCheck = await client.checkPermission(
  v1.CheckPermissionRequest.create({
    consistency: {
      requirement: {
        oneofKind: "atLeastAsFresh",
        atLeastAsFresh: v1.ZedToken.create({ token: storedToken }),
      },
    },
    resource: { objectType: "document", objectId: "doc-123" },
    permission: "view",
    subject: { object: { objectType: "user", objectId: "alice" } },
  })
);

// No stored token: bypass the cache before a destructive action
const deleteCheck = await client.checkPermission(
  v1.CheckPermissionRequest.create({
    consistency: {
      requirement: { oneofKind: "fullyConsistent", fullyConsistent: true },
    },
    resource: { objectType: "document", objectId: "doc-123" },
    permission: "delete",
    subject: { object: { objectType: "user", objectId: "alice" } },
  })
);

Consistency in Auth0 FGA (OpenFGA)#

OpenFGA offers a HIGHER_CONSISTENCY option on its query APIs (experimental in v1.5.7, enabled by default since v1.6.0). When set, OpenFGA skips its cache, and a self-hosted setup with a read replica sends the query to the primary database. Self-hosted OpenFGA ships with its check cache turned off, so its default reads are already uncached. Auth0 FGA runs two caches, each with a 10-second TTL. Its docs add that HIGHER_CONSISTENCY can still be affected by replication lag when requests are routed across regions.

// Auth0 FGA: consistency flag
const { allowed } = await fgaClient.check({
  user: "user:alice",
  relation: "delete",
  object: "document:doc-123",
}, {
  consistency: ConsistencyPreference.HigherConsistency,
});

This is a binary choice. There is no equivalent to SpiceDB’s at_least_as_fresh with a specific token: you either get default consistency (possibly cached) or higher consistency (no cache, at a latency cost on every such call).

Tip

Consistency tokens similar to ZedTokens, returned by writes and passed to later reads, are an open item on the OpenFGA roadmap. The OpenFGA docs say the project is considering a similar feature in future releases.

Consistency Comparison#

AspectSpiceDBAuth0 FGA (OpenFGA)
Default read modeminimize_latency (cache when possible)MINIMIZE_LATENCY (cache when possible)
Per-request controlFour modesTwo modes
Cache bypassfully_consistentHIGHER_CONSISTENCY
Bounded freshness per resourceat_least_as_fresh with a stored ZedTokenNot available (roadmap item)
Recommended for sensitive checksStored token, else fully_consistentHIGHER_CONSISTENCY

Both systems can enforce a committed revocation on the next read by bypassing the cache. The difference is what the New Enemy ordering costs at volume. In Auth0 FGA, every check that must not run against an ACL older than the content pays for a cache bypass. In SpiceDB, a check bounded by the resource’s stored ZedToken pays only for freshness up to the last change recorded on that resource. When only a few checks need that guarantee (deletes, sharing changes, admin actions), HIGHER_CONSISTENCY on those calls is enough, and Auth0 FGA’s model holds. When most reads in a hot path need it, SpiceDB’s tokens are the cheaper design. Making a revocation through a folder or group visible at once on unchanged content costs the same in both systems: a cache bypass, unless you copy the new token onto the child rows.

Listing What a User Can See#

A permission check answers one question about one resource. Most screens ask a different one: which documents can this user see? That is lookupResources in SpiceDB and listObjects in OpenFGA, and it needs its own design. Its cost follows the size of the graph the query walks, which can be large even when the result is short.

Both list APIs have hard edges:

  • OpenFGA stops at listObjectsMaxResults (default 1,000) or listObjectsDeadline (default 3 seconds), whichever comes first, and returns the results found by then. A long list can come back shorter than the truth.
  • Auth0 FGA returns at most 10,000 objects under a 3-second execution timeout. Its docs warn that relations using and or but not cost more to evaluate than or, and point to Streamed ListObjects for large results.
  • SpiceDB streams lookupResources results until the set is exhausted, with optional_limit and a cursor for paging. AuthZed’s guidance is that the approach fits when a user can access a small set (their example is under 10,000 resources), and that it can get slow quickly with a large dataset or a complex schema.

Three ACL filtering patterns cover most list endpoints:

PatternHow it worksFits whenSpiceDBOpenFGA / Auth0 FGA
Pre-filterList accessible IDs, then query the database with WHERE id = ANY($ids)Each user can access a small setlookupResourceslistObjects
Post-filterFetch a page of candidates from the database, bulk-check it, repeat until the page is fullSearch or filters narrow the candidatesCheckBulkPermissionsBatchCheck
Local indexStream permission changes into your own tables and join against themLarge accessible sets and high trafficMaterialize (early access, AuthZed Dedicated)Read changes from the /changes endpoint, then check the final page

Start with pre-filtering; it is the simplest and works while per-user sets stay small. Move a search endpoint to post-filtering when the accessible set grows, and use cursor-based pagination, since the number of hits per page is unknown in advance. Run a post-filter’s bulk checks at one revision (at_exact_snapshot with the first call’s ZedToken in SpiceDB) so a page does not mix two views of the ACL. A local index is the most scalable option and the most work. With OpenFGA, the docs still recommend a final check on the results to catch revocations the index has not seen yet.

Scalability#

Both systems have been validated at significant scale, though their scaling stories are different.

SpiceDB at Scale#

SpiceDB’s most notable deployment is at OpenAI, where it authorizes access for apps in ChatGPT that connect sources such as Google Drive and Box. AuthZed’s case study cites more than 37 billion documents with fine-grained access controls. OpenAI runs it on AuthZed Dedicated, the managed offering, so the largest public SpiceDB deployment is not a self-hosted one. AuthZed (the company behind SpiceDB) positions the system for AI agent authorization scenarios where permission checks happen at high frequency with complex relationship graphs.

Scaling SpiceDB involves:

  • Horizontal scaling: Add more SpiceDB instances behind a load balancer. All instances share the same datastore.
  • Storage backend choice: CockroachDB for horizontally scalable, strongly consistent storage. PostgreSQL for simpler deployments with vertical scaling. MySQL as an alternative relational backend.
  • Caching: SpiceDB caches frequently accessed relationships. The minimize_latency consistency mode maximizes cache utilization.
  • Watch API: Enables cache invalidation patterns for downstream consumers.

Auth0 FGA at Scale#

Auth0 FGA publishes high-scale figures (tuple count, requests per second) and a 99.99% availability SLA in product materials. What you actually get is set by your plan and contract, so validate the numbers you plan to design around. Scaling itself is handled entirely by the platform: you do not manage infrastructure.

Key scaling characteristics:

  • Multi-region: Automatic deployment across US, EU, and Australia regions.
  • Private cloud: Available on AWS for organizations with data residency requirements.
  • Managed scaling: Okta handles capacity planning, failover, and performance optimization.
  • OpenFGA self-hosted: If you outgrow the managed service or need custom deployment, OpenFGA can be self-hosted with PostgreSQL or MySQL.

Scale Comparison#

MetricSpiceDBAuth0 FGA
Documented scale37B+ documents with fine-grained access (OpenAI, on AuthZed Dedicated)Vendor-published: billions of tuples, millions of requests per second
Scaling approachSelf-managed horizontalFully managed
Storage scalingCockroachDB (horizontal) or PostgreSQL (vertical)Managed (opaque)
Multi-regionVia infrastructure setupBuilt-in
SLADepends on your infra99.99% in vendor docs

Self-Hosted vs. Managed Trade-offs#

The decision between self-hosting SpiceDB and using Auth0 FGA as a managed service goes beyond technical preference. It involves operations burden, compliance, cost, and organizational capability. Two options sit between those poles: AuthZed runs SpiceDB as a managed service, and OpenFGA gives you the Auth0 FGA model on your own servers.

When Self-Hosted SpiceDB Makes Sense#

  • Data sovereignty: Authorization data must stay within specific geographic or network boundaries. Self-hosting gives full control over data residency.
  • Custom storage requirements: You need a specific database backend (CockroachDB for multi-region consistency, for example) or custom backup/recovery procedures.
  • Cost control at scale: Open-source SpiceDB has no license fee, so the cost is the cluster and database you run, plus the people who run them. Whether that beats a managed contract depends on your volume and on the quote you get.
  • Deep integration needs: Direct access to the gRPC API, Watch API for streaming changes, or custom caching layers.
  • Existing Kubernetes expertise: If your team already operates Kubernetes clusters, adding SpiceDB is an incremental step on infrastructure you already run.

When Auth0 FGA Makes Sense#

  • Minimal operational overhead: No infrastructure to manage, no database to tune, no scaling decisions to make.
  • Auth0/Okta ecosystem: If you already use Auth0 for authentication, FGA integrates naturally with your existing identity infrastructure.
  • Quick adoption: REST APIs with official SDKs in multiple languages. Shorter time-to-production compared to self-hosted SpiceDB.
  • SLA requirements: A vendor-managed SLA can be easier to rely on operationally than matching the same target on self-hosted infrastructure, provided your SKU actually covers it.
  • Team size constraints: Small teams that cannot dedicate engineering capacity to authorization infrastructure benefit from a managed service.

Trade-off Matrix#

FactorSelf-Hosted SpiceDBAuth0 FGA (Managed)
PriceNo license fee (open source); you pay for your cluster and databaseNo published price; production needs an enterprise contract
Operations burdenMedium-High (K8s + DB)Low (fully managed)
Time to productionWeeks to monthsDays to weeks
Data residency controlFullLimited to available regions
Consistency modelFull Zanzibar (ZedTokens)HIGHER_CONSISTENCY flag
Vendor lock-inLow (open-source)Medium (Okta ecosystem)
Community supportActive open-source communityOkta enterprise support

Pricing as a Decision Input#

Neither managed option publishes a full price list, so get the quote during the proof of concept and treat it as a decision input.

  • Auth0 FGA: the free trial has no SLA and caps usage (50,000 tuples, 20 Check requests per second). Production use requires an enterprise contract through Okta sales, and the plans page publishes no price.
  • AuthZed: open-source SpiceDB is free to self-host. AuthZed Cloud lists $2 per hour for a deployed permissions system, billed on usage. Dedicated and the self-hosted enterprise license (priced per region and per vCPU) are quoted by sales.
  • Self-hosted OpenFGA: no license fee; the cost is the servers, the database and the on-call time.

Decision Matrix#

The flowchart starts at the hosting question, then lets the ordering requirement pick the engine.

Yes

Yes

No

No

Yes

No

Yes

No

Need Zanzibar-style
ReBAC?

Must authorization data
stay on infra you control?

Many hot-path checks need
New Enemy ordering
without a cache bypass?

SpiceDB self-hosted
ZedToken stored per resource

OpenFGA self-hosted
HIGHER_CONSISTENCY
on sensitive checks

Many hot-path checks need
New Enemy ordering
without a cache bypass?

AuthZed Cloud or Dedicated
Managed SpiceDB

Okta enterprise
contract an option?

Auth0 FGA
Quote it in the PoC

OpenFGA self-hosted
or AuthZed Cloud

Quick Decision Guide#

ScenarioRecommendationReason
Hot-path checks must never run against an ACL older than the content (New Enemy ordering)SpiceDB (self-hosted or AuthZed managed)A ZedToken stored per resource gives that ordering without a cache bypass on every check
Only deletes, sharing and admin actions need the latest ACLAuth0 FGAHIGHER_CONSISTENCY on those few calls is enough
Small team wanting fast adoption with Auth0 authAuth0 FGAManaged service with native Auth0 integration
Data must stay on your infrastructure, cache bypass is enoughOpenFGA (self-hosted)Same model as Auth0 FGA, no license fee
Data must stay on your infrastructure, many checks need New Enemy orderingSpiceDB (self-hosted)Full control over data residency plus ZedTokens
Large-scale system with Kubernetes infrastructureSpiceDBNatural fit with infrastructure the team already runs
No Okta enterprise contract possibleOpenFGA (self-hosted) or AuthZed CloudAuth0 FGA production use requires that contract

What Not to Do#

  • Do not choose SpiceDB just because it is open-source if your team lacks Kubernetes and database operations expertise. The operational overhead can outweigh the benefits.
  • Do not choose Auth0 FGA assuming consistency tokens work like ZedTokens. The consistency models are meaningfully different. If you need at_least_as_fresh semantics, test Auth0 FGA’s current consistency model against your requirements.
  • Do not leave pricing to the end. Auth0 FGA publishes no production price, and its enterprise plan lists default limits (500 Check requests per second, 10 million tuples). Check both against your load before the PoC verdict.
  • Do not design list screens around one listObjects or lookupResources call per page load without testing it on production-sized data. When a query is slow, result caps and deadlines can return a shortened list.
  • Do not skip the dual-write problem analysis. Both systems require a synchronization strategy. Choosing either platform without a plan for keeping authorization data in sync with application data will lead to production issues.
  • Do not ignore OpenFGA as a middle path. Self-hosting OpenFGA gives you the Auth0 FGA schema language with self-hosted control. If you later need managed infrastructure, migrating to Auth0 FGA is straightforward since the underlying model is the same.

Conclusion#

Auth0 FGA holds as the default while only a few checks need the latest ACL, so HIGHER_CONSISTENCY on those calls is affordable, and your authorization data can live in a vendor’s regions. Override it for SpiceDB when many hot-path checks must never run against an ACL older than the content they guard. A ZedToken stored per resource gives that ordering without a cache bypass on every check; the bypass remains only for folder or group revocations that must show at once on unchanged content. When the data has to stay on your infrastructure, self-host: OpenFGA if the cache bypass is enough, SpiceDB if it is not. The price of the SpiceDB override is either a Kubernetes and database footprint your team operates or an AuthZed contract.

The dual-write problem applies equally to both. Whichever system you choose, plan for how authorization data stays synchronized with application data; the transactional outbox pattern is the most reliable approach for most architectures.

Before committing, model your most complex authorization scenario in both playgrounds (play.authzed.com and play.fga.dev). Schema modeling takes an afternoon and exposes the differences that comparison tables flatten.

References#

External Authorization Systems

Part 3 of 4

A comprehensive guide to external authorization platforms for distributed systems. Covers platform selection, policy language comparison, cloud-native authorization with AWS, and relationship-based access control with SpiceDB and Auth0 FGA.

Related posts