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
| Use | Mergeable transaction | Serializable transaction |
|---|---|---|
| Best for | Grouping normal local-first writes | Enforcing an invariant across reads and writes |
| Concurrent work | Merges using Jazz's normal conflict rules | The authority validates the transaction as one serialisable unit |
| TypeScript callback | db.transaction(...) | db.serializableTransaction(...) |
| Go | db.Tx(ctx, fn) | db.Tx(ctx, fn, jazz.Serializable()) |
| TypeScript wait | wait({ tier: "local" | "global" }) | wait() |
| Offline | Can commit locally and sync later | Can 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.
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.tsexport 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;}
app.tsexport const groupTodoWrites = Effect.fn("groupTodoWrites")(function* (existingTodoId: string) {const jazz = yield* Jazz;// Commits when the inner Effect succeeds; rolls back if it fails, dies or is interrupted.return yield* jazz.transaction((tx) =>Effect.gen(function* () {const created = yield* tx.insert(app.todos, {title: "Write transaction docs",done: false,owner_id: EXAMPLE_OWNER_ID,projectId: EXAMPLE_PROJECT_ID,});yield* tx.update(app.todos, existingTodoId, { done: true });const staged = yield* tx.one(app.todos.where({ id: created.id }));if (Option.isNone(staged)) return yield* new TodoNotFound({ id: created.id });return staged.value.id;}),{ wait: "global" },);});
pub async fn group_todo_writes(jazz: &Jazz,existing_todo_id: ObjectId,) -> jazz_app::Result<ObjectId> {// Committed together if the closure returns `Ok`, rolled back if it// returns `Err`. On a durable handle it returns once the commit reached// that tier.jazz.durable(DurabilityTier::GlobalServer).transaction(move |tx| async move {let created = tx.insert(NewTodo {owner_id: Some(ObjectId::from_uuid(EXAMPLE_OWNER_ID)),project_id: Some(ObjectId::from_uuid(EXAMPLE_PROJECT_ID)),..NewTodo::new("Write transaction docs", false)})?;tx.update(existing_todo_id,TodoUpdate {done: Some(true),..Default::default()},)?;// Reads inside the transaction see its staged writes.let staged = tx.get::<Todo>(created.id).await?.ok_or(jazz_app::Error::NotFound {table: "todos",id: created.id.to_string(),})?;Ok(staged.id)}).await}
public func groupTodoWrites(_ jazz: Jazz.Client, existingTodoId: Jazz.ID) async throws -> Jazz.ID {// Commits when the closure returns, waiting for `.global`; rolls back// when it throws.try await jazz.transaction(commit: .global) { tx inlet created = try await tx.insert(JazzApp.NewTodo(title: "Write transaction docs", done: false, ownerId: exampleOwnerId,projectId: exampleProjectId))try await tx.update(existingTodoId, JazzApp.TodoPatch(done: .set(true)))// Reads inside see the transaction's own writes.guard let staged = try await tx.one(JazzApp.todos.query().where(JazzApp.todos.id.eq(created.id)))else { throw TodoNotFound(id: created.id) }return staged.id}}
// The block's reads see its own writes. The transaction commits when the block// returns (here: once the sync server accepted it) and rolls back if it throws.suspend fun groupTodoWrites(jazz: Jazz, existingTodoId: String): String =jazz.transaction(tier = WriteTier.Global) { tx ->val created = tx.insert(Todos,NewTodo(title = "Write transaction docs", done = false, owner_id = EXAMPLE_OWNER_ID, projectId = EXAMPLE_PROJECT_ID),)tx.update(Todos, existingTodoId) { done(true) }val staged = tx.one(Todos.where(Todos.id eq created.id)) ?: error("Staged todo not found")staged.id}
func GroupTodoWrites(ctx context.Context, db *jazz.DB, existingTodoID, ownerID, projectID string) (string, error) {var createdID string// Commits when the function returns nil; an error or a panic rolls every// write back. CommitAt waits until the server has the transaction.err := db.Tx(ctx, func(tx *jazz.Tx) error {created, err := jazzapp.Todos.Insert(ctx, tx, jazzapp.NewTodo{Title: "Write transaction docs",Done: false,OwnerID: &ownerID,ProjectID: &projectID,})if err != nil {return err}if err := jazzapp.Todos.Update(ctx, tx, existingTodoID, jazzapp.TodoPatch{Done: jazz.Set(true)}); err != nil {return err}staged, err := jazzapp.Todos.Query().Where(jazzapp.Todos.ID.Eq(created.ID)).One(ctx, tx)if err != nil {return err}if staged == nil {return errors.New("staged todo not found")}createdID = staged.IDreturn nil}, jazz.CommitAt(jazz.WriteGlobal))return createdID, err}
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:
| Method | Returns |
|---|---|
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:
| Code | What it proves |
|---|---|
await db.transaction(...) | The callback finished and Jazz created the committed mergeable transaction locally |
result.value | The value returned by the callback |
await result.txId | The 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:
- 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 anot_observederror. - The callback or local commit can fail. Jazz rolls back a callback transaction and rejects
db.transaction(...)ordb.serializableTransaction(...). - The authority can reject a committed transaction later. In TypeScript,
wait(...)then rejects withPersistedWriteRejectedErrorand Jazz removes the rejected local changes.
app.tsexport 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;}}
app.tsexport const completeTodoInTransaction = Effect.fn("completeTodoInTransaction")(function* (todoId: string,) {const jazz = yield* Jazz;yield* jazz.transaction((tx) => tx.update(app.todos, todoId, { done: true }), { wait: "global" }).pipe(Effect.catchTag("JazzWriteRejected", (rejected) =>Effect.logError(rejected.code, rejected.reason),),);});
/// Whether the server accepted the commit.pub async fn complete_todo_in_transaction(jazz: &Jazz,todo_id: ObjectId,) -> jazz_app::Result<bool> {let committed = jazz.durable(DurabilityTier::GlobalServer).transaction(move |tx| async move {tx.update(todo_id,TodoUpdate {done: Some(true),..Default::default()},)}).await;match committed {Ok(()) => Ok(true),Err(jazz_app::Error::WriteRejected { code, reason, .. }) => {eprintln!("{code}: {reason}");Ok(false)}Err(error) => Err(error),}}
public func completeTodoInTransaction(_ jazz: Jazz.Client, todoId: Jazz.ID) async throws {do {try await jazz.transaction(commit: .global) { tx intry await tx.update(todoId, JazzApp.TodoPatch(done: .set(true)))}} catch JazzError.permissionDenied(let reason) {// The server rejected the transaction.print("permissionDenied", reason)}}
// At WriteTier.Global the commit waits for the server; if the server rejects// the transaction, nothing of it is applied and the commit throws.// JazzException has no code field: its subtype (Permission or Refused) says// what kind of rejection it is, and its message gives the reason.suspend fun completeTodoInTransaction(jazz: Jazz, todoId: String) {try {jazz.transaction(tier = WriteTier.Global) { tx ->tx.update(Todos, todoId) { done(true) }}} catch (e: JazzException.Permission) {System.err.println("permission denied: ${e.message}")} catch (e: JazzException.Refused) {System.err.println("refused: ${e.message}")}}
func CompleteTodoInTransaction(ctx context.Context, db *jazz.DB, todoID string) error {err := db.Tx(ctx, func(tx *jazz.Tx) error {return jazzapp.Todos.Update(ctx, tx, todoID, jazzapp.TodoPatch{Done: jazz.Set(true)})}, jazz.CommitAt(jazz.WriteGlobal))var rejected *jazz.Errorif errors.As(err, &rejected) {return fmt.Errorf("rejected (%s): %s", rejected.Kind, rejected.Message)}return err}
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
existssees 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(codecommit_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.tsexport 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();}
app.tsexport const finishTodoSerializably = Effect.fn("finishTodoSerializably")(function* (todoId: string,) {const jazz = yield* Jazz;// Waits for the authority's verdict. A conflict fails with JazzWriteRejected,// so the whole transaction can simply be retried.return yield* jazz.serializableTransaction((tx) =>Effect.gen(function* () {const todo = yield* tx.one(app.todos.where({ id: todoId }));if (Option.isNone(todo)) return yield* new TodoNotFound({ id: todoId });yield* tx.update(app.todos, todo.value.id, { done: true });return todo.value.id;}),).pipe(Effect.retry({while: (error) => error._tag === "JazzWriteRejected",schedule: Schedule.recurs(3),}),);});
pub async fn finish_todo_serializably(jazz: &Jazz,todo_id: ObjectId,) -> jazz_app::Result<ObjectId> {// Reads see the data as of the transaction's start; the server applies// the commit only if nothing it read or wrote changed meanwhile, and// refuses it otherwise.jazz.serializable_transaction(move |tx| async move {let todo = tx.get::<Todo>(todo_id).await?.ok_or(jazz_app::Error::NotFound {table: "todos",id: todo_id.to_string(),})?;tx.update(todo.id,TodoUpdate {done: Some(true),..Default::default()},)?;Ok(todo.id)}).await}
public func finishTodoSerializably(_ jazz: Jazz.Client, todoId: Jazz.ID) async throws -> Jazz.ID {// The server accepts it only if nothing it read changed meanwhile: a// `JazzError.conflict` means another write won, and retrying may succeed.try await jazz.serializableTransaction { tx inguard let todo = try await tx.one(JazzApp.todos.query().where(JazzApp.todos.id.eq(todoId)))else { throw TodoNotFound(id: todoId) }try await tx.update(todo.id, JazzApp.TodoPatch(done: .set(true)))return todo.id}}
// The server accepts it only if what it read hasn't changed concurrently;// otherwise the commit throws JazzException.Conflict and nothing is applied.suspend fun finishTodoSerializably(jazz: Jazz, todoId: String): String =jazz.transaction(tier = WriteTier.Global, serializable = true) { tx ->val todo = tx.one(Todos.where(Todos.id eq todoId)) ?: error("Todo not found")tx.update(Todos, todo.id) { done(true) }todo.id}
func FinishTodoSerializably(ctx context.Context, db *jazz.DB, todoID string) (string, error) {var finishedID string// Serializable: if the todo changed after it was read here, the commit// fails with jazz.ErrConflict.err := db.Tx(ctx, func(tx *jazz.Tx) error {todo, err := jazzapp.Todos.Query().Where(jazzapp.Todos.ID.Eq(todoID)).One(ctx, tx)if err != nil {return err}if todo == nil {return errors.New("todo not found")}finishedID = todo.IDreturn jazzapp.Todos.Update(ctx, tx, todo.ID, jazzapp.TodoPatch{Done: jazz.Set(true)})}, jazz.Serializable())return finishedID, err}
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.tsexport 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" });}
pub async fn stage_todo_across_steps(jazz: &Jazz, should_cancel: bool) -> jazz_app::Result<()> {// On a durable handle, `commit` returns once the commit reached that tier.let tx = jazz.durable(DurabilityTier::GlobalServer).begin_transaction().await?;tx.insert(NewTodo {owner_id: Some(ObjectId::from_uuid(EXAMPLE_OWNER_ID)),project_id: Some(ObjectId::from_uuid(EXAMPLE_PROJECT_ID)),..NewTodo::new("Review staged changes", false)}).await?;if should_cancel {return tx.rollback().await;}tx.commit().await}
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.