Transactions

Learn how to group reads and writes into one mergeable or serializable transaction.

A transaction groups related writes under one commit. Reads made through the transaction can see its staged writes, while code outside the transaction cannot see them until it commits.

The server checks a transaction's writes against what the transaction itself wrote. See Know when permissions are checked.

Jazz has two transaction types. The difference is how they handle concurrent changes:

  • A mergeable transaction commits locally, even when the device is offline. When it syncs, Jazz combines it with concurrent work using the normal conflict rules. Jazz does not reject it just because another client changed the same data.
  • A serializable transaction uses a stable view of the data. Before accepting it, the authority checks whether another write made a conflicting change. If so, it rejects the whole transaction and Jazz removes its local changes. Use this when accepting both changes would break a rule.

Most applications should start with a mergeable transaction.

The authority is the part of Jazz that accepts or rejects writes. It checks permissions and other rules before accepting them. For a serializable transaction, it also checks that the data read by the transaction has not changed in a conflicting way.

For most apps, the authority is the server at the global durability tier. This is why a serializable transaction cannot be accepted while the device is offline. For an app without a sync server, the authority runs locally instead.

Choose a transaction type

UseMergeable transactionSerializable transaction
Best forGrouping normal local-first writesEnforcing an invariant across reads and writes
Concurrent workMerges using Jazz's normal conflict rulesThe authority validates the transaction as one serialisable unit
TypeScript callbackdb.transaction(...)db.serializableTransaction(...)
Godb.Tx(ctx, fn)db.Tx(ctx, fn, jazz.Serializable())
TypeScript waitwait({ tier: "local" | "global" })wait()
OfflineCan commit locally and sync laterCan be staged, but cannot be accepted until the authority is reachable

You do not need a transaction for every write. insert, update, upsert, delete and restore already apply locally first and sync in the background.

One commit does not mean one UI update

Jazz sends every transaction upstream as one unit, and the authority decides that unit as a whole. Other clients can still receive rows from a mergeable transaction in separate updates. An serializable transaction is shown atomically within each subscription view.

Use a callback for normal work

The callback form commits automatically when the callback finishes. Jazz rolls the transaction back if the callback throws or returns a rejected promise.

A mergeable callback that writes nothing, such as a cleanup that finds nothing to delete, commits nothing and doesn't fail: db.transaction(...) resolves with the callback's value, its wait() resolves at once, and its txId rejects, since there is no transaction to name (from alpha.65; earlier versions throw "empty mergeable transaction has no committed unit").

app.ts
export async function groupTodoWrites(db: Db, existingTodoId: string) {
const result = await db.transaction(async (tx) => {
const created = tx.insert(app.todos, {
title: "Write transaction docs",
done: false,
owner_id: EXAMPLE_OWNER_ID,
projectId: EXAMPLE_PROJECT_ID,
});
​
tx.update(app.todos, existingTodoId, { done: true });
​
const staged = await tx.one(app.todos.where({ id: created.id }));
if (!staged) throw new Error("Staged todo not found");
​
return staged.id;
});
​
await result.wait({ tier: "global" });
return result.value;
}

The TypeScript callback returns the new row ID. Jazz exposes that value as result.value, and result.wait(...) resolves to the same value.

Inside a TypeScript transaction:

MethodReturns
insert(...), restore(...)The staged row
update(...), upsert(...), delete(...)void
all(...)A promise for all matching rows, including staged changes
one(...)A promise for the first matching row, or null

To point one new row at another in the same transaction, use the staged row's id:

const project = tx.insert(app.projects, { name: "Launch" });
tx.insert(app.todos, { title: "Write the post", projectId: project.id });

insert assigns the id itself: an id in the values fails with "Unknown column id".

Use the tx object for every read and write that belongs to the transaction. A query made through the outer db does not read the transaction's staged changes.

Know what each await means

In TypeScript, committing and waiting for durability are separate steps:

CodeWhat it proves
await db.transaction(...)The callback finished and Jazz created the committed mergeable transaction locally
result.valueThe value returned by the callback
await result.txIdThe committed transaction has an ID
await result.wait({ tier })The mergeable transaction reached that durability tier, or was rejected
await db.serializableTransaction(...)Jazz created the committed serializable transaction locally
await result.wait()The authority accepted the serializable transaction, or rejected it

If your next action depends on server acceptance, keep the result and call wait(...). Awaiting db.transaction(...) by itself is not enough.

See Durability Tiers for the meaning of local and global.

Handle errors

A transaction can fail at three points:

  1. While the callback runs, a write can throw immediately or an awaited read can reject, for example because its input is invalid. An update inside a transaction needs its row read first in this process (with tx.one(...), say); otherwise it throws a not_observed error.
  2. The callback or local commit can fail. Jazz rolls back a callback transaction and rejects db.transaction(...) or db.serializableTransaction(...).
  3. The authority can reject a committed transaction later. In TypeScript, wait(...) then rejects with PersistedWriteRejectedError and Jazz removes the rejected local changes.
