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
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • Mastering Advanced Aggregations in Spark SQL
  • Thermometer Continuation in Scala
  • Deploying a Scala Play Application to Heroku: A Step-by-Step Guide
  • Upgrading Spark Pipelines Code: A Comprehensive Guide

Trending

  • AI-Driven Test Automation Techniques for Multimodal Systems
  • How to Convert XLS to XLSX in Java
  • Monolith: The Good, The Bad and The Ugly
  • Agentic AI for Automated Application Security and Vulnerability Management
  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
4.8K 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

  • Mastering Advanced Aggregations in Spark SQL
  • Thermometer Continuation in Scala
  • Deploying a Scala Play Application to Heroku: A Step-by-Step Guide
  • Upgrading Spark Pipelines Code: A Comprehensive Guide

Partner Resources

×

Comments
Oops! Something Went Wrong

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

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

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 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!