Ecto.Multi: atomic database operations in Elixir transactions
Ecto.Multi bundles multiple database operations into one atomic transaction, but its error tuple and trade-offs require careful handling to avoid partial state persisting.
04 Apr 2026, 22:10 UTC

When you need to create or update several database records at once and want them to succeed or fail together, Ecto.Multi is the idiomatic Elixir solution. It bundles individual operations into a single Repo.transaction/2 call, guaranteeing that either every step commits or none do. The useful takeaway: always pattern-match the error tuple returned on failure so you can inspect which step broke and what already succeeded.
How Ecto.Multi bundles operations
Ecto.Multi represents a sequence of database operations as tagged tuples. A typical insert looks like {:insert, :users, changeset}. You can also :update, :delete, or run custom functions with {:run, fn ... end}. Multiple operations are collected into an Ecto.Multi struct and passed to Repo.transaction/2. Inside the transaction, Ecto executes each operation in order using the underlying database connection. If any operation's changeset is invalid or the custom function raises, the entire transaction is aborted and the database rolls back to its pre-Multi state. A changeset is Ecto's validation and casting pipeline that ensures data conforms to schema constraints before it hits the database. Ecto.Multi is part of Ecto 3.x and 4.x, the standard persistence library for Elixir and Phoenix applications.
Worked example – creating a user and a profile, with a deliberate failure
Suppose we have two schemas: User and Profile. We want to insert both atomically, but we'll intentionally make the profile changeset invalid so the whole thing rolls back.
multi = Ecto.Multi.new()
|> Ecto.Multi.insert(:user, user_changeset)
|> Ecto.Multi.insert(:profile, profile_changeset)
case Repo.transaction(multi) do
{:ok, changes} ->
IO.puts('Transaction committed')
{:error, failed_op, failed_value, changes_so_far} ->
IO.inspect failed_op
IO.inspect changes_so_far
end
Run this in a Phoenix project with a connected Postgres database. Because the profile changeset is invalid (type mismatch), Repo.transaction/2 returns {:error, :insert, ...} and neither the user nor the profile row will be visible in the database after the call exits. To verify, open iex -S mix (or run mix run), execute the snippet, then query the tables: SELECT count(*) FROM users; and SELECT count(*) FROM profiles;. Both should return 0. If you swap the profile changeset for a valid one, both rows appear. This concrete pattern lets you see atomicity in action without writing custom rollback logic. To confirm the rollback behavior locally, set up a Postgres instance via Docker: docker run --name elixir-postgres -e POSTGRES_PASSWORD=pass -e POSTGRES_DB=elixir -p 5432:5432 -d postgres:15. In your Elixir project, create the users and profiles tables via migrations, then run the example snippet above. After the transaction returns an error, connect with psql -U postgres -d elixir and run SELECT * FROM users; and SELECT * FROM profiles;. Empty result sets confirm that no partial state persisted. If you see rows, the transaction either didn't wrap those operations or an external commit occurred outside the Repo.transaction/2 call. When you're ready, integrate the pattern into your feature branch, observe the error tuple in CI logs, and iterate the retry logic as needed.
Trade-offs, limitations, and practical mitigation
- No automatic retry – If the database returns a transient error (e.g., a brief lock timeout), Repo.transaction/2 returns {:error, ...} without retrying. Wrap the call in retry logic such as Enum.reduce_while with backoff, or use a library like retryable.
- External side effects – Placing email sends, HTTP calls, or file writes inside a Multi is risky because a failure aborts the transaction, but those external actions have already happened (or not) outside the database's control. If you need them part of the atomic unit, design compensating transactions or use a message queue instead.
- Lock contention – Large or long-running Multi transactions hold database locks for the entire duration. Under high concurrent write load, this can increase wait times or deadlocks. Keep transactions minimal: only include the operations strictly needed for the atomic unit, and consider batching or sagas for complex workflows.
Ecto.Multi gives Elixir developers a straightforward way to bundle database operations into a single atomic transaction. The key to using it confidently is understanding its error semantics—pattern-match the returned tuple to learn what failed and what already committed—and respecting its boundaries: no implicit retries, no hidden side effects, and keep transactions scoped to minimize lock pressure. Try the worked example in a local project, observe the error tuple, and add retry logic if your workload involves flaky connections. From there, you'll have a reliable building block for atomic data operations in any Elixir or Phoenix application.
0 replies
A thoughtful contribution can make all the difference. Be the first to share one.