0Pricing
Scala for Backend Engineering & Functional Programming · Lesson

Composing Transactions

Combine effects safely.

Composing Transactions is a free Scala for Backend Engineering & Functional Programming lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Scala for Backend Engineering & Functional Programming learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

ConnectionIO Is a Monad

The real power of Doobie is that ConnectionIO is a monad. You combine many statements into one larger program using flatMap or a for-comprehension.

Everything you sequence this way runs on the same connection inside one transaction.

import doobie.implicits._

val program: ConnectionIO[Long] =
  for {
    id <- insertUser("Ada")
    _  <- insertProfile(id)
  } yield id

One Transaction per transact

No matter how many statements you compose, the whole ConnectionIO becomes a single transaction when you call .transact.

If any step fails, the Transactor's strategy rolls back everything; if all succeed, it commits once at the end.

val io: IO[Long] = program.transact(xa)

Atomic Multi-Statement Writes

Because composed statements share a transaction, you get atomicity for free. A transfer that debits one account and credits another either fully happens or not at all.

There is no partial state if the second update throws.

def transfer(from: Long, to: Long, cents: Int) =
  for {
    _ <- sql"update acct set bal = bal - $cents where id = $from".update.run
    _ <- sql"update acct set bal = bal + $cents where id = $to".update.run
  } yield ()

Raising and Handling Errors

ConnectionIO has a MonadError instance, so you can raiseError to abort a transaction and trigger rollback.

You can also handleErrorWith to recover, but note that recovering does not by itself undo prior statements unless the transaction rolls back.

import cats.syntax.all._
import doobie.free.connection.{raiseError, pure}

def debit(id: Long, c: Int): ConnectionIO[Unit] =
  sql"update acct set bal = bal - $c where id = $id".update.run.flatMap {
    case 1 => pure(())
    case _ => raiseError(new RuntimeException("no such account"))
  }

Conditional Logic in a Transaction

Since it is just a monad, ordinary Scala control flow works. You can read a row, branch on its value, and write accordingly, all atomically.

This keeps business rules and persistence in one consistent unit.

for {
  bal <- sql"select bal from acct where id = $id".query[Int].unique
  _   <- if (bal >= amt)
           sql"update acct set bal = bal - $amt where id = $id".update.run
         else raiseError(new RuntimeException("insufficient funds"))
} yield ()

Savepoints for Partial Rollback

For finer control, Doobie exposes JDBC Savepoints via the FC (free connection) algebra. You can roll back to a savepoint without aborting the entire transaction.

This enables try/fallback patterns inside one outer transaction.

import doobie.free.{connection => FC}

val withSp =
  for {
    sp <- FC.setSavepoint
    _  <- riskyWrite.handleErrorWith(_ => FC.rollback(sp))
  } yield ()

Combining Queries and Writes

Reads and writes mix freely in the same program. You might select current state, compute a change in Scala, and persist it, all on one connection.

The read sees uncommitted changes made earlier in the same transaction.

for {
  v <- sql"select stock from items where id = $id".query[Int].unique
  _ <- sql"update items set stock = ${v - 1} where id = $id".update.run
  n <- sql"select stock from items where id = $id".query[Int].unique
} yield n

Reusing Programs with traverse

Because programs are values, you can run the same one over a list with cats' traverse, sequencing them in a single transaction.

All the inserts commit together, or none do.

import cats.syntax.all._

def saveAll(names: List[String]): ConnectionIO[List[Long]] =
  names.traverse(insertUser)

Isolation Levels

You can set the transaction isolation level inside a program using the connection algebra before doing your work.

Stricter levels like SERIALIZABLE prevent anomalies but may cause the database to abort conflicting transactions, which you should retry.

import doobie.free.{connection => FC}
import java.sql.Connection

val serializable =
  FC.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE) *> program

Retrying on Serialization Failures

Retries belong in the effect layer, not the transaction. After .transact you have an IO, and you can retry the whole transaction on a serialization error.

Each retry is a fresh, independent transaction.

def runWithRetry(io: IO[Unit], n: Int): IO[Unit] =
  io.handleErrorWith {
    case _ if n > 0 => runWithRetry(io, n - 1)
    case e          => IO.raiseError(e)
  }

Keep Transactions Short

Compose only the work that must be atomic into one ConnectionIO. Do not perform external calls (HTTP, slow CPU work) inside a transaction; it holds a connection and locks.

Read, compute outside if possible, then write in a tight transaction.

// good: gather input first, then one short transactional write
val write: ConnectionIO[Int] =
  sql"update users set name = $name where id = $id".update.run

Quick Check

Reason about transaction boundaries.

Recap

ConnectionIO is a monad, so for-comprehensions compose statements into one atomic transaction per .transact. Errors roll back everything; raiseError aborts deliberately.

Use savepoints for partial rollback, set isolation levels in-program, retry serialization failures in the effect layer, and keep transactions short.

Frequently asked questions

Is the “Composing Transactions” lesson free?

Yes — the full text of “Composing Transactions” is free to read here on the web, and the Scala for Backend Engineering & Functional Programming course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Scala for Backend Engineering & Functional Programming course, upgrade to CoddyKit PRO.

What will I learn in “Composing Transactions”?

Combine effects safely. You practise Scala for Backend Engineering & Functional Programming with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Scala for Backend Engineering & Functional Programming?

No prior experience is required. Scala for Backend Engineering & Functional Programming on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Composing Transactions” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Scala for Backend Engineering & Functional Programming lesson?

Yes. Every Scala for Backend Engineering & Functional Programming lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Connecting with a Transactor
  2. Running Queries
  3. Inserts and Updates
  4. Composing Transactions
← Back to Scala for Backend Engineering & Functional Programming