Ecto.Multi: Why Your Transaction Should Be a Data Structure, Not a Callback Nest
Ecto.Multi turns database transactions into composable data structures, giving you atomic operations with automatic rollback and structured errors—but it only works on a single Repo and forbids side effects inside the transaction.
25 Oct 2026, 13:40 UTC

The atomicity trap in user registration
Your user registration flow needs to insert a user row, create a profile, and assign a role—all or nothing. When you write this with Repo.transaction/1, you end up with nested callbacks, manual error threading, and a rollback function that must be called in exactly the right places. Miss one path and you leave orphaned data. The logic spreads across lines, and adding a new step means touching every branch.
Ecto.Multi (Ecto 3.x+) flips this around. Instead of executing operations immediately, you build a data structure describing what should happen. When you pass that structure to Repo.transaction/1, Ecto runs everything in a single database transaction, rolls back automatically on any failure, and returns a structured error that tells you exactly which step failed and with what value.
Declarative steps with automatic rollback
Each operation is added with Multi.insert/3, Multi.update/3, Multi.delete/3, or Multi.run/3 for custom logic. Later steps receive a map of results from earlier steps by key.
alias MyApp.{Repo, Accounts, Profiles}
def register_user(params) do
Multi.new()
|> Multi.insert(:user, Accounts.changeset(%Accounts.User{}, params))
|> Multi.run(:profile, fn %{user: user} ->
Profiles.create_for(user)
end)
|> Multi.run(:role, fn %{user: user} ->
{:ok, Accounts.assign_default_role(user)}
end)
|> Repo.transaction()
end
If Profiles.create_for/1 returns {:error, changeset}, the entire transaction rolls back. No user, no profile, no role. The return value is {:error, :profile, changeset, %{user: user_struct}}, pinpointing the failure.
Merging transactions across contexts
Real applications split logic into bounded contexts. Multi.merge/2 lets each context return a Multi struct that a caller stitches together—still one transaction.
# accounts_context.ex
def register_user_multi(params) do
Multi.new()
|> Multi.insert(:user, changeset(%User{}, params))
end
# billing_context.ex
def add_trial_multi(%{user: user}) do
Multi.new()
|> Multi.insert(:subscription, Subscription.trial_changeset(user))
|> Multi.run(:invoice, fn %{subscription: sub} ->
Invoice.generate_for(sub)
end)
end
# caller.ex
Multi.new()
|> Multi.merge(Accounts.register_user_multi(params))
|> Multi.merge(Billing.add_trial_multi)
|> Repo.transaction()
Operations execute in merge order. The billing steps see %{user: user} from the accounts step. Each context only needs to agree on the keys it produces and consumes.
Limitations that shape your design
- Single Repo only.
Multiuses one database connection. Cross-database atomicity requires saga patterns or manual coordination—Multicannot span databases. - No side effects in
runsteps. Sending emails or making HTTP calls inside arunfunction executes even if the transaction rolls back. UseObov,Broadway, or a post-commit callback afterRepo.transaction/1returns{:ok, _}. - Connection holding. Long chains hold a pool checkout and row locks. Under load, a 20-step
Multican starve the pool. Consider batching or splitting large workflows. - Valid changesets only. Passing an invalid changeset to
insertorupdatefails immediately with the changeset errors. - No nested transactions. Calling
Repo.transactioninside aMulti.runstarts an independent transaction that commits separately.
Verify atomicity before you ship
- Test the structured error tuple:
test "fails on invalid second insert" do assert {:error, :u2, _changeset, %{u: _user}} = Multi.new() |> Multi.insert(:u, User.changeset(%User{}, %{name: "A"})) |> Multi.insert(:u2, User.changeset(%User{}, %{name: nil})) |> Repo.transaction() end - Inspect generated SQL with
Repo.to_sql(:all, multi)—confirm a singleBEGIN/COMMITblock. - After a failed
Multi, query the tables directly: no partial rows should exist. - Benchmark: run 100 concurrent
Multitransactions (5 ops each) and watch pool checkout time.
When to reach for Multi
Use Ecto.Multi when you have 2–10 related Repo operations that must succeed or fail together on a single database. It gives readable composition, automatic rollback, and error tuples that pinpoint the failure. For cross-database workflows, long-running batches, or steps that trigger external side effects, design a saga with compensating actions instead.
0 replies
A thoughtful contribution can make all the difference. Be the first to share one.