<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Roman Maiun on Medium]]></title>
        <description><![CDATA[Stories by Roman Maiun on Medium]]></description>
        <link>https://medium.com/@romamaiun?source=rss-96f6067c96b3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*zlAzWDWau-9ZT5blnzh_Dg.jpeg</url>
            <title>Stories by Roman Maiun on Medium</title>
            <link>https://medium.com/@romamaiun?source=rss-96f6067c96b3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 23:40:01 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@romamaiun/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Switching between RabbitMQ virtual hosts with Scala and Fs2]]></title>
            <link>https://medium.com/@romamaiun/switching-between-rabbitmq-virtual-hosts-with-scala-and-fs2-4a3166fec0fb?source=rss-96f6067c96b3------2</link>
            <guid isPermaLink="false">https://medium.com/p/4a3166fec0fb</guid>
            <category><![CDATA[rabbitmq]]></category>
            <category><![CDATA[scala]]></category>
            <category><![CDATA[fs2]]></category>
            <dc:creator><![CDATA[Roman Maiun]]></dc:creator>
            <pubDate>Mon, 01 May 2023 14:17:02 GMT</pubDate>
            <atom:updated>2023-05-01T14:17:02.594Z</atom:updated>
            <content:encoded><![CDATA[<h3>Intro</h3><p>In this short article we will explore how to switch between message broker virtual hosts in functional programming using Scala stack, including Fs2 library.</p><h3>Problem definition</h3><p>The problem itself seems to be trivial for imperative programming languages and the solution is basically all about closing connection or exclusion/destroying bean. Anyway, lets imagine that we have 2 different virtual hosts of RabbitMQ broker. Our service by default is connected to the first virtual host, publishes each 2 seconds a message to exchange and listens to the queue. A user is able to call REST command to switch to a different virtual host, shutting down connection to the previous vhost and initializing a new publisher and a subscriber.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/623/1*JbysrE659YMBy1YyH7H69w.png" /><figcaption>Switching between virtual hosts by REST command</figcaption></figure><h3>Solution</h3><p>As a first step lets pick a RabbitMQ client library. My personal choice is fs2-rabbit. It is simple, smart and stream-based, built-in on top of Fs2 and the RabbitMq Java Client. More information could be found at <a href="https://fs2-rabbit.profunktor.dev/"><em>https://fs2-rabbit.profunktor.dev/</em>.</a> Following this link anyone can also find different examples of library usage.</p><p>In our case we need both a producer and a consumer, with a string as message payload type for simplicity.</p><p><strong>So what can be called a producer in functional world?<em> </em></strong>It is just a function MessageToSend -&gt; Effect[Unit] which in our case can be interpreted as AmqpMessage[String] =&gt; F[Unit].</p><blockquote>Because of simplicity our payload will be a string to avoid codec usage.</blockquote><p><strong>And what about the consumer?</strong></p><p>We can understand it as an indefinite stream of elements from the queue, which we are listening to. So, lets describe its type as Stream[F, AmqpEnvelope[String]], where AmqpEnvelope is an incoming message with its metadata including delivery tag, F - our effect which will be responsible for incoming message execution.</p><p>We can introduce new types:</p><pre>import fs2.Stream as Fs2Stream<br><br>type AmqpPublisher[F[_]]  = AmqpMessage[String] =&gt; F[Unit]     //(1)<br>type AmqpConsumer[F[_]]   = Fs2Stream[F, AmqpEnvelope[String]] //(2)<br>  <br>case class AmqpStructures[F[_]](                               //(3)   <br>    instructionPublisher: AmqpPublisher[F],<br>    instructionConsumer: AmqpConsumer[F],<br>    connections: List[AMQPConnection]<br>  )</pre><p>where<br>1 — type of publisher<br>2 — type of consumer<br>3 — case class which contains information about the publisher and the subscriber and their connections.</p><p><strong>This is good moment to describe connection to RabbitMQ.</strong></p><pre>  def initRabbitStructs[F[_]: Async](cfg: Fs2RabbitConfig): Fs2Stream[F, AmqpStructures[F]] =<br>    val structs = for<br>      dispatcher       &lt;- Dispatcher[F]<br>      rc               &lt;- Resource.eval(RabbitClient[F](cfg, dispatcher))<br>      conn1            &lt;- rc.createConnection<br>      conn2            &lt;- rc.createConnection<br>      publisherChannel &lt;- rc.createChannel(conn1)<br>      consumerChannel  &lt;- rc.createChannel(conn2)<br>      publisher        &lt;- Resource.eval(rc.createPublisher[AmqpMessage[String]](instructionEx, instructionRK)(publisherChannel, summon))<br>      consumer         &lt;- Resource.eval(rc.createAutoAckConsumer(instructionQ)(consumerChannel, summon))<br>    yield AmqpStructures(publisher, consumer, List(conn1, conn2))<br>    Fs2Stream.resource(structs)</pre><p>The first thing that we need is Dispatcher which can be explained as a supervisor for effect evaluation. The next step is the creation of a rabbit client. Then we are creating separate channels for the publisher and the consumer, and initializing AmqpStructures with them. As the last step we are transforming Resource into <a href="http://fs2.stream/">fs2.Stream</a>.</p><blockquote>Conversion of the supplied resource into a singleton stream is not mandatory.</blockquote><p><strong>Reconnection approach</strong></p><p>Now it is time to think about reconnection process. As it was said above, on application startup we will create a producer and a consumer. The consumer as an infinite stream will be run at separate fiber. After retrieving a signal for connection to another virtual host we should perform a couple of actions:<br>1. close current connection<br>2. initialize new RabbitMQ connection<br>3. create a new publisher and a subscriber<br>4. stop current consumer.</p><p>Here lets highlight 2 things we need to solve. At first, our publisher seems to be mutable, because after reconnection we will recreate it and the whole business layer will continue to use it. Secondly, we need to define some mechanism of stopping <a href="http://fs2.stream/">fs2.Stream</a> which is run in a separate fiber.</p><p><strong>Consumer stop</strong></p><p>There are multiple possibilities how to stop <a href="http://fs2.stream/">fs2.Stream</a>. We will use SignallingRef. Its type is wrapped into effect. It means that the creation of new SignallingRef is suspended until IO or other monad is evaluated. The right way would be to create switch once on the top level of application and then pass it to business layers as an argument. In scope of stream declaration we will use this type of signal to interrupt stream calling interruptWhen(s: Signal[F,Boolean]).</p><pre>object Main extends IOApp.Simple:<br>  def run: IO[Unit] =<br>    for<br>      switch &lt;- SignallingRef[IO, Boolean](false)                   // (1)<br>      _      &lt;- SwitchBrokerServer.stream[IO](switch).compile.drain // (2)<br>    yield ExitCode.Success</pre><p>At an application entrypoint we can define SignallingRef (1) and pass it to server stream configuration (2).</p><p><strong>Producer mutability</strong></p><p>Cats Effect library includes <a href="https://typelevel.org/cats-effect/docs/std/ref">Ref</a> — a concurrent mutable reference. It is non-blocking, lightweight and built around an AtomicReference. We will use it for our publisher. On the start of the service we will initialize Ref with a default publisher and on each reconnection we will modify Ref with a new one.</p><pre>import fs2.Stream as Fs2Stream<br>  <br>def stream[F[_]: Async](switch: SignallingRef[F, Boolean]): Fs2Stream[F, Nothing] = {<br>    given logger: Logger[F] = Slf4jLogger.getLogger[F]<br>    val defaultBrokerCfg    = SwitchVirtualHostCommand(&quot;dev&quot;)<br>    for<br>            dispatcher  &lt;- Fs2Stream.resource(Dispatcher[F])<br>      _           &lt;- RabbitService.initRabbitRoutes(defaultBrokerCfg)(dispatcher)<br>      structs     &lt;- RabbitService.initRabbitStructs(RabbitService.reconfig(defaultBrokerCfg))(dispatcher)                       // (1)<br>      structsRef  &lt;- Fs2Stream.eval(Ref[F].of(structs))                                                                          // (2)<br>      service     &lt;- Fs2Stream.eval(Slf4jLogger.create[F].map(SwitchVirtualHostService.impl(switch, structsRef, dispatcher, _))) // (3)<br>      httpApp      = (SwitchBrokerRoutes.switchVirtualHostRoutes[F](service)).orNotFound<br>      finalHttpApp = MiddlewareLogger.httpApp(true, true)(httpApp)<br>      exitCode &lt;-<br>        runServer(finalHttpApp) // (4)<br>          .concurrently(  <br>            Fs2Stream  // (5)<br>            .awakeDelay(2 seconds)<br>            .evalTap(_ =&gt; structs.instructionPublisher(AmqpMessage(&quot;init&quot;, new AmqpProperties())))<br>            .interruptWhen(switch)) <br>          .concurrently(<br>            structs.instructionConsumer // (6)<br>              .evalTap(x =&gt; LogService.logPingResult(x.payload))<br>              .interruptWhen(switch)<br>          )<br>    yield exitCode<br>  }.drain</pre><p>In scope of http4s server initialization we create rabbit structures (1) which include a producer and a consumer for a particular virtual host. After that we initialize Ref with a publisher (2) and pass it to application business logic which is represented by SwitchVirtualHostService (3). The next step is the description of http4s server stream itself (4) and the description of 2 concurrent fs2.Streams where the first of them will fire each 2 seconds some default message to a queue (5) and the other one will listen to this queue and log incoming messages (6). Please pay attention to .interruptWhen(switch) part of both streams, which indicates that given streams will be stopped after this switch value is turned to true.</p><p><strong>Switch to another virtual host</strong></p><p>Lets introduce simple REST command to switch between custom virtual hosts.</p><pre>  case class SwitchVirtualHostCommand(virtualHost: String)<br>  case class SwitchBrokerResult(timestamp: LocalDateTime)<br><br>  def switchVirtualHostRoutes[F[_]: Async: Concurrent: Logger: MonadThrowable](<br>    switchBrokerService: SwitchVirtualHostService[F]<br>  ): HttpRoutes[F] =<br>    val dsl = new Http4sDsl[F] {}<br>    import dsl.*<br>    HttpRoutes.of[F] { case req @ POST -&gt; Root / &quot;vhost&quot; / &quot;switch&quot; =&gt;<br>      for<br>        body   &lt;- req.as[SwitchVirtualHostCommand]<br>        result &lt;- switchBrokerService.switchBroker(body)<br>        resp   &lt;- Ok(result)<br>      yield resp<br>    }</pre><p>Now it is time to describe business logic itself.</p><pre>object SwitchVirtualHostService:<br>  def impl[F[_]: Concurrent: Async: Logger](<br>    switch: SignallingRef[F, Boolean],<br>    structsRef: Ref[F, AmqpStructures[F]],<br>    dispatcher: Dispatcher[F],<br>    logger: StructuredLogger[F]<br>  )(using MT: MonadThrowable[F]): SwitchVirtualHostService[F] = new SwitchVirtualHostService[F]:<br><br>    override def switchBroker(dto: SwitchVirtualHostCommand): F[SwitchBrokerResult] =<br>      val switchBrokerF = for<br>        structs &lt;- structsRef.get<br>        _       &lt;- RabbitService.closeConnection(structs)  // (1)<br>        _       &lt;- logger.info(&quot;Old connections are closed&quot;)<br>        _       &lt;- refreshSwitch(switch)  // (2)<br>        _       &lt;- logger.info(&quot;Switch is refreshed&quot;)<br>        _       &lt;- Concurrent[F].start(processReconnectionToBroker(dto, switch, structsRef))  // (3)<br>        _       &lt;- logger.info(&quot;Broker is reconnected&quot;)<br>      yield SwitchBrokerResult(LocalDateTime.now())<br>      MT.handleErrorWith(switchBrokerF)(err =&gt;<br>        logger.error(err)(s&quot;Error while switch to ${dto.virtualHost} vhost&quot;) *&gt;<br>          MT.pure(SwitchBrokerResult(LocalDateTime.now()))<br>      )</pre><p>To disconnect from exist RabbitMQ we need to close previous connections (1). After that we will refresh SignallingRef switch, and that is what we are doing at step (2). Right after that we need to reinitialize rabbit connection, create a publisher and assign it to Ref, then we need to create subscriber and start it (3). We are doing it in a separate fiber because we don’t want to block the main application thread. After all of these actions we can introduce some error handling (4).</p><p>refreshSwitch can be quite simple, for example:</p><pre>    def refreshSwitch(switch: SignallingRef[F, Boolean]): F[Unit] =<br>      switch.update(x =&gt; !x) *&gt; switch.update(x =&gt; !x)</pre><p>processReconnectionToBroker example:</p><pre>private def processReconnectionToBroker(<br>      dto: SwitchVirtualHostCommand,<br>      switch: SignallingRef[F, Boolean],<br>      structsRef: Ref[F, AmqpStructures[F]]<br>    ): F[Unit] =<br>      val consumerStream = for<br>        structs &lt;- RabbitService.initRabbitStructs(RabbitService.reconfig(dto))(dispatcher)<br>        _       &lt;- Fs2Stream.eval(structsRef.update(_ =&gt; structs))<br>        _ &lt;- structs.instructionConsumer<br>               .evalTap(msg =&gt; LogService.logPingResult(msg.payload))<br>               .interruptWhen(switch)<br>               .concurrently(runPingSignals(structs.instructionPublisher, switch))<br>      yield structs<br>      consumerStream.compile.drain</pre><h3><strong>Conclusions</strong></h3><p>In this article we have explored one of the possible scenarios for connecting, reconnecting, switching between virtual hosts or even whole message brokers for RabbitMQ. We have found the way how to work with Fs2 library in scope of this task and have also written a code in a Tagless Final pattern in Scala. Hope it will motivate somebody to discover the amazing world of functional programming concept, especially with Scala. You can find full example by following the link below:<br><a href="https://github.com/rmaiun/switchbrokerservice"><em>https://github.com/rmaiun/switchbrokerservice</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4a3166fec0fb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Saga management in Java with microsaga library.]]></title>
            <link>https://medium.com/@romamaiun/saga-management-in-java-with-microsaga-library-dd146ca7d6a6?source=rss-96f6067c96b3------2</link>
            <guid isPermaLink="false">https://medium.com/p/dd146ca7d6a6</guid>
            <category><![CDATA[microservices-pattern]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[saga]]></category>
            <dc:creator><![CDATA[Roman Maiun]]></dc:creator>
            <pubDate>Thu, 22 Sep 2022 11:36:15 GMT</pubDate>
            <atom:updated>2022-09-22T11:36:15.001Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/417/1*9QkAyJ1epWA0CTkt-DOO5A.png" /></figure><h3>Intro</h3><p>Nowadays microservice architecture plays a significant role in software development. The reasons for that include improved productivity, better resilience, increased scalability, flexible development process, especially for big enterprise solutions. Usually, microservice should be small, self-sufficient and independent. Communication layer should be also taken into account as a separate actor. HTTP, AMQP, gRPC or others — all of them have their pros and cons which should be analyzed and used in some specific cases.</p><p>Encapsulation and single responsibility are good principles for data management on a microservice level. This approach will cover some domain needs, although I`m not sure if anybody will be happy to store some user information by calling absolutely non-related to user endpoints. So that’s why each service usually has its own database and is responsible for data management in scope of a particular domain.</p><p>You can read more about database per service pattern <a href="https://microservices.io/patterns/data/database-per-service.html">here</a>.</p><p>Usage of different databases leads us to the problem where the data inside each service are persisted by local transaction where particular service ensures the atomicity of only its part.</p><p>The Saga pattern, in its turn, combines local transactions between microservices into so-called “Sagas”. The main idea of this pattern is that if local transaction was finished successfully, next transaction will be sequentially run. In case local transaction was failed, a series of compensatory actions must be initiated in order to cancel the results of all the previous transactions.</p><h3>Problem definition</h3><p>As we defined in the previous chapter, saga pattern takes care of long-running transactions by managing sequential run of local transactions and their compensations.</p><p>Let us take a look at a situation where there are 3 services:</p><ul><li><em>OrderService</em> — responsible for product orders management;</li><li><em>PaymentService</em> — responsible for money transferring between bank; accounts</li><li><em>DeliveryService</em> — responsible for all deliveries for ordered products.</li></ul><p>We are trying to implement use case for buying a product. To do that, we should create an order <em>(1)</em> with the description of product attributes and its quantity using order service. Then we should process payment <em>(2)</em>, transferring money from a user account to a company account. Finally, we should ask a delivery company to plan delivery for a particular city for certain date <em>(3)</em>.</p><pre>buyProduct:<br>  OrderClient.createOrder       // 1<br>  PaymentClient.processPayment  // 2<br>  DeliveryClient.planDevivery   // 3</pre><p>However, we should not expect only happy day scenario. Usually some technical or business issues can happen, starting from connection problems to business logic validations. For saga approach we need to describe compensations for our actions. Compensation means some action which will rollback the previous local transaction. In our case it can be done this way:</p><ol><li>Cancel order for particular product.</li><li>Cancel payment and move money back to initial state.</li><li>Cancel planned delivery.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/415/1*Utyxqur6w9nS9cM7npm9Eg.png" /><figcaption>Actions and compensations in case Plan Delivery service fails with an error</figcaption></figure><p>Also, we need to manage the correct order of compensations. If PaymentClient.processPayment part will fail, we must call 2 compensations:</p><ol><li>PaymentClient.cancelPayment to cancel payment and unfreeze client’s money.</li><li>OrderClient.cancelOrder to cancel order itself and make it available for other potential clients.</li></ol><p>So, we will receive the following sets of actions with compensations:</p><pre>OrderClient.createOrder              action #1<br>  OrderClient.cancelOrder              compensation #1<br>PaymentClient.process                action #2<br>  PaymentClient.cancelPayment           compensation #2.1<br>  OrderClient.cancelOrder               compensation #2.2<br>DeliveryClient.planDevivery          action #3<br>  DeliveryClient.cancelDelivery         compensation #3.1<br>  PaymentClient.cancelPayment           compensation #3.2<br>  OrderClient.cancelOrder               compensation #3.3</pre><p>In total, we can see a lot of duplicates and a hardly readable code with a lot of space for potential bugs. With microsaga library we will try to implement saga in an easier way.</p><h3>Microsaga library in practice</h3><p>It is open source library which can be found at <a href="https://github.com/rmaiun/microsaga">github repository</a> and is available at maven central.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bed9cdf4f129af8e5f5c7e5ae3c8ee2c/href">https://medium.com/media/bed9cdf4f129af8e5f5c7e5ae3c8ee2c/href</a></iframe><p>Our task will be to write saga which will be responsible for buying products with given API, where:</p><ul><li><em>client</em> — user who will pay for the product</li><li><em>product</em> — some unique identifier</li><li><em>city</em> — information for delivery</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/855b395156aa666318ce30247e27a040/href">https://medium.com/media/855b395156aa666318ce30247e27a040/href</a></iframe><p>Let us create a saga step for order creation, where compensation will remove a product by sagaId. It should be mentioned that the library automatically creates id based on UUID for each saga and implicitly provides it for both to action and compensation. So, having the following API of Order service,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/197e5d06d2388f683cc48c3cdf855b73/href">https://medium.com/media/197e5d06d2388f683cc48c3cdf855b73/href</a></iframe><p>we can do this saga step:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d2ef3bd207848bba2f3b4dbe66694cda/href">https://medium.com/media/d2ef3bd207848bba2f3b4dbe66694cda/href</a></iframe><p>What we can see here is:</p><ol><li>Saga action has name and action, which can be Callable, Function or Runnable for void action representation. It consumes sagaId, which was passed implicitly by microsaga library. We will use it to mark our data in database.</li><li>Compensation also has name and execution block which in our case also consumes sagaId for data deletion in case action is failed.</li><li>Last instruction creates a saga step which is easy to read and pairs action and compensation.</li></ol><p>We could rewrite it together as follows</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1ff5ff1886cdc7bfaddf090659da05c8/href">https://medium.com/media/1ff5ff1886cdc7bfaddf090659da05c8/href</a></iframe><p>Let us do the same for payment service</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cdb98b9e0c512653e7c1995870c3ee81/href">https://medium.com/media/cdb98b9e0c512653e7c1995870c3ee81/href</a></iframe><p>The only difference for this saga step is that we will use retryable compensation. <em>Failsafe</em> library is one and the only dependency in microsaga library, so we can use its great API for different retry policies.</p><p>As a result, we will receive the following saga step</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4760cbc4c3dc44869da76bd9d0349ff4/href">https://medium.com/media/4760cbc4c3dc44869da76bd9d0349ff4/href</a></iframe><p>Delivery service is the last one in our chain so we will declare saga step for it without compensation, because there is no need to compensate anything if delivery local transaction was unsuccessful. We are not expecting any useful information in response from it, so we use voidRetryableAction for it. Be aware that for void actions NoResultinstance will be returned. Finally, we will make this saga step</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a905ede23e833eae2bb0114ecdc15d4f/href">https://medium.com/media/a905ede23e833eae2bb0114ecdc15d4f/href</a></iframe><p>Now, it is time to combine all those steps and run our saga.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5bb13bc69651907f6d3dcbe4bddcc835/href">https://medium.com/media/5bb13bc69651907f6d3dcbe4bddcc835/href</a></iframe><p>Our saga evaluation consists of multiple steps:</p><ol><li>Composition via zipWith gives an opportunity to make dto transformation for in and out dtos of a particular saga step.</li><li>Composing saga steps by flatmap allows the second step to use data from the result of the first as an input parameter.</li><li>Saga is lazy evaluated, so after we described all the steps, we need to execute them. The easiest way is to call saga management with default behavior by static method use.</li><li>transact method will run the whole saga and apply a chain of compensations for the unsuccessful scenario in the right way.</li><li>EvaluationResult is the result of saga execution which includes some minimal information about saga run. To apply a side effect to a given result, method peek was introduced.</li><li>There are several options for evaluation result processing. We will use API to call value if saga finished successfully or throw error.</li></ol><p>As an example, we can see similar logs for the situation when delivery was not planned.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/992/1*eUkopjvL2Kb4L0fpJvFO-A.png" /></figure><h3>Conclusion</h3><p>Saga pattern implementation requires complex approach and for each system there can be various technologies and techniques used based on a huge amount of factors like technological stack, budget, requirements, etc.. However, if you need a small and smart solution to handle distributed transaction, you can find microsaga library quite attractive. It uses only one dependency, has simple, readable API and can be used starting from java 8. Its syntax is very similar to java streams and Spring Reactor Mono/Flux operators, which gives additional benefits in favor of using it now rather then saving it it for a rainy day.</p><p>Links</p><ul><li>Pattern: Saga<br><a href="https://microservices.io/patterns/data/saga.html">https://microservices.io/patterns/data/saga.html</a></li><li>Microsaga library<br><a href="https://github.com/rmaiun/microsaga">https://github.com/rmaiun/microsaga</a></li><li>Full example for a Spring Boot project + microsaga library<br><a href="https://github.com/rmaiun/microsaga/tree/main/example/simpleservice">https://github.com/rmaiun/microsaga/tree/main/example/simpleservice</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dd146ca7d6a6" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>