RolebookDocs

PostgreSQL fences and transactions

Eligibility, email-recipient, workspace-role, team, and policy fences, and SERIALIZABLE retries.

The identity adapter’s answer is a preflight. Fences make it hold until the mutation commits: each runs inside the mutation’s SERIALIZABLE transaction, takes FOR SHARE locks on the authoritative rows, and rechecks them, so a concurrent removal either commits first (and the mutation fails) or waits for the already-authorized mutation. A fence result counts only when it is literally true.

The authoritative identity rows must live in the same database as the sharing tables. A remote provider (Clerk, WorkOS) cannot be locked by this transaction: maintain a database-local projection of its memberships whose lifecycle you coordinate with removals, and point the fences at that projection.

Membership eligibility

import { createPostgresMembershipEligibilityFence } from "@rolebook/sharing-postgres";

const lockEligibleSubjects = createPostgresMembershipEligibilityFence({
  table: ["auth", "member"],
  tenantColumn: "organization_id",
  subjectIdColumn: "user_id",
  subjectType: "user", // optional
});

Required on every adapter. It locks each required subject’s member row in the tenant and checks that the row names exactly the requested tenant and subject. It also receives ownerCandidates (the owner on initialization, a transfer’s recipient, a move’s retained owner); the team-aware fence refuses a team there.

Email invitation recipients

import { createPostgresEmailInvitationRecipientFence } from "@rolebook/sharing-postgres";

const lockInvitationRecipient = createPostgresEmailInvitationRecipientFence({
  membershipTable: ["auth", "member"],
  membershipTenantColumn: "organization_id",
  membershipSubjectIdColumn: "user_id",
  userTable: ["auth", "user"],
  userIdColumn: "id",
  userEmailColumn: "email",
  userEmailVerifiedColumn: "email_verified",
  emailNormalization: "lower_trim", // default; "exact" only for a pre-normalized column
});

Email-bound acceptance locks the membership row and the user’s email and verification row in the consuming transaction and requires a verified address equal to the invitation’s. Without this fence, email invitations fail closed. A remote identity API cannot be made atomic with the transaction, so with a remote provider issue subject-bound invitations instead.

Mapped workspace roles

When your identity adapter maps provider workspace roles to Rolebook assignments, each mutation carries an authorization fact with the member ID and role. Configure a fence that locks and compares it:

import { BETTER_AUTH_WORKSPACE_MEMBER_AUTHORIZATION_FACT } from "@rolebook/sharing-better-auth";
import { createPostgresWorkspaceRoleAuthorizationFactFence } from "@rolebook/sharing-postgres";

const revalidateAuthorizationFacts = createPostgresWorkspaceRoleAuthorizationFactFence({
  table: ["auth", "member"],
  tenantColumn: "organization_id",
  subjectIdColumn: "user_id",
  factType: BETTER_AUTH_WORKSPACE_MEMBER_AUTHORIZATION_FACT, // the identity adapter's fact type
  memberIdColumn: "id",
  roleColumn: "role",
});

Member-row existence alone does not make a mapped allow current: the fence compares the exact tenant, subject, membership ID, and role. A mutation that carries facts while no revalidateAuthorizationFacts is configured fails closed (identity_ineligible, reported as NOT_TENANT_MEMBER), and the adapter logs once which fact types were unfenced.

revalidateAuthorizationFacts runs after the eligibility fence and decides the mutation: true proceeds; "conflict" means facts changed in a way that needs a fresh authorization (the adapter rolls back, returns conflict, and the module re-resolves and retries); anything else is identity_ineligible. Lifecycle methods do not call it.

Exact text comparison

Every shipped fence matches identity rows in SQL and then compares the matched columns, read back as text, with the requested values in JavaScript, exactly. SQL = follows the column’s type and collation: a citext column, a case-insensitive collation, or a uuid or integer column would also match another spelling, so a membership reassigned from bob to a distinct BOB could otherwise satisfy a fence for bob. A row with another spelling, a second matching row, a NULL, or a non-string value fails closed, so identity columns must hold the canonical spelling your identity adapter reports.

Teams

With teams, use createPostgresTeamFences() from @rolebook/teams/sql for both lockEligibleSubjects and revalidateAuthorizationFacts. It wraps your membership fences, locks team and team-member rows, refuses a team as an owner candidate, and returns "conflict" when the actor’s team set changed since preflight. Keep groupSubjectTypes equal to the teamType you give withTeams().

Policy fence

For versioned sharing, store policy versions in the same database and fence every adapter:

import {
  createPostgresPolicyFence,
  createPostgresPolicyStore,
  createPostgresSharingAdapter,
  type ParameterizedSqlExecutor,
  type PostgresEligibilityFence,
  type PostgresResourceDescriptor,
} from "@rolebook/sharing-postgres";

declare const executor: ParameterizedSqlExecutor;
declare const projectTable: PostgresResourceDescriptor;
declare const lockEligibleSubjects: PostgresEligibilityFence;

const policyStore = createPostgresPolicyStore({ executor, schema: "app", tablePrefix: "rolebook" });
const projectAdapter = createPostgresSharingAdapter({
  executor,
  resource: projectTable,
  lockEligibleSubjects,
  fencePolicy: createPostgresPolicyFence({ schema: "app", tablePrefix: "rolebook" }),
});
// projectAdapter.policyFence === "enforced"

The fence runs inside the mutation transaction, after the resource-revision compare and before the sharing write, through that transaction’s executor only. The store and every fence must use the same schema and tablePrefix; protected writes and authorized queries refuse a fence without an explicit schema. A fenced adapter rejects an applyMutation without expectedPolicy. PolicyStoreRowError reports a store row that does not decode; isPolicyStoreRowError from @rolebook/sharing recognizes it.

SERIALIZABLE retries

Serialization failures and deadlocks (40001, 40P01, also when wrapped as an error’s cause) retry only the idempotent unit of work. serializableRetry on the adapter (and the same options on the helpers below) sets attempts (default 3, including the first) and pauses with the same capped, fully jittered backoff the sharing module uses: 0 to min(50, 5 x 2^(retry - 1)) ms before each retry. backoffMs(retry) must return 0 to 1,000 ms; wait(ms) replaces the timer.

HelperUse
withSerializableRetry(executor, operation, options?)Run an idempotent unit of work in a retried SERIALIZABLE transaction.
withSerializableTransaction(executor, operation, options?)Run caller-owned application and sharing work in one retried SERIALIZABLE transaction.
isRetryableSerializationError(error)Whether an error (or its cause chain) is a retryable serialization or deadlock failure.
asSerializablePostgresTransaction(transaction)Compile-time assertion that an ORM transaction you opened is SERIALIZABLE.

Retries replay the whole unit of work, so callbacks must not perform non-transactional side effects.