DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Modernizing Apache Spark Applications With GenAI: Migrating From Java to Scala
  • Mastering Advanced Aggregations in Spark SQL
  • Thermometer Continuation in Scala
  • Deploying a Scala Play Application to Heroku: A Step-by-Step Guide

Trending

  • Can We Build Elite Search Agents Without Massive Industrial RL Pipelines?
  • 5 Failure Patterns That Break AI Chatbots in Production
  • Getting Started With Agentic Workflows in Java and Quarkus
  • How AI Is Rewriting Full-Stack Java Systems: Practical Patterns with Spring Boot, Kafka and WebSockets
  1. DZone
  2. Coding
  3. Languages
  4. Transactional Effects in Scala

Transactional Effects in Scala

Composing effects with rollbacks in case of failure

By 
Ivan Kurchenko user avatar
Ivan Kurchenko
·
Feb. 13, 21 · Tutorial
Likes (2)
Comment
Save
Tweet
Share
5.0K Views

Join the DZone community and get the full member experience.

Join For Free

Introduction

This post was inspired by a StackOverflow answer for the question Compose Futures with Recovery in Scala: Is it possible to compose Futures in a manner where, if one of them fails, a previous Future's execution result will be rolled back via some function?

The Problem

The case with Future can be generalized to some effect F[_], so we can say: How can we compose effects F[_] in a manner where, if one of them fails, the previous F[_] execution result will be rolled back via some function? This behavior is similar to what we know as a Transaction.

Solution

For the code solution below cats-effect version 2.3.1 used. The final solution can look like this:

Scala
 




x


 
1
/**
2
 * Transactional effect provide possibility to recover effect execution result if it failed, but still return failed
3
 * result.
4
 *
5
 * @tparam F surrounding effect type
6
 */
7
class TransactionEffect[F[_], E](underlying: F[E], rollback: PartialFunction[Throwable, F[Unit]])
8
                                (implicit F: FlatMap[F], ME: MonadError[F, Throwable]) {
9

          
10
  /*
11
   * Here goes syntax trick - in for-comprehension will be invoked `flatMap` of this wrapper and not of underlying effect.
12
   */
13
  def flatMap[S](f: E => F[S]): F[S] = {
14
    F.flatMap(underlying)(f).recoverWith {
15
      case exception: Throwable =>
16
        val failure: F[S] = ME.raiseError[S](exception)
17
        rollback.lift(exception).fold(failure)(recoverEffect => F.flatMap(recoverEffect)(_ => failure))
18
    }
19
  }
20
}
21

          
22
object TransactionEffect {
23

          
24
  /**
25
   * Provides syntax sugar over [[TransactionEffect]] wrapper.
26
   */
27
  implicit class TransactionEffectSyntax[F[_], E](underling: F[E])
28
                                                 (implicit F: FlatMap[F], AE: MonadError[F, Throwable]){
29
    def rollbackWith(rollback: PartialFunction[Throwable, F[Unit]]): TransactionEffect[F, E] = {
30
      new TransactionEffect[F, E](underling, rollback)
31
    }
32
  }
33
}



And small demo:

Scala
 




xxxxxxxxxx
1
14


 
1
object TransactionEffectDemo extends IOApp {
2
  import TransactionEffect._
3
  override def run(args: List[String]): IO[ExitCode] = {
4
    for {
5
      _ <- IO.delay(println("A executed")).rollbackWith {
6
        case _: Throwable => IO.delay(println("A recovered"))
7
      }
8
      _ <- IO.delay(println("B executed")).rollbackWith {
9
        case _: Throwable => IO.delay(println("B recovered"))
10
      }
11
      _ <- IO.raiseError(new Exception("C failed"))
12
    } yield ExitCode.Success
13
  }
14
}



Which will print out the next output (made shorter for the sake of the example):

A executed
B executed
B recovered
A recovered
java.lang.Exception: C failed

Also, you can play with demo in Scatie: https://scastie.scala-lang.org/W8qmBrVQRx6izAVo3Q9yvg

Real-Life Usage

If an application is written in the pure Functional Programming paradigm, ideally it should not have any side effects that it needs to "roll-back" in case of another effect failure. But this approach can be useful when, for instance, the app stores documents in more than one database, e.g. Mongo and Elasticsearch, and removes the document from the main MongoDB if storing in Elasticsearch failed.

Thank you for your attention and hope it will be helpful!

Scala (programming language)

Published at DZone with permission of Ivan Kurchenko. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Modernizing Apache Spark Applications With GenAI: Migrating From Java to Scala
  • Mastering Advanced Aggregations in Spark SQL
  • Thermometer Continuation in Scala
  • Deploying a Scala Play Application to Heroku: A Step-by-Step Guide

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook