<?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 Ddavidso on Medium]]></title>
        <description><![CDATA[Stories by Ddavidso on Medium]]></description>
        <link>https://medium.com/@ddavidso_21474?source=rss-2e4999868347------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*Zl6lkPBbXvnG-oC5</url>
            <title>Stories by Ddavidso on Medium</title>
            <link>https://medium.com/@ddavidso_21474?source=rss-2e4999868347------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 22:11:41 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ddavidso_21474/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[Testing Akka Streams and Kafka]]></title>
            <link>https://medium.com/@ddavidso_21474/testing-akka-stream-and-kafka-35303ac06707?source=rss-2e4999868347------2</link>
            <guid isPermaLink="false">https://medium.com/p/35303ac06707</guid>
            <category><![CDATA[akka-streams]]></category>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[stream]]></category>
            <dc:creator><![CDATA[Ddavidso]]></dc:creator>
            <pubDate>Mon, 11 Nov 2024 20:06:50 GMT</pubDate>
            <atom:updated>2024-11-11T20:13:31.974Z</atom:updated>
            <content:encoded><![CDATA[<p>Recently I had my first foray into the world of <a href="https://doc.akka.io/libraries/akka/current/stream/">Akka Streams</a> and have to say the overall experience was highly positive. I enjoyed the in-depth documentation, the robust feature set both within the framework as well as the testing framework.</p><p>My project was a straight forward project to consume messages from a Kafka topic and transform those messages and persist them. While getting the proof of concept built and running was relatively straight forward using <a href="https://doc.akka.io/libraries/alpakka-kafka/current/home.html">Alpakka Kafka</a>, I struggled to move to production code when it came to writing tests.</p><p>I’ll go over the lessons I learned while working on this project to hopefully help future developers not run into the same hardship I encountered.</p><h3>Alpakka Kafka Documentation</h3><p>The one example “test” in the Alpakka Kafka documentation is missing elements to what I feel is a good example.</p><p>One approach to unit testing is to follow the Arrange, Act and Assert (AAA) pattern. Following this well established pattern would allow for a near real world unit test. Let’s take a look at the “test” in Akka’s documentation a see where we can improve.</p><pre>import akka.kafka.testkit.ConsumerResultFactory;<br>import akka.kafka.testkit.ProducerResultFactory;<br>import akka.kafka.testkit.javadsl.ConsumerControlFactory;<br><br>// create elements emitted by the mocked Consumer<br>List&lt;ConsumerMessage.CommittableMessage&lt;String, String&gt;&gt; elements =<br>    Arrays.asList(<br>        ConsumerResultFactory.committableMessage(<br>            new ConsumerRecord&lt;&gt;(topic, partition, startOffset, &quot;key&quot;, &quot;value 1&quot;),<br>            ConsumerResultFactory.committableOffset(<br>                groupId, topic, partition, startOffset, &quot;metadata&quot;)),<br>        ConsumerResultFactory.committableMessage(<br>            new ConsumerRecord&lt;&gt;(topic, partition, startOffset + 1, &quot;key&quot;, &quot;value 2&quot;),<br>            ConsumerResultFactory.committableOffset(<br>                groupId, topic, partition, startOffset + 1, &quot;metadata 2&quot;)));<br><br>// create a source imitating the Consumer.committableSource<br>Source&lt;ConsumerMessage.CommittableMessage&lt;String, String&gt;, Consumer.Control&gt;<br>    mockedKafkaConsumerSource =<br>        Source.cycle(elements::iterator)<br>            .viaMat(ConsumerControlFactory.controlFlow(), Keep.right());<br><br>// create a source imitating the Producer.flexiFlow<br>Flow&lt;<br>        ProducerMessage.Envelope&lt;String, String, ConsumerMessage.CommittableOffset&gt;,<br>        ProducerMessage.Results&lt;String, String, ConsumerMessage.CommittableOffset&gt;,<br>        NotUsed&gt;<br>    mockedKafkaProducerFlow =<br>        Flow<br>            .&lt;ProducerMessage.Envelope&lt;String, String, ConsumerMessage.CommittableOffset&gt;&gt;<br>                create()<br>            .map(<br>                msg -&gt; {<br>                  if (msg instanceof ProducerMessage.Message) {<br>                    ProducerMessage.Message&lt;String, String, ConsumerMessage.CommittableOffset&gt;<br>                        msg2 =<br>                            (ProducerMessage.Message&lt;<br>                                    String, String, ConsumerMessage.CommittableOffset&gt;)<br>                                msg;<br>                    return ProducerResultFactory.result(msg2);<br>                  } else throw new RuntimeException(&quot;unexpected element: &quot; + msg);<br>                });<br><br>// run the flow as if it was connected to a Kafka broker<br>Pair&lt;Consumer.Control, CompletionStage&lt;Done&gt;&gt; stream =<br>    mockedKafkaConsumerSource<br>        .map(<br>            msg -&gt; {<br>              ProducerMessage.Envelope&lt;String, String, ConsumerMessage.CommittableOffset&gt;<br>                  message =<br>                      new ProducerMessage.Message&lt;&gt;(<br>                          new ProducerRecord&lt;&gt;(<br>                              targetTopic, msg.record().key(), msg.record().value()),<br>                          msg.committableOffset());<br>              return message;<br>            })<br>        .via(mockedKafkaProducerFlow)<br>        .map(ProducerMessage.Results::passThrough)<br>        .toMat(Committer.sink(committerSettings), Keep.both())<br>        .run(sys);</pre><p>Above, there seems to be no testing pattern followed, missing distinct set up and execution of a unit, and no assertion at all. As well as this example is not using a unit testing framework. It would be nice to have examples for each, but I will focus on JUnit 5.</p><h3>Arrange</h3><p>Taking the above, let’s put it with the JUnit 5 framework as well as designate the setup.</p><pre>package com.adobe.akka.alpakka.kafka;<br><br>import akka.Done;<br>import akka.NotUsed;<br>import akka.actor.ActorSystem;<br>import akka.kafka.ConsumerMessage;<br>import akka.kafka.ProducerMessage;<br>import akka.kafka.javadsl.Consumer;<br>import akka.kafka.testkit.ConsumerResultFactory;<br>import akka.kafka.testkit.ProducerResultFactory;<br>import akka.kafka.testkit.javadsl.ConsumerControlFactory;<br>import akka.stream.javadsl.Flow;<br>import akka.stream.javadsl.Keep;<br>import akka.stream.javadsl.Sink;<br>import akka.stream.javadsl.Source;<br>import akka.stream.testkit.TestSubscriber;<br>import org.apache.kafka.clients.consumer.ConsumerRecord;<br>import org.junit.jupiter.api.Test;<br><br>import java.util.Arrays;<br>import java.util.List;<br>import java.util.concurrent.CompletableFuture;<br>import java.util.concurrent.CompletionStage;<br><br>class ApplicationTest {<br><br>    @Test<br>    void givenTwoCommittableMessages_whenConsumed_thenProduceThoseMessagesOntoATargetTopic() {<br>        // Arrange<br>        var sys = ActorSystem.create(&quot;QuickStart&quot;);<br>        var topic = &quot;topic&quot;;<br>        var partition = 0;<br>        var startOffset = 0L;<br>        var groupId = &quot;groupId&quot;;<br><br>        // create elements emitted by the mocked Consumer<br>        List&lt;ConsumerMessage.CommittableMessage&lt;String, String&gt;&gt; elements =<br>                Arrays.asList(<br>                        ConsumerResultFactory.committableMessage(<br>                                new ConsumerRecord&lt;&gt;(topic, partition, startOffset, &quot;key&quot;, &quot;value 1&quot;),<br>                                ConsumerResultFactory.committableOffset(<br>                                        groupId, topic, partition, startOffset, &quot;metadata&quot;)),<br>                        ConsumerResultFactory.committableMessage(<br>                                new ConsumerRecord&lt;&gt;(topic, partition, startOffset + 1, &quot;key&quot;, &quot;value 2&quot;),<br>                                ConsumerResultFactory.committableOffset(<br>                                        groupId, topic, partition, startOffset + 1, &quot;metadata 2&quot;)));<br><br>        // create a source imitating the Consumer.committableSource<br>        Source&lt;ConsumerMessage.CommittableMessage&lt;String, String&gt;, Consumer.Control&gt;<br>                mockedKafkaConsumerSource =<br>                Source.cycle(elements::iterator)<br>                        .viaMat(ConsumerControlFactory.controlFlow(), Keep.right());<br><br>        // create a source imitating the Producer.flexiFlow<br>        Flow&lt;<br>                ProducerMessage.Envelope&lt;String, String, ConsumerMessage.CommittableOffset&gt;,<br>                ProducerMessage.Results&lt;String, String, ConsumerMessage.CommittableOffset&gt;,<br>                NotUsed&gt;<br>                mockedKafkaProducerFlow =<br>                Flow<br>                        .&lt;ProducerMessage.Envelope&lt;String, String, ConsumerMessage.CommittableOffset&gt;&gt;<br>                                create()<br>                        .map(<br>                                msg -&gt; {<br>                                    if (msg instanceof ProducerMessage.Message) {<br>                                        ProducerMessage.Message&lt;String, String, ConsumerMessage.CommittableOffset&gt;<br>                                                msg2 =<br>                                                (ProducerMessage.Message&lt;<br>                                                        String, String, ConsumerMessage.CommittableOffset&gt;)<br>                                                        msg;<br>                                        return ProducerResultFactory.result(msg2);<br>                                    } else throw new RuntimeException(&quot;unexpected element: &quot; + msg);<br>                                });<br><br>        // create a committable sink setup to commit the offsets<br>        TestSubscriber.Probe&lt;ConsumerMessage.CommittableOffset&gt; requestReceivedProbe =<br>                new TestSubscriber.Probe&lt;&gt;(sys);<br>        Sink&lt;ConsumerMessage.CommittableOffset, CompletionStage&lt;Done&gt;&gt; mockCommitterSink =<br>                Sink.fromSubscriber(requestReceivedProbe)<br>                        .mapMaterializedValue(done -&gt; CompletableFuture.completedFuture(null));<br><br>        // Act<br><br>        // Assert<br>    }<br>}</pre><p>In the refactoring above, I’ve included the imports (this really needs to be more standard practice), our test class, our annotated unit test and a full arrangement of the test including string and number constants.</p><p>You’ll also noticed I have included a mock of the committable sink. We will also assume we will take advantage of the <a href="https://doc.akka.io/libraries/akka-core/current/stream/stream-composition.html">compostability and modularity</a> of Akka streams. The code we are testing is injecting a source, a flow and a sink and we will verify if those components are correctly wired up in our topology.</p><h3>Act</h3><p>The <em>act</em> section of a unit test can be not obvious and some may prefer to skip this section all together. The reason is that in akka streams the execution of code does not occur until there are messages from the source to stream. Since in the example above the source is set up using an array of two messages the act can essentially be skipped. My preference is to retain the act section and programmatically add to the source.</p><pre>package com.adobe.akka.alpakka.kafka;<br><br>...<br>import akka.stream.testkit.TestPublisher;<br>...<br><br>class ApplicationTest {<br><br>    @Test<br>    void givenTwoCommittableMessages_whenConsumed_thenProduceThoseMessagesOntoATargetTopic() {<br>        // Arrange<br>        ...<br>        // remove the previous defined mockedKafkaConsumerSource and us a TestPublisher to allow for more granular control<br>        var source = new TestPublisher.Probe&lt;ConsumerMessage.CommittableMessage&lt;String, String&gt;&gt;(1, sys);<br><br>        // create a source imitating the Consumer.committableSource<br>        Source&lt;ConsumerMessage.CommittableMessage&lt;String, String&gt;, Consumer.Control&gt; mockedKafkaConsumerSource =<br>                Source.fromPublisher(source).viaMat(ConsumerControlFactory.controlFlow(), Keep.right());<br><br>        ...<br>        CompletionStage&lt;Void&gt; stream =<br>                Application.run(<br>                        mockedKafkaConsumerSource,<br>                        mockedKafkaProducerFlow,<br>                        mockCommitterSink);<br><br>        // Act<br>        requestReceivedProbe.request(2);<br>        source<br>                .sendNext(elements.get(0))<br>                .sendNext(elements.get(1))<br>                .sendComplete();<br><br>        // Assert<br>    }<br>}</pre><p>We start off the <strong>Act </strong>using a <a href="https://doc.akka.io/japi/akka-core/current/akka/stream/testkit/TestSubscriber.Probe.html">TestSubscriber.Probe</a> to request two messages. This is a nice display of how akka streams operates. The sinks are responsible for requesting messages when they have capacity and a core part of how <a href="https://doc.akka.io/libraries/akka-core/2.7/stream/stream-flows-and-basics.html#back-pressure-explained">back-pressure</a> is managed in Akka streams as subscribers (sinks) pull data from publishers (sources). Also we use a <a href="https://doc.akka.io/japi/akka-core/current//akka/stream/testkit/TestPublisher.Probe.html">TestPublisher.Probe</a> to allow us to programmatically send the next elements to the stream. Now we have an explicit <strong>Act</strong> where the requested messages are added using <em>sendNext</em><strong><em> </em></strong>method and the stream is ended using <em>sendComplete.</em></p><p>Also, we’ve updated the <strong>Arrange</strong> section to include what normally would be the act in non-streaming application, but in this case it is there is a slight paradigm shift as the <em>Application.run </em>is just setting up our topology to receive messages. Our <em>Application.run</em> implementation comes from the Akka example code and we inject the major elements of the topology: source, flow and sink.</p><pre>package com.adobe.akka.alpakka.kafka;<br><br>import akka.Done;<br>import akka.NotUsed;<br>import akka.actor.ActorSystem;<br>import akka.japi.Pair;<br>import akka.kafka.ConsumerMessage;<br>import akka.kafka.ProducerMessage;<br>import akka.kafka.javadsl.Consumer;<br>import akka.stream.javadsl.Flow;<br>import akka.stream.javadsl.Keep;<br>import akka.stream.javadsl.Sink;<br>import akka.stream.javadsl.Source;<br>import org.apache.kafka.clients.producer.ProducerRecord;<br><br>import java.util.concurrent.CompletionStage;<br><br>public class Application {<br>    public static void main(String[] args) {<br>        System.out.println(&quot;Hello World!&quot;);<br>    }<br><br>    public static CompletionStage&lt;Done&gt; run(<br>            ActorSystem system,<br>            Source&lt;ConsumerMessage.CommittableMessage&lt;String, String&gt;, Consumer.Control&gt; source,<br>            Flow&lt;<br>                    ProducerMessage.Envelope&lt;String, String, ConsumerMessage.CommittableOffset&gt;,<br>                    ProducerMessage.Results&lt;String, String, ConsumerMessage.CommittableOffset&gt;,<br>                    NotUsed&gt; flow,<br>            Sink&lt;ConsumerMessage.CommittableOffset, CompletionStage&lt;Done&gt;&gt; sink) {<br>        Pair&lt;Consumer.Control, CompletionStage&lt;Done&gt;&gt; stream =<br>                source<br>                        .map(<br>                                msg -&gt;<br>                                        (ProducerMessage.Envelope&lt;String, String, ConsumerMessage.CommittableOffset&gt;) new ProducerMessage.Message&lt;&gt;(<br>                                                new ProducerRecord&lt;&gt;(<br>                                                        &quot;targetTopic&quot;, msg.record().key(), msg.record().value()),<br>                                                msg.committableOffset()))<br>                        .via(flow)<br>                        .map(ProducerMessage.Results::passThrough)<br>                        .toMat(sink, Keep.both())<br>                        .run(system);<br>        return stream.second();<br>    }<br>}</pre><h3>Assert</h3><p>Finally, we need to assert our expectations for this test. I think there are two valid assertions that can be made in this unit test. Let’s start with what messages the <em>sink </em>receive.</p><pre>package com.adobe.akka.alpakka.kafka;<br><br>...<br><br>class ApplicationTest {<br><br>    @Test<br>    void givenTwoCommittableMessages_whenConsumed_thenProduceThoseMessagesOntoATargetTopic() {<br>        // Arrange<br>        ...<br><br>        // Act<br>        ...<br><br>        // Assert<br>        requestReceivedProbe<br>                .expectNext(elements.get(0).committableOffset())<br>                .expectNext(elements.get(1).committableOffset())<br>                .expectComplete();<br><br>        // Cleanup<br>        stream.thenAccept(done -&gt; sys.terminate());<br>    }<br>}</pre><p>In the adjustments above we expect the two offsets to be received by the committable sink and finally the complete signal. Complete signals should in theory never be received when consuming a kafka topic and for this is optional.</p><p>The other assertion we would like to verify is that the <em>flow</em> received the elements from the source. This assertion would verify that the flow is added to the topology correctly.</p><pre>package com.adobe.akka.alpakka.kafka;<br><br>...<br>import akka.japi.function.Function;<br>...<br><br>import static org.mockito.ArgumentMatchers.any;<br>import static org.mockito.Mockito.*;<br><br>class ApplicationTest {<br><br>    @Test<br>    void givenTwoCommittableMessages_whenConsumed_thenProduceThoseMessagesOntoATargetTopic() throws Exception {<br>        // Arrange<br>        ...<br>        Function&lt;ProducerMessage.Envelope&lt;String, String, ConsumerMessage.CommittableOffset&gt;,<br>                ProducerMessage.Results&lt;String, String, ConsumerMessage.CommittableOffset&gt;&gt; mockTransformer = mock(Function.class);<br>        when(mockTransformer.apply(any()))<br>                .thenReturn(ProducerResultFactory.result(message1))<br>                .thenReturn(ProducerResultFactory.result(message2));<br><br>        // create a source imitating the Producer.flexiFlow<br>        Flow&lt;<br>                ProducerMessage.Envelope&lt;String, String, ConsumerMessage.CommittableOffset&gt;,<br>                ProducerMessage.Results&lt;String, String, ConsumerMessage.CommittableOffset&gt;,<br>                NotUsed&gt;<br>                mockedKafkaProducerFlow =<br>                Flow.fromFunction(mockTransformer);<br><br>        ...<br><br>        // Act<br>        ...<br><br>        // Assert<br>        ...<br><br>        verify(mockTransformer, times(2)).apply(any());<br><br>        // Cleanup<br>        stream.thenAccept(done -&gt; sys.terminate());<br>    }<br>}</pre><p>In the above we introduced <a href="https://site.mockito.org/">Mockito</a> as a mocking framework and replaced our previous <em>mockedKafkaProducerFlow </em>with a mocked Function. Introducing a mocking framework allows us to both define the behavior of the flow, but also verify the flow has been invoked as expected.</p><h3>Conclusion</h3><p>My journey with Akka Streams and Kafka has been both challenging and rewarding. The robust documentation and feature set provided a solid foundation, but transitioning from a proof of concept to production-ready code highlighted the importance of thorough testing. By adopting the Arrange, Act, and Assert (AAA) pattern and leveraging tools like JUnit 5 and Mockito, I was able to create more reliable and maintainable tests. These practices not only improved the quality of my code but also deepened my understanding of Akka Streams’ capabilities and the intricacies of stream processing. I hope the lessons shared here will help other developers navigate similar challenges and achieve success in their projects. You can view the complete project on <a href="https://github.com/landondavidson/testing-alpakka-kafka">github</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=35303ac06707" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Akka Streams Parallel Processing Extended]]></title>
            <link>https://medium.com/@ddavidso_21474/akka-streams-parallel-processing-extended-535751e146ea?source=rss-2e4999868347------2</link>
            <guid isPermaLink="false">https://medium.com/p/535751e146ea</guid>
            <category><![CDATA[parallel-computing]]></category>
            <category><![CDATA[akka]]></category>
            <category><![CDATA[akka-streams]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Ddavidso]]></dc:creator>
            <pubDate>Fri, 01 Nov 2024 18:02:49 GMT</pubDate>
            <atom:updated>2024-11-01T18:02:49.247Z</atom:updated>
            <content:encoded><![CDATA[<p>Akka Streams is a mature and feature-rich package for processing data streams. While the Akka Streams documentation is extensive, I found a gap regarding parallel processing.</p><p>In my project, I needed to take a batch of events published to a Kafka topic, run them through an ETL process, and publish the transformed batch to another system. One part of the extraction process involved looking up the parent object of each event in the target system. If the parent object was missing, the project requirements dictated creating a new parent object using the data within the event. Each batch could contain a mix of events with missing and known parents, so the goal was to process these events in parallel while keeping the batch intact.</p><p>We will explore a solution to this problem, starting with the pancake chef example found in the Akka documentation. In this example, we have four chefs: the first two chefs cook the pancakes on one side and then pass them to the second two chefs to complete the cooking. Below is the code snippet from the Akka documentation:</p><pre>Flow&lt;ScoopOfBatter, HalfCookedPancake, NotUsed&gt; pancakeChefs1 =<br>    Flow.fromGraph(<br>        GraphDSL.create(<br>            b -&gt; {<br>              final UniformFanInShape&lt;HalfCookedPancake, HalfCookedPancake&gt; mergeHalfCooked =<br>                  b.add(Merge.create(2));<br>              final UniformFanOutShape&lt;ScoopOfBatter, ScoopOfBatter&gt; dispatchBatter =<br>                  b.add(Balance.create(2));<br><br>              // Two chefs work with one frying pan for each, half-frying the pancakes then<br>              // putting<br>              // them into a common pool<br>              b.from(dispatchBatter.out(0))<br>                  .via(b.add(fryingPan1.async()))<br>                  .toInlet(mergeHalfCooked.in(0));<br>              b.from(dispatchBatter.out(1))<br>                  .via(b.add(fryingPan1.async()))<br>                  .toInlet(mergeHalfCooked.in(1));<br><br>              return FlowShape.of(dispatchBatter.in(), mergeHalfCooked.out());<br>            }));<br><br>Flow&lt;HalfCookedPancake, Pancake, NotUsed&gt; pancakeChefs2 =<br>    Flow.fromGraph(<br>        GraphDSL.create(<br>            b -&gt; {<br>              final UniformFanInShape&lt;Pancake, Pancake&gt; mergePancakes = b.add(Merge.create(2));<br>              final UniformFanOutShape&lt;HalfCookedPancake, HalfCookedPancake&gt;<br>                  dispatchHalfCooked = b.add(Balance.create(2));<br><br>              // Two chefs work with one frying pan for each, finishing the pancakes then<br>              // putting<br>              // them into a common pool<br>              b.from(dispatchHalfCooked.out(0))<br>                  .via(b.add(fryingPan2.async()))<br>                  .toInlet(mergePancakes.in(0));<br>              b.from(dispatchHalfCooked.out(1))<br>                  .via(b.add(fryingPan2.async()))<br>                  .toInlet(mergePancakes.in(1));<br><br>              return FlowShape.of(dispatchHalfCooked.in(), mergePancakes.out());<br>            }));<br><br>Flow&lt;ScoopOfBatter, Pancake, NotUsed&gt; kitchen = pancakeChefs1.via(pancakeChefs2);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/716/1*Zfs_4DgmNsgGomeX9mTOPQ.png" /><figcaption>Illustrates the workflow in the kitchen with four chefs, each group of chefs specializing in a different task.</figcaption></figure><p>In the previous example, we parallelized the same work across multiple workers (pancake chefs). However, what if we need different types of work to be performed by different workers? Let’s introduce the concept of an order, which includes one pancake and one mix-in, such as chocolate chips, banana, or blueberry. Each pancake mix is unique and made to order, so we’ll need to have a chef who specializes in preparing each type of batter. With this new order concept, we’ll need another set of chefs to help out with the prep work, specific to each type of mix-in. So we’ll introduce the “prep chef” into the equation.</p><p>To accomplish this flow, we will <a href="https://doc.akka.io/docs/akka/current/stream/operators/Broadcast.html">broadcast</a> each order to all the prep chefs. Each prep chefs will ignore orders for batter they do not specialize in and only prepare the orders they are responsible for.</p><p>First, we will create flows for each pancake mix-in. Each flow will filter for the specific mix-in and then map each order that passes the filter into a specific scoop of batter.</p><pre>Flow&lt;PancakeOrder, ScoopOfBatter, NotUsed&gt; blueberryBatterFlow =<br>        Flow.of(PancakeOrder.class)<br>                .filter(order -&gt; order.getAddIn() == PancakeAddIn.BLUEBERRY)<br>                .map(PancakeOrder::getScoop);<br><br>Flow&lt;PancakeOrder, ScoopOfBatter, NotUsed&gt; bananaBatterFlow =<br>        Flow.of(PancakeOrder.class)<br>                .filter(order -&gt; order.getAddIn() == PancakeAddIn.BANANA)<br>                .map(PancakeOrder::getScoop);<br><br>Flow&lt;PancakeOrder, ScoopOfBatter, NotUsed&gt; chocolateChipBatterFlow =<br>        Flow.of(PancakeOrder.class)<br>                .filter(order -&gt; order.getAddIn() == PancakeAddIn.CHOCOLATE_CHIP)<br>                .map(PancakeOrder::getScoop);</pre><p>Next, we will create a graph similar to the one above. However, instead of using a balanced fan-out, we will use a broadcast so that each flow receives the order.</p><p>Finally, we will integrate the pancake mix chef flows into the graph. This way, the order will be distributed to each chef, and the results will be merged back into a single stream.</p><pre>Flow&lt;PancakeOrder, ScoopOfBatter, NotUsed&gt; prepareBatter = Flow.fromGraph(GraphDSL.create(builder -&gt; {<br>    final UniformFanInShape&lt;ScoopOfBatter, ScoopOfBatter&gt; mergeOrders = builder.add(Merge.create(3));<br>    final UniformFanOutShape&lt;PancakeOrder, PancakeOrder&gt; dispatchOrders = builder.add(Broadcast.create(3));<br><br>    // Three chefs work together to prepare a made to order batter.<br>    // A chef is assigned to a specific type of batter and a copy of all pancake orders go to each chef.<br>    // A chef will only prepare a batter if the order is for their assigned type of batter,<br>    // otherwise the order is dropped.<br>    builder.from(dispatchOrders)<br>            .via(builder.add(blueberryBatterFlow.async()))<br>            .toInlet(mergeOrders.in(0));<br>    builder.from(dispatchOrders)<br>            .via(builder.add(bananaBatterFlow.async()))<br>            .toInlet(mergeOrders.in(1));<br>    builder.from(dispatchOrders)<br>            .via(builder.add(chocolateChipBatterFlow.async()))<br>            .toInlet(mergeOrders.in(2));<br><br>    return FlowShape.of(dispatchOrders.in(), mergeOrders.out());<br>}));</pre><p>Once we have the scoops of batter with specific mix-ins prepared, we can continue the flow as previously established with the four pancake chefs example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oZg14L1SdPnHP0dlVcXzbA.png" /><figcaption>Each chef receives four orders but only prepares their assigned type of batter. For example, the chocolate chip chef ignores banana and blueberry orders and prepares only the chocolate chip batter.</figcaption></figure><p>To make this more relevant and efficient, we should support batches of orders. We’ll call each batch of orders a ticket, with each ticket containing all the pancake orders for a specific table. The expectation is that all pancakes for a table should be served at the same time. Therefore, we need a way to parallelize the work for each pancake mix while keeping the orders together to prevent them from getting cold or being served separately.</p><p>To accomplish this, we will use the broadcast method to send each ticket to all the pancake mix chefs. Instead of merging the scoops of batter, we will <a href="https://doc.akka.io/docs/akka/current/stream/operators/Source-or-Flow/zip.html">zip</a> the results into a PancakeBatterBatch. Each pancake mix chef will need to adjust their behavior slightly to always produce a PancakeBatterBatch for each ticket received, even if no work is needed, to easily merge the results back into a one-to-one batch corresponding to the ticket.</p><p>The first step is to create flows for each chef and add support for batching. As each ticket comes in, only the orders with a mix-in for the assigned chef will be processed. However, each ticket will produce a PancakeBatterBatch with 0 to n scoops of batter, where n is the number of orders in the ticket.</p><pre>Flow&lt;Ticket, PancakeBatterBatch, NotUsed&gt; blueberryBatterFlow =<br>        Flow.of(Ticket.class)<br>                .map(ticket -&gt; {<br>                            List&lt;ScoopOfBatter&gt; scoopsOfBatter =  ticket.getPancakeOrders()<br>                                    .stream()<br>                                    .filter(order -&gt; order.getAddIn() == PancakeAddIn.BLUEBERRY)<br>                                    .map(PancakeOrder::getScoop)<br>                                    .collect(Collectors.toList());<br>                            return new PancakeBatterBatch(ticket.getId(), scoopsOfBatter);<br>                        }<br>                );<br><br>Flow&lt;Ticket, PancakeBatterBatch, NotUsed&gt; bananaBatterFlow =<br>        Flow.of(Ticket.class)<br>                .map(ticket -&gt; {<br>                    List&lt;ScoopOfBatter&gt; scoopsOfBatter = ticket.getPancakeOrders()<br>                            .stream()<br>                            .filter(order -&gt; order.getAddIn() == PancakeAddIn.BANANA)<br>                            .map(PancakeOrder::getScoop)<br>                            .collect(Collectors.toList());<br>                    return new PancakeBatterBatch(ticket.getId(), scoopsOfBatter);<br>                });<br><br>Flow&lt;Ticket, PancakeBatterBatch, NotUsed&gt; chocolateChipBatterFlow =<br>        Flow.of(Ticket.class)<br>                .map(ticket -&gt; {<br>                    List&lt;ScoopOfBatter&gt; scoopsOfBatter = ticket.getPancakeOrders()<br>                            .stream()<br>                            .filter(order -&gt; order.getAddIn() == PancakeAddIn.CHOCOLATE_CHIP)<br>                            .map(PancakeOrder::getScoop)<br>                            .collect(Collectors.toList());<br>                    return new PancakeBatterBatch(ticket.getId(), scoopsOfBatter);<br>                });</pre><p>The next step is to broadcast the tickets to each pancake mix chef and then zip the batches of batter from each chef into a single batch to pass to Chef 1 (the chef that cooks one side of the pancake). In this example, we used the ZipWithN operator because there are three flows that need to be combined, whereas the standard zip operation only supports zipping two streams.</p><pre>Flow&lt;Ticket, PancakeBatterBatch, NotUsed&gt; prepareBatter = Flow.fromGraph(GraphDSL.create(builder -&gt;{<br>    final UniformFanInShape&lt;PancakeBatterBatch, PancakeBatterBatch&gt; mergeBatters =<br>            builder.add(ZipWithN.create(pancakeBatches -&gt; pancakeBatches<br>                    .stream()<br>                    .reduce(<br>                            new PancakeBatterBatch(), (accumulatorBatch, currentBatch) -&gt; {<br>                                accumulatorBatch.setTicketId(currentBatch.getTicketId());<br>                                accumulatorBatch.concatenateScoops(currentBatch.getScoops());<br>                                return accumulatorBatch;<br>                            } ),3<br>            ));<br>    final UniformFanOutShape&lt;Ticket, Ticket&gt; dispatchOrder =<br>            builder.add(Broadcast.create(3));<br><br>    builder.from(dispatchOrder)<br>            .via(builder.add(blueberryBatterFlow))<br>            .toInlet(mergeBatters.in(0));<br>    builder.from(dispatchOrder)<br>            .via(builder.add(bananaBatterFlow))<br>            .toInlet(mergeBatters.in(1));<br>    builder.from(dispatchOrder)<br>            .via(builder.add(chocolateChipBatterFlow))<br>            .toInlet(mergeBatters.in(2));<br>    return FlowShape.of(dispatchOrder.in(), mergeBatters.out());<br>}));</pre><p>Finally, we need to update the flows for Chef 1 and Chef 2 to operate on batches of batter rather than single scoops.</p><pre>Flow&lt;Ticket, HalfCookedPancakeBatch, NotUsed&gt; fryingPan1 = Flow.of(Ticket.class)<br>        .via(prepareBatter)<br>        .map(batch -&gt; {<br>            List&lt;HalfCookedPancake&gt; halfCookedPancakes = batch<br>                    .getScoops()<br>                    .stream()<br>                    .map(HalfCookedPancake::fromBatter)<br>                    .collect(Collectors.toList());<br>            return new HalfCookedPancakeBatch(batch.getTicketId(), halfCookedPancakes);<br>        });<br><br>Flow&lt;HalfCookedPancakeBatch, PancakeBatch, NotUsed&gt; fryingPan2 =<br>        Flow.of(HalfCookedPancakeBatch.class)<br>                .map(batch -&gt; {<br>                    List&lt;Pancake&gt; pancakes = batch.getHalfCookedPancakes()<br>                            .stream()<br>                            .map(HalfCookedPancake::complete)<br>                            .collect(Collectors.toList());<br>                    return new PancakeBatch(batch.getTicketId(), pancakes);<br>                });<br><br>CompletionStage&lt;Done&gt; done = source<br>        .viaMat(fryingPan1.async(), Keep.right())<br>        .viaMat(fryingPan2.async(), Keep.right())<br>        .toMat(sink, Keep.right())<br>        .run(system);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wdyz3CNN2HuC2KO3rq2rog.png" /><figcaption>This diagram shows three tickets, each with a mix of orders. It demonstrates how batches are produced even if a specific mix chef has no orders to prepare.</figcaption></figure><p>In conclusion, we successfully created a flow that enables parallelism across workers performing different tasks and demonstrated how to batch this work so that it is reassembled once the workers are finished.</p><p>You can find a complete implementation of this on my <a href="https://github.com/landondavidson/akka-stream-splitter">GitHub</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=535751e146ea" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>