app.ts
export async function completeTodoInTransaction(db: Db, todoId: string) {
try {
const result = await db.transaction((tx) => {
tx.update(app.todos, todoId, { done: true });
});
​
await result.wait({ tier: "global" });
} catch (error) {
if (error instanceof PersistedWriteRejectedError) {
console.error(error.code, error.reason);
return;
}
​
throw error;
}
}

Use db.onMutationError(...) as a fallback for later rejections when your code does not keep and wait on the transaction result.

Know when permissions are checked

Permissions are enforced by the server (the authority). For a transaction committed by a local-first client or a backend, it doesn't check the writes one by one as you made them: it checks them all when the committed transaction reaches it. If any write isn't allowed, the whole transaction is rejected, not just that write, and wait(...) rejects as described in Handle errors.

Each write is checked against the state the transaction leaves behind:

  • A policy's exists sees the rows the transaction inserts or updates, so a row and the rows that grant access to it can be written in one transaction.
  • A row the transaction deletes is still seen as it was before the transaction, so a transaction can use a row as evidence and delete it, such as admitting a member and removing their join request.
  • Writes from other transactions don't count until the server has accepted them.
  • The order of the writes inside the transaction doesn't matter, for a local-first client, a thin client connected through your backend, or a backend.

For example:

  • A task inserted with the show it needs. If a task's insert policy requires its show to exist, a client or a backend can create the show and the task in one transaction, in either order. Checked alone, the task insert would be refused, because the show doesn't exist yet; checked with the rest of the transaction, it's allowed. The show insert itself still has to be allowed by its own policy: rows a transaction writes can't grant each other access in a cycle.
  • Demoting yourself while making an admin-only write. If documents may only be created by an admin, a transaction that creates a document and changes your own membership from admin to member is rejected, even if the document insert comes first. In the state the transaction leaves behind, you're no longer an admin.

A thin client (jazz-tools/thin) that connects through your app's backend (createJazz) runs its transactions there: the backend stages the writes as you make them and sends the finished transaction to the server when you commit, so the server checks it as a whole, as above. (A thin client connected straight to the server has each write checked as it's staged, in order.) Two things differ from a local-first client:

  • A staged write the backend refuses outright, such as one with invalid values or an update of a row that doesn't exist, fails at once, and so does the whole transaction: committing it anyway fails with that refusal, and nothing of it is written.
  • If the server doesn't confirm a commit within 30 seconds, the commit fails with ThinCommitOutcomeUnknownError (code commit_outcome_unknown). The transaction may have been applied, or may still be: don't run it again as if it failed. Read the rows it wrote to find out.

A thin client's open transactions end with its connection, as before: a commit after a reconnect fails with ThinTransactionLostError, and nothing of the transaction is written.

To check whether an action is allowed before or between steps, for example to show or hide a button, use db.canInsert(), db.canUpdate(), db.canDelete() or db.canRead() (see Check permissions before an action). They ask the server about its committed data, not about writes a transaction has staged, and answer "unknown" when the server can't be reached. They're advice: the server's check of the transaction itself is final.

Use a serializable transaction to reject conflicts

A serializable transaction reads from a stable transaction snapshot. The authority checks the reads and writes, then accepts or rejects the transaction as one serialisable unit. This is useful when a write is valid only if the data you just read has not changed in a conflicting transaction.

app.ts
export async function finishTodoSerializably(db: Db, todoId: string) {
const result = await db.serializableTransaction(async (tx) => {
const todo = await tx.one(app.todos.where({ id: todoId }));
if (!todo) throw new Error("Todo not found");
​
tx.update(app.todos, todo.id, { done: true });
return todo.id;
});
​
return result.wait();
}

In TypeScript, wait() takes no durability tier for a serializable transaction. It resolves if the authority accepts the transaction and rejects if the authority rejects it.

Keep transactions small. Their cost grows faster than their size for now, so split a bulk import into transactions of 10 to 50 rows.

A conflict rejects with code serialization_conflict or transaction_conflict; treat both as "read again and retry". A rejection is different from a transport error, such as "websocket transport error" during an outage: there the transaction may still reach the authority, so check before you retry it.

Manage a transaction yourself only when needed

Use beginTransaction() when the work cannot fit in one callback. You then own the transaction and must call commit() or rollback().

app.ts
export async function stageTodoAcrossSteps(db: Db, shouldCancel: boolean) {
const tx = db.beginTransaction();
​
tx.insert(app.todos, {
title: "Review staged changes",
done: false,
owner_id: EXAMPLE_OWNER_ID,
projectId: EXAMPLE_PROJECT_ID,
});
​
if (shouldCancel) {
await tx.rollback();
return;
}
​
const result = await tx.commit();
await result.wait({ tier: "global" });
}

For a serializable transaction, use beginSerializableTransaction() instead. Call wait() on the commit result to wait for the authority to accept or reject the transaction. You do not choose a durability tier, it is always settled by the authority.

If a mergeable transaction you manage yourself has no writes, commit() throws. Call rollback() instead. (The callback form handles that case for you, as above.)

Await every read you start through a transaction before you commit it. Committing while one of its reads is still pending throws a not_observed error, and the transaction ends without publishing anything.