When you need three inserts and two updates to succeed or fail as one unit, Ecto.Multi provides a clear way to compose the operations. It is not merely an anonymous function passed to Repo.transaction/1: each step is named and can depend on previous results.
The Pattern
def register_user(attrs) do
Ecto.Multi.new()
|> Ecto.Multi.insert(:user, User.changeset(%User{}, attrs))
|> Ecto.Multi.insert(:profile, fn %{user: user} ->
Profile.changeset(%Profile{user_id: user.id}, %{})
end)
|> Ecto.Multi.insert(:audit, fn %{user: user} ->
AuditLog.changeset(%{action: "user_registered", user_id: user.id})
end)
|> Repo.transaction()
end
Every step has a name (:user, :profile, :audit). Later steps can access the results of earlier ones through pattern matching on the changes map.
Why Use It Instead of a Transaction Function?
With Repo.transaction(fn -> ... end), you are responsible for explicitly handling errors and rollbacks within your function. With Ecto.Multi, a failure returns a structured result such as {:error, failed_step, failed_value, _changes}, identifying the operation that failed and the associated value.
Example: Registration with a Welcome Email
def register(attrs) do
Ecto.Multi.new()
|> Ecto.Multi.insert(:user, User.changeset(%User{}, attrs))
|> Ecto.Multi.run(:welcome_email, fn _repo, %{user: user} ->
case Mailer.send_welcome(user) do
{:ok, _} -> {:ok, :sent}
{:error, reason} -> {:error, reason}
end
end)
|> Repo.transaction()
end
In this example, if inserting the user fails, the email step is not reached. If sending the email returns an error, the database transaction is rolled back and the user is not persisted. An external email is not itself transactional, however: sending it cannot be undone if a later operation fails or the database commit does not complete. For production workflows, a transactional outbox or a job scheduled after commit is usually safer.
Conclusion
Ecto.Multi turns complex transactional flows into readable, named steps. It is one of the most useful APIs in Elixir for expressing a sequence of database operations and handling failure explicitly.