Compose Scala service workflows with EitherT and OptionT. Handle optional lookups, typed errors, cache fallback, and effect failures, with a brief guide to other monad transformers.
Compose Scala service workflows with EitherT and OptionT. Handle optional lookups, typed errors, cache fallback, and effect failures, with a brief guide to other monad transformers.
A service method often needs to compose more than one kind of result. A customer lookup returns IO[Option[Customer]]. Input validation returns Either[QuoteError, Int]. Another service already exposes IO[Either[QuoteError, Quote]]. The business workflow is straightforward, but connecting those layers adds branches and repeated matching.
EitherT and OptionT provide a useful way to compose these results. They preserve the meaning of a typed rejection or an absent value while the outer effect handles execution. I use them when several dependent steps share that shape and the composition starts hiding the business sequence.
This fifth article in the Cats, Cats Effect & fs2 series follows Functor in Cats. I will build a read-only quote workflow with EitherT, compose optional lookups with OptionT, and briefly place ReaderT, WriterT, and StateT alongside them.
Suppose an endpoint accepts a customer ID and a requested quantity. It validates the quantity, loads the customer, checks whether the customer is active, obtains a unit price, and calculates a quote.
The workflow has three outcomes worth keeping separate. A quote is a successful domain value. An invalid quantity, missing customer, or inactive customer is an expected domain rejection. A database connection failure is a failed effect. Returning a domain Left and failing an IO express different things.
| Type | Meaning |
|---|---|
Option[Customer] | A customer or expected absence. |
Either[QuoteError, Quote] | A domain rejection or a quote. |
IO[Option[Customer]] | An effect that can produce a customer or absence; the effect may fail separately. |
IO[Either[QuoteError, Quote]] | An effect with an explicit domain result; effect failure remains separate. |
The outer IO describes an effectful computation. Creating a properly suspended IO does not run its described effects. A Cats Effect runtime executes them, and the program can succeed, fail with a Throwable, or be canceled. The Either inside it describes the domain result of a successful effect. An IO that returns Left(CustomerMissing(...)) has completed successfully at the effect level.
This article needs only that small part of the Cats Effect execution model. The full source uses IOApp.Simple to run checks at the application boundary. Resource ownership, blocking clients, and runtime configuration remain separate concerns.
//> using scala "3.3.8"
//> using dep "org.typelevel::cats-core:2.13.0"
//> using dep "org.typelevel::cats-effect:3.6.3"
import cats.data.{EitherT, OptionT}
import cats.effect.{IO, IOApp, Ref}
import cats.syntax.all.*The example pins Scala 3.3.8, Cats Core 2.13.0, and Cats Effect 3.6.3. These are the tested versions, rather than a claim about the newest release. cats.syntax.all.* enables Cats syntax. Ref records dependency calls in the checks; the service functions do not require it.
The quote domain stays small. The quantity policy accepts an integer from 1 to 100. The example pricing dependency supplies a nonnegative integer amount in cents in one assumed currency. BigInt keeps the demonstrated multiplication exact. There is no reservation, payment, or database write here.
final case class Customer(id: Long, active: Boolean)
final case class Quote(customerId: Long, quantity: Int, totalCents: BigInt)
enum QuoteError:
case InvalidQuantity(input: String)
case CustomerMissing(id: Long)
case InactiveCustomer(id: Long)
def parseQuantity(input: String): Either[QuoteError, Int] =
input.toIntOption.filter(n => n >= 1 && n <= 100)
.toRight(QuoteError.InvalidQuantity(input))
type FindCustomer = Long => IO[Option[Customer]]
type UnitPrice = Customer => IO[BigInt]FindCustomer describes an effectful optional lookup. UnitPrice describes an effectful price lookup. If the repository is unavailable, its IO should fail. That is different from returning None because the customer was not found.
def quoteNested(id: Long, rawQuantity: String)(
find: FindCustomer,
unitPrice: UnitPrice
): IO[Either[QuoteError, Quote]] =
parseQuantity(rawQuantity) match
case Left(error) => IO.pure(Left(error))
case Right(quantity) =>
find(id).flatMap {
case None => IO.pure(Left(QuoteError.CustomerMissing(id)))
case Some(customer) if !customer.active =>
IO.pure(Left(QuoteError.InactiveCustomer(id)))
case Some(customer) =>
unitPrice(customer).map { cents =>
Right(Quote(customer.id, quantity, cents * quantity))
}
}This code is valid. An invalid quantity avoids the customer lookup. A missing or inactive customer avoids the price call. However, the method repeatedly connects Either branches with IO sequencing and optional results. Adding another dependent step adds more of the same plumbing.
EitherT[F, E, A] wraps F[Either[E, A]]. It provides operations that account for both the outer computation and the inner Either. Here, F is IO, E is QuoteError, and A is the successful result.
The name monad transformer describes adding a particular sequencing behavior to a compatible outer context. EitherT adds sequencing through Right, with an inner Left skipping the dependent continuation. OptionT adds sequencing through Some, with None skipping the continuation. The outer context still contributes its own behavior.
If an existing method already returns IO[Either[QuoteError, Quote]], the direct constructor wraps that value:
def wrappedQuote(id: Long, rawQuantity: String)(
find: FindCustomer,
unitPrice: UnitPrice
): EitherT[IO, QuoteError, Quote] =
EitherT(quoteNested(id, rawQuantity)(find, unitPrice))Wrapping the existing method does not rewrite its implementation or catch its exceptions. It gives callers the transformer’s composition operations. Calling .value reverses that wrapping and returns the underlying IO[Either[QuoteError, Quote]].
Instead of wrapping the whole plain implementation, I can express its individual steps using EitherT:
def quote(id: Long, rawQuantity: String)(
find: FindCustomer,
unitPrice: UnitPrice
): EitherT[IO, QuoteError, Quote] =
for
quantity <- EitherT.fromEither[IO](parseQuantity(rawQuantity))
customer <- EitherT.fromOptionF(
find(id), QuoteError.CustomerMissing(id)
)
_ <- EitherT.cond[IO](
customer.active, (), QuoteError.InactiveCustomer(id)
)
cents <- EitherT.liftF[IO, QuoteError, BigInt](unitPrice(customer))
yield Quote(customer.id, quantity, cents * quantity)fromEither[IO] lifts the pure quantity check into the chosen effect. fromOptionF turns the effectful lookup’s None into the error supplied by this service. cond[IO] checks whether the customer is active. liftF lifts the price computation, which has no additional typed domain-error result in this example.
The for comprehension uses flatMap to sequence dependent operations and map to construct the final value. The workflow validates the quantity before calling the customer lookup. The price call needs a present, active customer. An earlier Left skips the later dependent calls.
With the example price of 1200 cents, customer 1 and quantity "2" produce Right(Quote(1, 2, 2400)) when the program runs. Quantity "bad" produces Left(InvalidQuantity("bad")) without calling either dependency. A missing customer produces CustomerMissing without asking for a price.
quote(...).value returns an IO program. It does not run that program, synchronously extract a quote, or translate an infrastructure exception into QuoteError. A failed customer or price effect remains a failed IO.
This distinction matters during recovery. A broad attempt followed by a catch-all domain error can collapse a timeout, a decoding defect, and a known business rejection into one result. Translate a recognized external failure at the adapter boundary when it has a meaningful domain interpretation. Keep unrelated failures available to the effect-level error policy.
At an HTTP boundary, unwrap once and map typed errors to the application’s response policy. Handle failed effects separately. EitherT does not assign HTTP status codes, retry a request, or provide transaction rollback. A successful quote also does not guarantee that its price will remain valid for a later purchase.
OptionT[F, A] wraps F[Option[A]]. Use it when absence is an expected result and the caller does not yet need an explanation for it.
For example, a contact lookup first needs a customer and then an optional contact email. If the customer is absent, there is no reason to call the email dependency:
def contactEmail(id: Long)(
find: FindCustomer,
emailFor: Customer => IO[Option[String]]
): IO[Option[String]] =
val result = for
customer <- OptionT(find(id))
email <- OptionT(emailFor(customer))
yield email
result.valueEach generator produces an OptionT[IO, ...]. A present customer feeds the second lookup. A missing customer skips it. A missing email leaves the whole result absent. The final .value exposes IO[Option[String]] when the caller needs the ordinary nested type.
This deliberately treats both kinds of absence alike. If a caller must distinguish “customer missing” from “customer has no contact email,” EitherT with separate error cases is a better fit. OptionT does not retain a reason for None.
A cache-first customer lookup is another useful optional workflow:
def cachedCustomer(id: Long)(
cache: FindCustomer,
repository: FindCustomer
): IO[Option[Customer]] =
OptionT(cache(id))
.orElse(OptionT(IO.defer(repository(id))))
.value
def requiredCustomer(id: Long)(
cache: FindCustomer,
repository: FindCustomer
): EitherT[IO, QuoteError, Customer] =
OptionT(cachedCustomer(id)(cache, repository))
.toRight(QuoteError.CustomerMissing(id))orElse selects the repository alternative when the cache returns None. A cache hit skips it. The fallback argument is by-name; IO.defer also keeps construction of the repository program suspended until that alternative is needed. cachedCustomer returns IO[Option[Customer]] because absence is still a valid lookup outcome.
requiredCustomer makes the service-level decision. toRight turns the absent result into CustomerMissing and returns EitherT[IO, QuoteError, Customer]. One caller can keep the lookup optional while another gives absence an explicit domain meaning. That choice belongs with the use case.
The quote workflow can reuse the same lookup by passing a FindCustomer that delegates to cachedCustomer. There is no need to make the repository itself return a quote-specific error. Conversely, a method already returning EitherT can be composed directly with other EitherT steps using the same outer effect and error type.
A failed cache effect does not trigger orElse. None and an outage are different outcomes. If the application intentionally tolerates a particular cache failure, recover from that recognized failure in the cache adapter. Converting every exception into None also hides failures that should be investigated.
The example selects where to read. It does not populate the cache, establish freshness, prevent a stampede, or make the repository and cache consistent. Those policies need their own implementation.
| Input | Operation |
|---|---|
F[Either[E, A]] | EitherT(existing) |
Either[E, A] | EitherT.fromEither[F](result) |
F[Option[A]] plus an error | EitherT.fromOptionF(optional, error) |
F[A] | EitherT.liftF[F, E, A](effect) |
F[Option[A]] | OptionT(existing) |
Option[A] | OptionT.fromOption[F](optional) |
F[A] | OptionT.liftF[F, A](effect) |
OptionT[F, A] plus an error | optional.toRight(error) |
The direct constructors are useful when the nested type already exists. The other constructors adapt a plain value, an existing domain result, or an effectful result into the workflow. The types make the distinction visible: lifting an IO[A] supplies no new domain rejection or absence branch, although the IO can still fail. Constructors and operations request the appropriate Cats instances for F; the dependent sequencing shown here requires Monad[F], which IO provides.
Keep the error type consistent across an EitherT chain. If separate dependencies use different error models, translate those errors into the service’s error algebra, for example with leftMap. Let each translation explain what the dependency failure means to this use case.
The same composition idea applies to other recurring shapes. I would introduce these when their particular behavior is needed:
| Transformer | Underlying shape | Purpose |
|---|---|---|
ReaderT[F, R, A] (alias for Kleisli[F, R, A]) | R => F[A] | Read a shared environment. |
WriterT[F, L, A] | F[(L, A)] | Carry and combine additional output. |
StateT[F, S, A] | S => F[(S, A)] | Thread state through a calculation. |
ReaderT, represented by Kleisli in Cats, describes a computation that requires an environment before it can produce its effect. Composed steps can share that environment. It can help with dependency passing, but ordinary constructor parameters remain a straightforward choice for many services.
WriterT carries an additional output alongside the result. A suitable combination operation accumulates that output; the standard Monad instance requires Monad[F] and Monoid[L], supplying both sequencing and an empty, combinable output. This can describe diagnostics returned by a computation. It does not automatically write durable logs, and retaining a growing output collection has a memory cost.
StateT threads an explicit state value from one step to the next. It is useful for a stateful calculation that should expose its inputs and outputs. It does not provide shared concurrent mutation or a database transaction merely because the type contains “state.”
These are alternatives for different shapes, not a set of wrappers every service should stack. If a method only maps one optional result, ordinary map may be enough. A transformer becomes useful when its composition behavior removes repeated handling across several steps.
I would keep EitherT and OptionT in the layer where they make the workflow clearer. A repository can expose IO[Option[Customer]]. A service can convert absence into a domain error and compose through EitherT. An endpoint can unwrap to IO[Either[QuoteError, Quote]] before translating the result into a response.
A deeper type such as IO[Either[E, Option[A]]] can be meaningful when rejection and accepted absence are different outcomes. If every None immediately becomes the same error, convert it once and use a simpler service result. The extra layer should represent a real distinction.
Save the expanded source as PracticalCats.scala and run scala run PracticalCats.scala with Scala CLI. It contains the dependency pins, complete fixture data, a fixed price, and checks for successful quotes, rejected inputs, skipped dependent calls, optional lookup composition, cache fallback, and effect failure propagation.
//> using scala "3.3.8"
//> using dep "org.typelevel::cats-core:2.13.0"
//> using dep "org.typelevel::cats-effect:3.6.3"
import cats.data.{EitherT, OptionT}
import cats.effect.{IO, IOApp, Ref}
import cats.syntax.all.*
object PracticalCats extends IOApp.Simple:
final case class Customer(id: Long, active: Boolean)
final case class Quote(customerId: Long, quantity: Int, totalCents: BigInt)
enum QuoteError:
case InvalidQuantity(input: String)
case CustomerMissing(id: Long)
case InactiveCustomer(id: Long)
def parseQuantity(input: String): Either[QuoteError, Int] =
input.toIntOption.filter(n => n >= 1 && n <= 100)
.toRight(QuoteError.InvalidQuantity(input))
type FindCustomer = Long => IO[Option[Customer]]
type UnitPrice = Customer => IO[BigInt]
def quoteNested(id: Long, rawQuantity: String)(
find: FindCustomer,
unitPrice: UnitPrice
): IO[Either[QuoteError, Quote]] =
parseQuantity(rawQuantity) match
case Left(error) => IO.pure(Left(error))
case Right(quantity) =>
find(id).flatMap {
case None => IO.pure(Left(QuoteError.CustomerMissing(id)))
case Some(customer) if !customer.active =>
IO.pure(Left(QuoteError.InactiveCustomer(id)))
case Some(customer) =>
unitPrice(customer).map { cents =>
Right(Quote(customer.id, quantity, cents * quantity))
}
}
def wrappedQuote(id: Long, rawQuantity: String)(
find: FindCustomer,
unitPrice: UnitPrice
): EitherT[IO, QuoteError, Quote] =
EitherT(quoteNested(id, rawQuantity)(find, unitPrice))
def quote(id: Long, rawQuantity: String)(
find: FindCustomer,
unitPrice: UnitPrice
): EitherT[IO, QuoteError, Quote] =
for
quantity <- EitherT.fromEither[IO](parseQuantity(rawQuantity))
customer <- EitherT.fromOptionF(
find(id), QuoteError.CustomerMissing(id)
)
_ <- EitherT.cond[IO](
customer.active, (), QuoteError.InactiveCustomer(id)
)
cents <- EitherT.liftF[IO, QuoteError, BigInt](unitPrice(customer))
yield Quote(customer.id, quantity, cents * quantity)
def contactEmail(id: Long)(
find: FindCustomer,
emailFor: Customer => IO[Option[String]]
): IO[Option[String]] =
val result = for
customer <- OptionT(find(id))
email <- OptionT(emailFor(customer))
yield email
result.value
def cachedCustomer(id: Long)(
cache: FindCustomer,
repository: FindCustomer
): IO[Option[Customer]] =
OptionT(cache(id))
.orElse(OptionT(IO.defer(repository(id))))
.value
def requiredCustomer(id: Long)(
cache: FindCustomer,
repository: FindCustomer
): EitherT[IO, QuoteError, Customer] =
OptionT(cachedCustomer(id)(cache, repository))
.toRight(QuoteError.CustomerMissing(id))
private val customers = Map(
1L -> Customer(1, active = true),
2L -> Customer(2, active = false),
3L -> Customer(3, active = true)
)
private val price: UnitPrice = _ => IO.pure(BigInt(1200))
private val repository: FindCustomer = id => IO.pure(customers.get(id))
private def check(condition: Boolean): IO[Unit] = IO(assert(condition))
private def equivalent(id: Long, quantity: String): IO[Unit] =
for
plain <- quoteNested(id, quantity)(repository, price)
transformed <- quote(id, quantity)(repository, price).value
wrapped <- wrappedQuote(id, quantity)(repository, price).value
_ <- check(plain == transformed && wrapped == plain)
yield ()
def run: IO[Unit] =
for
_ <- check(parseQuantity("2") == Right(2))
_ <- check(List("0", "101", "bad", "2147483648", "").forall(parseQuantity(_).isLeft))
_ <- equivalent(1, "2")
_ <- equivalent(2, "2")
_ <- equivalent(99, "2")
_ <- equivalent(1, "bad")
good <- quote(1, "2")(repository, price).value
_ <- check(good == Right(Quote(1, 2, BigInt(2400))))
calls <- Ref.of[IO, Vector[String]](Vector.empty)
find: FindCustomer = id => calls.update(_ :+ s"find:$id") *> repository(id)
priced: UnitPrice = customer => calls.update(_ :+ s"price:${customer.id}") *> price(customer)
invalid <- quote(1, "bad")(find, priced).value
invalidCalls <- calls.getAndSet(Vector.empty)
_ <- check(invalid == Left(QuoteError.InvalidQuantity("bad")) && invalidCalls.isEmpty)
invalidAttempt <- quote(1, "bad")(find, priced).value.attempt
_ <- check(invalidAttempt == Right(Left(QuoteError.InvalidQuantity("bad"))))
missing <- quote(99, "2")(find, priced).value
missingCalls <- calls.getAndSet(Vector.empty)
_ <- check(missing == Left(QuoteError.CustomerMissing(99)) && missingCalls == Vector("find:99"))
inactive <- quote(2, "2")(find, priced).value
inactiveCalls <- calls.getAndSet(Vector.empty)
_ <- check(inactive == Left(QuoteError.InactiveCustomer(2)) && inactiveCalls == Vector("find:2"))
offline = new RuntimeException("database unavailable")
failed <- quote(1, "2")(_ => IO.raiseError(offline), priced).value.attempt
failedCalls <- calls.getAndSet(Vector.empty)
_ <- check(failed == Left(offline) && failedCalls.isEmpty)
priceFailure <- quote(1, "2")(repository, _ => IO.raiseError(offline)).value.attempt
_ <- check(priceFailure == Left(offline))
emailFor: (Customer => IO[Option[String]]) = customer =>
calls.update(_ :+ s"email:${customer.id}").as(Some("reader@example.com"))
contact <- contactEmail(1)(find, emailFor)
contactCalls <- calls.getAndSet(Vector.empty)
_ <- check(contact.contains("reader@example.com") && contactCalls == Vector("find:1", "email:1"))
missingContact <- contactEmail(99)(find, emailFor)
missingContactCalls <- calls.getAndSet(Vector.empty)
_ <- check(missingContact.isEmpty && missingContactCalls == Vector("find:99"))
missingEmail <- contactEmail(1)(find, customer => calls.update(_ :+ s"email:${customer.id}").as(None))
missingEmailCalls <- calls.getAndSet(Vector.empty)
_ <- check(missingEmail.isEmpty && missingEmailCalls == Vector("find:1", "email:1"))
failedEmail <- contactEmail(1)(repository, _ => IO.raiseError(offline)).attempt
_ <- check(failedEmail == Left(offline))
cache: FindCustomer = id => calls.update(_ :+ s"cache:$id") *> IO.pure(customers.get(id))
hitProgram = cachedCustomer(1)(cache, find)
beforeRun <- calls.get
_ <- check(beforeRun.isEmpty)
hit <- hitProgram
hitCalls <- calls.getAndSet(Vector.empty)
_ <- check(hit.contains(customers(1)) && hitCalls == Vector("cache:1"))
miss <- cachedCustomer(1)(_ => calls.update(_ :+ "cache:miss").as(None), find)
missCalls <- calls.getAndSet(Vector.empty)
_ <- check(miss.contains(customers(1)) && missCalls == Vector("cache:miss", "find:1"))
absent <- cachedCustomer(99)(cache, find)
absentCalls <- calls.getAndSet(Vector.empty)
_ <- check(absent.isEmpty && absentCalls == Vector("cache:99", "find:99"))
cacheFailed <- cachedCustomer(1)(_ => IO.raiseError(offline), find).attempt
cacheFailureCalls <- calls.getAndSet(Vector.empty)
_ <- check(cacheFailed == Left(offline) && cacheFailureCalls.isEmpty)
required <- requiredCustomer(99)(cache, find).value
_ <- check(required == Left(QuoteError.CustomerMissing(99)))
_ <- IO.println(s"Quote: $good")
_ <- IO.println(s"Contact email: $contact")
_ <- IO.println(s"Missing contact: $missingContact")
_ <- IO.println(s"Cache hit: $hit")
_ <- IO.println("All practical Cats checks passed.")
yield ()Start with the result you want to expose. Use OptionT while absence is meaningful on its own. Use EitherT when the workflow needs to explain why it cannot continue. Keep the outer effect’s failure behavior visible, and unwrap at a deliberate boundary. Continue from the Cats, Cats Effect & fs2 series page or revisit type classes, Eq, and Show for the instance model behind these operations.
Scala, JVM, AI, and backend systems. I send practical articles when there is something worth reading.
Join the newsletterNecessary cookies keep the site working. With your permission, I use analytics cookies to understand which articles are useful.