<?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 Xavyr Rademaker on Medium]]></title>
        <description><![CDATA[Stories by Xavyr Rademaker on Medium]]></description>
        <link>https://medium.com/@xavyr-rademaker?source=rss-c670a3fc444b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*taNSJ2MgAyJzp_blaZW73g.jpeg</url>
            <title>Stories by Xavyr Rademaker on Medium</title>
            <link>https://medium.com/@xavyr-rademaker?source=rss-c670a3fc444b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 22:04:00 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@xavyr-rademaker/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[Event services on AWS Part 2: SQS deep dive]]></title>
            <link>https://xavyr-rademaker.medium.com/event-services-on-aws-part-2-sqs-deep-dive-380674b6831d?source=rss-c670a3fc444b------2</link>
            <guid isPermaLink="false">https://medium.com/p/380674b6831d</guid>
            <category><![CDATA[sqs]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[event-broker]]></category>
            <category><![CDATA[event-driven-architecture]]></category>
            <category><![CDATA[queuing-system]]></category>
            <dc:creator><![CDATA[Xavyr Rademaker]]></dc:creator>
            <pubDate>Thu, 16 Nov 2023 19:44:50 GMT</pubDate>
            <atom:updated>2023-11-16T19:44:50.477Z</atom:updated>
            <content:encoded><![CDATA[<p>Decoupling microservices using a queueing mechanism</p><p>In my last blog we covered all <a href="https://medium.com/@xavyr-rademaker/event-services-on-aws-part-1-introduction-3e01dfa5a394">event-driven services offered by AWS</a> , the oldest and most used is Simple Queuing Service (SQS). Over the course of this blog, I will first describe queues in SQS incl. the diverse types available, the features and properties related to events, consuming an event, dealing with errors, and monitoring of the queues. Finally, I will wrap it all up with the way pricing works when using SQS.</p><h3>Queues in SQS</h3><p>SQS is a serverless queueing service that is used to decouple microservices from each other using events. It is used for one-to-one microservice communication, where the consumer must poll to receive events. This polling mechanism ensures that downstream services do not get overloaded (the queue acts as a buffering layer). Since it is serverless you do not have to provision or maintain any servers, this is all done by AWS. All you must do is create a queue and start producing/consuming the events from it.</p><p>Event producers can produce their events to the queue, and event consumers can poll them from the queue at their own pace, preventing consumers from getting overwhelmed. Figure 1 gives an example of how the queues can be used to decouple services.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/920/1*6E1bGObNySTeSMkG3_aP0Q.png" /><figcaption><em>Figure 1: Example of queues used to decouple microservices</em></figcaption></figure><p>SQS stores all queues and events in a distributed fashion for resilience and availability purposes. Queues are bound by a region, but by default spread across availability zones (AZs). Whenever an event is produced, it gets stored across AZs to ensure any local outage (or any other form of AZ-wide downtime) will not lead to the loss of events. All management of this distribution is done behind the scenes by AWS. In case your interested in how this is stored, this <a href="https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-resilience.html">page</a> explains it quite well.</p><h4>Types of queues</h4><p>SQS offers multiple types of queues which can serve different use cases. The three main types currently available are:</p><ul><li>Standard queues</li><li>First in first out (FIFO) queues</li><li>High throughput for FIFO queues, which are FIFO queues with specific configurations</li></ul><p>Besides the main queue types, there are also configurations which make a queue a “delay queue”, and a mechanism called temporary queues. In the following subsections I will go over each one of these types of queues to explain what they are and how they differ from each other.</p><p><strong>Standard queues</strong></p><p>Standard queues are the default queues offered by SQS, and are basic queues used for decoupling services and for acting as a buffering layer as described in the introduction of this section. This type of queue does have the highest throughput values in SQS, supporting (nearly) unlimited API calls per second.</p><p>Although the high throughput is a big strength of standard queues, there are some limitations to them as well. The first being related to delivery guarantees. Standard queues support at-least-once message delivery (meaning that an event will be consumed at least once, but potentially multiple times). To ensure proper state in your landscape the consuming microservices should be idempotent, where they produce the same output when given the same inputs, even when the input is given multiple times. An example of when an event can be delivered multiple times is when one of the servers storing a copy of the event is down when the delete operation is being requested. In such scenarios, the copy of the message isn’t deleted on that unavailable server and as consequence a new poll request can result in the old event being retrieved.</p><p>The second limitation to discuss is the ordering guarantee. AWS offers a best-effort ordering guarantee for standard queues, meaning that events will not necessarily be processed in the same order they are produced. If ordering is a requirement in your use-case, FIFO queues are a better fit for you.</p><p><strong>FIFO queues</strong></p><p>FIFO queues are queues where events are guaranteed to be kept in order, and they can be recognized by their names as it is required for them to end with “.fifo.” It is important to know that the ordering guarantee goes for a subset of the events. Each event produced to a FIFO queue is expected to have a message group ID, showing that an event belongs to a group (for example to the session of a user). All events in a queue with the same message group ID are guaranteed to be processed in order, but events of separate groups can be processed out of order of each other. Figure 2 visualizes the ordering difference between standard and FIFO queues.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/896/1*deZNBOS2_qO0uppmOXgNzw.png" /><figcaption><em>Figure 2:</em> <em>Standard vs FIFO queue ordering. Note that for FIFO the consuming combinations (A1, A2, B1) and (B1, A1, A2) are also possible since A1 is before A2 in those combinations. For standard queues all 6 combinations of the 3 events are possible</em></figcaption></figure><p>When consuming from a FIFO queue, the consumer cannot request a specific message group ID to consume from. Instead, consumers just poll from the queue to receive any message present. However, whenever there are multiple message group IDs present on the queue, SQS tries to return as many events with the same message group ID as possible. This way other consumers can process events with other message group IDs. Furthermore, whenever an event with a certain message group ID is consumed, all future events with the same message group ID will not be retrieved by later polls until either the current event is acknowledged (deleted from the queue) or processing has timed out (processing longer than the configured visibility timeout, more on this later).</p><p>Besides ordering, FIFO queues also have a deduplication feature to prevent the same event from getting produced multiple times. There are two ways (which are configurable) for a FIFO queue to detect duplicates. The first approach is content based deduplication, in which SQS uses a SHA-256 hash based on the event body. It uses this hash as the deduplication ID. The second approach is for the producer to explicitly set the deduplication ID value. In both cases SQS will ignore any event it received within the next 5 minutes that has the same deduplication ID.</p><p>By combining the ordering guarantee and the deduplication feature, SQS FIFO queues provide an exactly once-processing functionality. However, there are some situations where this is not the case. The most common edge case being error scenarios. When events are not processed within the configured time, or there are consumer errors with retries enabled, events can be processed multiple times.</p><p>With all the benefits described above, there are also some limitations to FIFO queues. The main limitation is the throughput. Where standard queues offer (nearly) unlimited API calls per second, FIFO queues support up to 300 API calls per second (per queue, including both produce and consume calls). If you enable batching, this means up to 3.000 events can be either produced, consumed or a mix of both per second (note, batches can have up to 10 events). Luckily, if ordering guarantees are necessary in your landscape, and you need a higher throughput, you can either request a quota increase or you can use a feature called high throughput for FIFO queues.</p><p><strong>High throughput for FIFO</strong></p><p>What happens when you need the ordering guarantees and the deduplication features FIFO queues offer, but you need higher throughput than FIFO queues offer? For such use cases you can opt for a feature in FIFO queues called high throughput for FIFO queues.</p><p>High throughput for FIFO queues can be enabled by setting the following two configurations when creating a FIFO queue:</p><ol><li>Set the “deduplication scope” to “Message group”</li><li>Set the “FIFO throughput limits” to “Per message group ID”</li></ol><p>Alternatively, when using the AWS console, you can also check the “Enable high throughput for FIFO” checkmark, which will set the two configurations appropriately.</p><p>The way high throughput for FIFO queues works, when setting these configurations, is that it will partition the data per message group. A partition in this case is a subset of the events that is stored, and replicated, together. Events will be spread across the different partitions based on their message group ID. Even though not all message group IDs will go to the same partition, each group will go to the same. Furthermore, AWS will manage the partition lifecycles for us, and will scale in/out based on the request rates per partition and utilization. Figure 3 gives an example of how events will be distributed across partitions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/958/1*kkuZ3tcJCElaUL3e9yuWGQ.png" /><figcaption><em>Figure 3: Partitions on high throughput for FIFO queues</em></figcaption></figure><p>When using the high throughput for FIFO queues feature, the throughput of your queue can go up to 6.000 transactions per second (depending on your region), which can be increased to 60.000 transactions per second when using batching. For maximum throughput it is recommended to use a message group ID that has enough diversity, to ensure events get distributed over different partitions. This ensures the events get distributed across partitions evenly which can prevent hot partitions. However, in doing so it is important to keep in mind that ordering is guaranteed within a message group ID, so taking a random value for each event will lead to the loss of ordering.</p><p>On a final note, before moving to delay queues, you might wonder why you wouldn’t always use high throughput for FIFO queues when you need the ordering guarantee. Personally I haven’t found any use cases where high throughput mode wasn’t suitable. That being said, if we look at the specific configurations that are set to make a FIFO queue high throughput we see that we need to set the deduplication scope to message group ID rather than the entire queue. This implies that if you have a use case where you need events to be deduplicated over the entire queue, rather than just within a message group, high throughput mode is not suitable for you. Although this sounds like a rather edgy edge-case, because it means you could have the exact same event with a different message group ID without explicitly wanting that, it’s the only use case I can think of not to use high throughput mode when using FIFO queues.</p><p><strong>Delay queues</strong></p><p>Delay queues are more of a configuration on top of standard and FIFO queues rather than their own queue type. When enabling the delay period, all events sent to that queue will be invisible for consumers for the specified period (default is 0 seconds, with a maximum value of 15 minutes). This configuration can be specified when creating a queue, or on existing queues. However, for standard queues the delay will not be added retroactively to existing events on the queue. For FIFO queues the delay will be added retroactively to existing events. Although use cases for delay queues are rare, they can be used to work around race conditions where the service needs some more time processing the data before consumers can use the event. An example of such a use case would be if you have stored procedures that manipulate the database state, while the service already produced the event (when using event notification for example. Note: this is of course an extreme example for illustration purposes which I won’t recommend implementing like this). Another use case could be when you have a fixed period between stages in your landscape, so adding a default delay could be useful instead of consumers consistently checking when the last stage was executed.</p><p><strong>Temporary queues</strong></p><p>The last type of queue is the temporary queue.They are short-lived queues that are created and deleted on the fly when needed. This is done using the temporary queue client. Although depicted here as a different type of queue, temporary queues are actually virtually created on an existing queue, essentially becoming a “sub-queue”. Due to it’s nature, it is not recommended to produce events to temporary queues wiith the same message group ID, because this can lead to the events being distributed over multiple temporary queues which will cause an ordering dependency between temporary queues. For this reason it is recommended to not use virtual queues if you need the FIFO functionality.</p><p>Temporary queues are most often used when a request-reply pattern is needed, while using SQS as the communication layer. Even though this is often considered an anti-pattern, since SQS (and events in general) are used for asynchronous communication between services, AWS decided to add this functionality anyway because users were using SQS for synchronous communication due to, amongst other things, the following benefits:</p><ul><li>It is often easier setting up a queue rather than the infra needed for secure HTTPS communication.</li><li>Queues are secure and can absorb DDOS attacks out of the box.</li></ul><p>Since it is quite rare to have a use case for temporary queues, and it can become quite lengthy to cover them in dept, I will not dive deeper into their mechanics. Instead, for those interested, I would recommend this <a href="https://aws.amazon.com/blogs/compute/simple-two-way-messaging-using-the-amazon-sqs-temporary-queue-client/">blog</a> about it.</p><h3>Event properties</h3><p>Now that we understand the queues in SQS, let us look at the events. All events sent to SQS have a maximum size of 256KiB, which includes the event itself and its metadata. For events larger than this you could use the <a href="https://github.com/awslabs/amazon-sqs-java-extended-client-lib">AWS extended client library for Java</a> which uses the claim/check pattern in combination with S3 for sharing the large events. Events sent over SQS consist out of three parts: Identifier(s), body, and metadata. Next to these parts, events can also have a message timer and can be sent in batches.</p><h4>Event identifier(s)</h4><p>Every event is sent to an SQS queue as a certain number of identifiers, either created by the server (SQS) or provided by the producer of the event. The first identifier to be aware of is the message ID, which is a server generated identifier which is generated and returned by the queue whenever you produce an event. Whenever an event is consumed, a receipt handle is provided with the event. This handle is related to receiving the event, not the actual event (so when consuming an event twice it will have the same message ID, but a different receipt handle). The receipt handle is used to delete events from the queue, meaning you always need to consume the event before deleting it from the queue.</p><p>While the message ID and the receipt handle are present for all queue types, there are three more identifiers that are only present when using FIFO queues. The first being the deduplication id. As mentioned earlier in the FIFO section, the deduplication id is used to prevent duplicate events being produced in a span of 5 minutes and can be either provided by the producer or based on the hash of the event body. The second identifier is the message group id. The message group id indicates to which group the event belongs, which is used to preserve the order of events within that group. Finally, there is the sequence number which SQS assigns to each event that is produced. The sequence number is used to maintain the order of events (within a message group).</p><h4>Event body</h4><p>The event body is the content of the event you have produced. The body is just a string of the intended data to be shared across services. Good to know, when producing an object/JSON, the consumer should have serialization logic to transform this from a string to an object/dictionary as the actual event will just be a string.</p><h4>Event metadata</h4><p>Next to the body, producers can also share metadata about the event along with the body. Examples of metadata that is shared along could be session identifiers and tags to filter events on. There is a limit of 10 attributes that can be added to each event, and each attribute consists of a name, type, and value. Do note that message attributes do count towards the 256KiB event limit.</p><p>Besides custom attributes, it is also possible to provide system attributes. This refers to attributes that are specifically used by other AWS services. Currently the only system attribute supported is the AWSTraceHeader, which is a string which refers to the trace header provided by X-ray. System attributes do not count towards the event size limit.</p><h4>Other Event properties</h4><p>There are two more event properties that can be interesting when producing events, given certain use cases. The first of them is the message timers. Message timers indicate that an event should be invisible to consumers for a certain period (between 0 seconds and 15 minutes). This can be set by the producer upon producing the event. Do note, FIFO queues do not allow you to set message timers on individual events. If you need delays in a FIFO queue, delay queues can be used, which were discussed earlier in this blog.</p><p>The second property to discuss when producing events is batching. SQS supports batches of up to 10 events. Batching can help improve throughput and reduce costs, as all 10 events go over the same API call. There are currently three batch operations: sending events, deleting events, and changing the message visibility. To enable batching, simply use the batch operations instead of the normal ones (for example: SendMessageBatch instead of SendMessage).</p><h3>Consuming events</h3><p>Consuming an event goes in three steps:</p><ol><li>The consumer polls from the queue to get any available events.</li><li>When it receives an event, the consumer will process it.</li><li>The consumer will delete the event from the queue, preventing future polls (of itself or of other consumers) from receiving the same event again.</li></ol><p>Figure 4 illustrates this process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/876/1*2EHE25yCVnCb9jGCn5yZAw.png" /><figcaption><em>Figure 4: Steps taken when consuming an event</em></figcaption></figure><p>Now you might wonder, but what if another consumer (consumer B) polls the queue while the first consumer (consumer A) is still processing the last event it polled, how do we ensure that consumer B does not receive the same event? After an event is consumed, the visibility timeout kicks in. The visibility timeout is a predetermined time span (30 seconds by default but can be configured to be anywhere within 0 seconds and 12 hours on a queue level) for which the event turns invisible for other consumers while it is being processed. This prevents other consumers (consumer B in our example) to re-process the same event. However, this does mean that the event must be processed and deleted within the span of the invisibility timeout. If for some reason processing the event takes longer than the specified visibility timeout consumers can call the ChangeVisibilityTimeout API to extend it. The time specified in the API call will start counting starting the moment the call is made, not from when the event was consumed.</p><p>Finally, I have referred to polling a few times already. By default, consumers apply a mechanism called short polling, which means that it will call the queue and either get an immediate response with events or get an immediate empty response. However, it is often the case that the queue is empty every now and then, meaning that cutting the poll immediately if there are no events is costly. To solve this, and reduce costs, SQS has long polling. Long polling means that the consumer will wait for a certain period to see whether any new events are still coming in before cutting the poll. The maximum configurable waiting period is 20 seconds, which is configurable on the consumer side. It is recommended to always enable long polling for your consumers.</p><h3>Error handling</h3><p>You’ve set up your first queue, created the producers and consumers that use the queue, and all is going well. After a little while you start to see some errors happening where events are either not produced or consumed. What now? In this section I will answer that question as SQS has a few configurations to deal with this.</p><p>Starting with the producer, whenever you receive an error while trying to produce an event, the best you can do is add retries with exponential backoff. As simple as this may sound, it is important to understand the consequences of this. In rare occasions you can get an error on the producing side, but the actual event has been produced and is available on the queue. When using standard queues this means that retrying the event means that the event is produced multiple times, and thus will be consumed multiple times. Luckily, we already know that consumers need to be idempotent, which will solve this. For FIFO queues this will never happen due to the deduplication id, meaning the queue will ignore the second (or third) time the same event happens (within 5 minutes).</p><p>For the consumers, the retrying mechanism is a little different. If the consumer does not delete an event from the queue after processing or takes longer to process an event than the configured visibility timeout, the event will be re-processed upon the next polling cycle. This means that the default behavior of the consumer is to retry the events when an error occurs during processing. Although this is good for resilience, if the event is a poison pill (an event that cannot be processed either due to it being malformed or due to a bug) the event will end in an endless cycle of being consumed and throwing errors.</p><p>For standard queues this is non-blocking. Since events from a standard queue can be consumed out of order, the consumers will just continue to poll all events (including the poison pill) and process them, which will (most often) lead to the valid events being processed and the poison pill repeatedly failing until the queue retention period (which can be configured from 1 minute to 14 days) eventually cleans up the invalid event. For FIFO queues impact is bigger. Since events of a certain message group must be processed in order, an invalid message will block the rest of the message group to be processed until the invalid message is either processed successfully or removed by the retention policy (which can have an impact on the consuming order).</p><p>As you can imagine by now, even though the consumer impact is limited, it can have a serious impact on both your performance and your costs. Repeatedly processing an invalid event costs resources, and for FIFO queues even prevents the rest of the message group from being processed. To prevent the invalid event(s) from being repeatedly consumed for eternity it is recommended to set up a dead-letter queue (DLQ) where these events can go to.</p><p>A DLQ is a second queue where SQS can automatically send events to that cannot be processed properly. This queue must be of the same type as the original (source) queue (so if the source queue is a FIFO queue the DLQ should be a FIFO queue as well). Since the DLQ is a secondary queue, it must be created up front and can only then be configured to act as the DLQ for the source queue. After you have created the DLQ and configured it to act as such, you can setup the redrive policy, which will specify under which conditions an event should move from the source queue to the DLQ (for example: after it has been consumed and processed unsuccessfully 3 times). Do be careful with the conditions you set, because setting it too low (1 failure for example) will increase the chances of false positives (e.g., sending a valid event that failed due to a network error to the DLQ), and setting it too high can lead to the higher costs/lower performance mentioned earlier.</p><p>After the event is sent to the DLQ, you can inspect the event (consume it without deleting it) to see why it caused an issue. After finding and solving the issue (assuming it was an issue in the source code of the consumer which has been fixed), you can use the redrive to source API to send the event back from the DLQ to the source queue, to allow it to be reprocessed. There are some things to keep in mind during the process of moving the events:</p><ul><li>When the event is moved to the DLQ, it keeps the original enqueue timestamp, meaning that the retention period of the DLQ starts counting from the moment the event was originally produced. Do make sure the DLQ retention period is higher than the source queue (or just as high if you have it set to the 14 days).</li><li>When events are moved back to the source queue, they will be seen as “new” events, with a new message id, enqueue time and retention period.</li></ul><p>Before moving the next section, two things to keep in mind whether using a DLQ suits your use case or not:</p><ul><li>For standard queues it is good to use a DLQ, unless you really want to keep retrying an event until it succeeds or expires.</li><li>For FIFO queues, do not use DLQs when the system produces a different outcome if events are not in order. In such cases checking the error and fixing it forward is a better solution (even though it does make the operations more difficult)*.</li></ul><p>*Main reasons why DLQs are not recommended for FIFO queues are:</p><ul><li>You can’t redrive back to the queue out of the box, meaning you’ll have to implement this yourself which can be tricky</li><li>You will need some custom mechanism that routes all events with the same group ID, after the failed event, to the DLQ until the issue is resolved and all events of that group can be driven back to the original queue (in order), which also has to be custom build</li></ul><h3>Metrics and monitoring</h3><p>We know how to deal with errors now, so let us see how to monitor the activities in the queue(s). The first AWS service we can use for monitoring purposes is CloudWatch. By default, SQS pushes multiple metrics to CloudWatch, which can be accessed through the management portal in SQS and in CloudWatch (where you can also create dashboards and alerts based on the metrics), through the SDK or through the CLI. It is important to know that metrics are only gathered for queues that are active. A queue in SQS is said to be active when it contains events for up to 6 hours. After those 6 hours the queue is marked as inactive, and no metrics are gathered. After a queue is activated (again), it can take up to 15 minutes before metrics are being gathered again. Some metrics that are gathered are:</p><ul><li>Number of events in the queue</li><li>The age of the oldest event</li><li>Number of empty poll responses</li><li>Number and size of the events sent</li></ul><p>The full list of metrics can be found <a href="https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-available-cloudwatch-metrics.html">here</a>.</p><p>The second AWS service used for monitoring is CloudTrail. All API calls made to SQS are captured in CloudTrail as logs. These logs can, amongst others, be used for security monitoring. Some examples could be seeing whether unauthorized people/services have access and perform operations the queue for example, or to figure out who deleted the queue on production. Some examples of operations that are being logged in CloudTrail are:</p><ul><li>Creating or deleting a queue</li><li>Setting attributes or tags to a queue</li><li>Sending events to the queue</li></ul><p>The last service I want to discuss regarding monitoring is X-Ray. X-Ray can be used to trace events throughout the various AWS services and microservices. As indicated earlier, we can add the AWSTraceHeader message system attribute to the event to ensure that X-Ray traces the event through the system. Subsequently we can use the management console to view the connections between all services (incl. SQS) used in your event flow.</p><h3>Pricing</h3><p>Before wrapping up, the last subject I want to discuss is the pricing model of SQS. SQS has quite a big free tier, serving the first 1 million requests for free each month. It is good to understand the definition of a request here: every action taken on a queue (sending, receiving, and deleting events, but also increasing the visibility timeout for example) is counted as a request. The size of a request is set at 64 KB, meaning that sending an event of 256KB is counted as 4 requests.</p><p>FIFO requests are charged at a higher rate than standard requests. The FIFO requests are sending, receiving, deleting, and changing visibility of messages from FIFO queues. All other requests (even on FIFO queues) are charged at the standard rates. Finally, you also pay for data going in and out of SQS. All data going into SQS is free of charge. For data going out of SQS you pay per GB, with rates based on the volume. There are some exceptions to this rule: data going from SQS to either AWS Lambda or EC2 in the same region is free of charge. For more information, and the current rates, you can visit <a href="https://aws.amazon.com/sqs/pricing/">here</a>. Furthermore, I found this <a href="https://blog.awsfundamentals.com/sqs-pricing">blog</a> on SQS pricing, including how to be as cost efficient as possible, quite helpful in understanding the pricing model of SQS.</p><h3>Wrap up</h3><p>That is all for the SQS deep dive, by now you should know all about it! Stay tuned for future blogs where I will do similar deep dives into SNS, Kinesis Data Streams (KDS), Managed Streaming for Apache Kafka (MSK), and EventBridge. Besides that, I will also give some practical code examples on working with all of them (incl. SQS)!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=380674b6831d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Event services on AWS Part 1: Introduction]]></title>
            <link>https://xavyr-rademaker.medium.com/event-services-on-aws-part-1-introduction-3e01dfa5a394?source=rss-c670a3fc444b------2</link>
            <guid isPermaLink="false">https://medium.com/p/3e01dfa5a394</guid>
            <category><![CDATA[event-streaming]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[event-broker]]></category>
            <category><![CDATA[event-driven-architecture]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Xavyr Rademaker]]></dc:creator>
            <pubDate>Mon, 12 Jun 2023 12:04:22 GMT</pubDate>
            <atom:updated>2023-06-12T12:04:22.081Z</atom:updated>
            <content:encoded><![CDATA[<p>An overview of event services provided by AWS</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OsnRBs2890GoG4Df" /><figcaption>Photo by <a href="https://unsplash.com/@robynnexy?utm_source=medium&amp;utm_medium=referral">Robynne Hu</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In one of my previous <a href="https://medium.com/@xavyr-rademaker/peer-to-peer-choreography-and-orchestration-544af8b1bcfb">blogs</a> I discussed different event strategies, describing how communication between microservices can be designed to facilitate (work)flows in your system. However, while knowing and understanding the communication strategy is important, the blog did not touch upon the key component in an event-driven architecture: the event service. There are lots of event services out there, each with their own strengths and limitations which are important to be aware of when selecting one for your use case.</p><p>In this blog I will describe some of the different event services that AWS offers and list some of the use cases that can be fulfilled with them. The services I will cover are Simple Queue Service (SQS), Simple Notification Service (SNS), Kinesis Data Streams (KDS), Amazon Managed Streaming for Apache Kafka (MSK), Amazon MQ and EventBridge. After describing the event services, I will finish with some other streaming features AWS offers and a short wrap up.</p><p>In the context of this blog AWS services that are used to deliver events between systems and/or services will be referred to as event services, even if not officially positioned by AWS as such. At the start of each subsection, I will add a small callout to prevent any confusion. Finally, I do assume familiarity with <a href="https://medium.com/swlh/the-engineers-guide-to-event-driven-architectures-benefits-and-challenges-3e96ded8568b">event-driven architectures</a> and fundamentals of event brokers.</p><h3>Event services on AWS</h3><p>The most common AWS services that are used as event services are Managed Streaming for Simple Queueing Service (SQS), Simple Notification Service (SNS), Kinesis data streams (KDS), Apache Kafka (MSK), Amazon MQ, and EventBridge.</p><p>While all these services provide a way to get events from the producer to the consumer(s), they all have a different mechanism and feature set, making each one of them suitable for different use cases. In this section I will go over the services, describe how they work and what use cases they can be used for.</p><h4>Simple Queueing Service (SQS)</h4><p>Let us start with the Simple Queueing Service (SQS). SQS is (one of) the oldest services provided by AWS. SQS is a serverless service, meaning that you do not have to provision nor maintain any capacity. Do note that although referred to as an event service in this blog, SQS is a queueing system which means communication between services via SQS is one-to-one (no publish and subscribe functionality).</p><p>On a high level, the way SQS works is that producers can push their event on a queue, and consumers poll from it. After polling an event, the event becomes “hidden” for future polls for a set period (also known as <a href="https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-visibility-timeout.html">visibility timeout</a>) in which the consumer can process the event. After the consumer is done processing, the consumer issues a DeleteMessage call to the queue to remove the event and prevent others from re-consuming the same data. If the consumer of the event does not remove the event from the queue after the visibility timeout expires, the event will be retrieved again at the next poll.</p><p>Because it supports re-reading an event (that has not been removed) and polling by consumers we can consider SQS to be a durable queue. Furthermore, by allowing the consumers to poll, events can be processed at the pace that the consumer can handle without overwhelming it. Also, even though SQS is a queuing service, it does not guarantee ordering when using the standard queues (it provides best effort ordering). However, if ordering is really a hard requirement, FIFO queues can be used instead.</p><p>FIFO queues do provide event-ordering guarantees (except for edge cases where events that do not get processed get sent to a Dead Letter Queue). However, the throughput for FIFO queues is lower than standard queues. Standard queues have virtually no limit on throughput, while FIFO queues have a limit of 300 transactions per second, which can be increased to 3000 transactions per second (300 API calls with batches of 10) by enabling batching. Also, FIFO queues have an exactly once delivery guarantee for events produced within 5 minutes. It does so by deduplicating the messages upon arrival in the queue. The deduplication can be configured to either deduplicate based on the hash of the content (SQS will do the hashing and matching for you) or by adding a unique deduplication ID to the event.</p><p>Now you might wonder what if ordering is critical to my application, but I have a throughput higher than the values defined above? For use cases like that AWS introduced high throughput for FIFO queues! All FIFO queues can be configured to support high throughput by setting the configuration “Deduplication scope” to “ Message group” and “FIFO throughput limit” to “Per message group ID”. With these configurations set, the events will be partitioned based on their group ID. Each partition will have a maximum throughput of 3000 (with batches of 10), or 300 without batching. Also, SQS will automatically scale the number of partitions up or down as needed based on utilization. Finally, by ensuring that you have a well distributed message ID you can get the best out of this feature.</p><p>Finally, some other characteristics of SQS are:</p><ul><li>It is highly available by default. AWS stores the queues, partitions, and messages across multiple AZs within a single region</li><li>Default queues do not have FIFO ordering guarantees, instead they have a best effort ordering guarantee. If ordering is a critical factor to your application, you can use FIFO queues as these do provide ordering guarantees</li></ul><p>Although the list of supported features is quite lengthy, there are some limitations:</p><ul><li>FIFO queues have limited throughput compared to standard queues, which can be overcome by using high throughput queues</li><li>It does not support pub-sub, although SQS can be combined with SNS to enable pub-sub using the fanout pattern</li><li>A queue is a basic concept where there is a 1-to-1 relation between producer and consumer, so if you have a lot of different events in the landscape, you will likely end up with a lot of queues as well</li></ul><p>Some use cases were using an SQS queue could be beneficial:</p><ul><li>Decoupling user interaction from (batch) processing logic</li><li>Replacing already existing direct (e.g., HTTP) communication between services</li><li>The need for a buffering layer for work processing, preventing downstream services from getting overwhelmed</li></ul><h4>Simple Notification Service (SNS)</h4><p>Just like SQS, SNS is a serverless service provided by AWS. As the name implies, SNS is used to deliver notifications. Some of its prime use cases are to send push notifications to users (on their mobile phone), send emails or SMS messages. However, SNS also supports pushing notifications to other application services like AWS Lambda &amp; AWS SQS, meaning that it can serve as an event service as well.</p><p>SNS has the notion of topics to which producers can produce and consumers can consume. An event produced to a topic will be sent to all consumers subscribed to that topic (also referred to as subscribers), meaning that SNS supports the fanout pattern. However, SNS works with a push mechanism where all the events get pushed to the subscribers. This means that it does not serve as a buffering layer between services, but by combining it with SQS you can get the best of both worlds.</p><p>By default, subscribers of a topic will receive all events produced to that topic. In case a subscriber is only interested in a subset of the events, it is possible to assign a filtering policy. Filtering policies are written in Json and can be applied to both the message attributes (default), as well as to the message body (if configured). Furthermore, filters are inclusive which means that only events that match the filter will be pushed to the subscriber (see Figure 1 for an example).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5KSmJkJTHsQ36nN7ZsWc1A.png" /><figcaption><em>Figure 1: example of SNS filtering policy (taken from </em><a href="https://docs.aws.amazon.com/sns/latest/dg/example-filter-policies.html"><em>AWS documentation</em></a><em>)</em></figcaption></figure><p>Even though SNS uses a push mechanism, it does have at least once delivery guarantee with the condition that the consumers are available to push to. If a consumer is unavailable it will retry for up to 14 days (default is 4 days) until it works, otherwise it will not be delivered. This means that, even though there is a promise of guaranteed delivery, there are edge cases where events can get lost. In case you want to increase the chances of events being delivered, it is possible to configure an SQS queue to function as dead letter queue. In doing so the events that cannot be delivered can be stored in the queue for later reprocessing.</p><p>Finally, SNS does not give an ordering guarantee by default, but just like with SQS queues, it is possible to create FIFO topics which do have an ordering guarantee. These are most often used when the consumers of the SNS topics are SQS FIFO queues (since only SNS FIFO topics can push to SQS FIFO queues) and have the same ordering guarantee as SQS FIFO queues. By leveraging SNS FIFO topics with SQS FIFO queues you get both the ordering guarantees as well as the publish and subscribe functionality in your landscape. Do note that SNS FIFO topics have a lower throughput than SQS FIFO queues. SNS FIFO queues support 300 messages per second or 10MB (whichever comes first).</p><p>To summarize the use cases where SNS can be used:</p><ul><li>Send push notifications to mobile users</li><li>Send messages to users via email or SMS</li><li>Parallel processing of events using the fanout pattern</li></ul><h4>Kinesis data streams (KDS)</h4><p>The third event service on the list is Kinesis data streams. Kinesis data streams is a serverless event service, that is tailored towards processing data streams (for example log data or events). It has the notion of <em>streams</em> and <em>shards</em>.</p><p>A stream is a collection of similar events that can be logically grouped together. A stream consists of 1 or more shard(s), which are queues where all the events (also referred to as “data record” in Kinesis terms) land. A producer of an event produces to a shard within a stream. Consumers subscribe to a stream and consume from 1 or more shards. In case there are multiple replicas of a consumer, each will be assigned a certain subset of the shards (meaning that the maximum number of parallel consumers is equal to the maximum number of shards). Besides that, data consumed from a single shard will always be in order as the shards are queues. Finally, KDS supports the publish and subscribe pattern out of the box, so multiple applications can read from the same streams/shards.</p><p>KDS is a durable event service that can keep events for up to 365 days (default is 24 hours). During this period, each consumer can re-process the events if needed. Consumers do so by simply requesting the event of a specific shard at a specific index (checkpoint). However, KDS does not keep track of the latest index each consumer read last. This means that consumers are responsible for keeping track of what the next event is they should poll for. Luckily, the Kinesis Client Library (KCL) has this build in, by leveraging a DynamoDB table. Since the client is responsible for polling the events at the position they want, KDS can guarantee an at-least-once-delivery model (which is also how KCL is implemented).</p><p>KDS has two capacity modes that it can be configured: provisioned and on-demand. For provisioned mode you will have to scale the number of shards up or down manually using either the AWS management console, the CLI or one of the SDKs (or automate it using <a href="https://aws.amazon.com/blogs/big-data/auto-scaling-amazon-kinesis-data-streams-using-amazon-cloudwatch-and-aws-lambda/">CloudWatch and Lambda</a> for example). On the other hand, when using on-demand mode AWS will ensure that the number of shards will scale up or down automatically based on the data volume and traffic going through the stream. There are some differences in terms of quotas between the two capacity modes (although most of them are soft limits that can be increased by opening support tickets):</p><ul><li>By default, you can create up to 50 on-demand streams, and unlimited provisioned streams per AWS account. The number of on-demand streams can be increased by opening a support ticket.</li><li>On-demand streams do not have an upper limit in terms of number of shards, however on-demand mode has a default limit of 500 shards per AWS account in us-east-1 (North Virginia), us-west-2 (Oregon) and eu-west-1 (Ireland). For all other regions, the default limit for provisioned mode is 200 shards. To increase this limit, you can open a support ticket</li><li>On-demand streams have a default throughput of 4 MB/s write and 8 MB/s read. This will scale up automatically to 200 MB/s of write and 400 MB/s read capacity. If needed, a support ticket can be opened to increase this number to 1 GB/s write and 2 GB/s read capacity. Provisioned mode has no upper limit to the throughput, as the throughput is determined per shard. Each shard can support up to 1 MB/s or 1000 messages of write and up to 2 MB/s or 2000 messages of read capacity. If more throughput is needed, simply scale up the number of shards.</li></ul><p>If the read throughput described above is not sufficient for your use case, you can also leverage the enhanced fan-out consumers feature provided by KDS. When using enhanced fanout-consumers the read throughput increases from 2 MB/s per shard, to 2 MB/s per consumer. It also changes the interaction pattern between the consumer and the shards from polling to pushing (the shard will push data to the consumer). However, to prevent the consumers from becoming overwhelmed, there is still an acknowledgement of bytes received sent from the consumer to the shard. Whenever the consumer fails to acknowledge, KDS will stop pushing data to it until the next acknowledgement comes in. Do note: the client still needs to keep track of its checkpoint in case of scaling out or restarting the consumer.</p><p>Some final notes on KDS before looking at its use cases:</p><ul><li>Events can have a maximum size of 1 MB</li><li>KDS can be connected to Kinesis Data Analytics (KDA), for real time analytics, and Kinesis Data Firehose (KDF), for loading data into data lakes and/or analytics services</li></ul><p>Looking at the use-cases where KDS would excel, they are:</p><ul><li>Event streaming applications (for example streaming log, click or IOT data)</li><li>Data analytics ingestion platform (when combined with KDA or KDF)</li><li>Data processing pipelines</li><li>Delayed processing (up to a year after producing the event)</li><li>Applications with the need for publish and subscribe, with ordering guarantees and parallel processing</li></ul><h4>Managed Streaming for Apache Kafka (MSK)</h4><p>Next up is Managed Streaming for Apache Kafka (MSK). As the name indicates, this is a managed version of Apache Kafka, meaning that all Kafka APIs work out of the box. This makes it an excellent choice of broker if your system is already using Apache Kafka and you are migrating to AWS, or if you are using AWS currently but do not want vendor lock-in on the broker level.</p><p>Apache Kafka has the notion of <em>topics </em>and <em>partitions</em>. A topic is a logical grouping of events (like a stream in KDS), and a partition is a queue within a topic (like a shard in KDS). Events are produced to specific partitions within topics based on either the event key, a custom partitioner or randomly assigned. It is important to note that if ordering of a subset of events (for example all events of a specific user should be in order), then a partition strategy that enforces the same partition for that subset is important. Furthermore, MSK is managed. This means that the underlying resources still must be provisioned, but after provisioning they will be managed by AWS. Finally, with the default configurations MSK supports at least once delivery, but consumers can be configured to support exactly once delivery as well. Pulling this together, some use cases for choosing MSK as your event service would be:</p><p>Although there are similarities between KDS and MSK from a functional point of view (streams &amp; shards vs topics &amp; partitions), there are also some key differences:</p><ul><li>MSK is a managed service, meaning you still must provision and size the underlying resources, although the provisioned resources will be managed by AWS</li><li>The throughput in MSK is determined by the provisioned broker type instead of the number of shards</li><li>There is no maximum retention limit, events can be retained forever</li><li>The index (offset in Kafka) of each consumer (group) is stored and managed at the broker side instead of at the client side</li><li>The maximum event size is configurable to be higher than 1MB (although this is a bad idea, for big events I would recommend using the claim/check pattern)</li></ul><p>Some use case for choosing MSK would be:</p><ul><li>High throughput application</li><li>Events that need to be retained (and potentially replayed) for longer than 7 days</li><li>Producing events of big sizes (&gt; 1MB)</li><li>The needs for out of the box publish-and-subscribe support</li><li>Migrating a system that already uses Apache Kafka to AWS</li></ul><h4>Amazon MQ</h4><p>Amazon MQ is a managed event service that provides compatibility with multiple event services that use the one of the following protocols: AMQP 0–9–1, AMQP 1.0, MQTT, OpenWire, and STOMP as well as brokers that rely on API calls like JMS. Currently Amazon MQ supports two engine types, which are Apache ActiveMQ and RabbitMQ.</p><p>Although there is no explicit distinction between standard and FIFO queues in Amazon MQ, it is possible to set up ordering guarantees. This can be done by either an exclusive consumer, or by using message groups. When setting this up, what will happen is that the events will be distributed over the consumers based on the message group. As ordering is guaranteed per group, you will have the FIFO behavior. This <a href="https://aws.amazon.com/blogs/compute/implementing-fifo-message-ordering-with-amazon-mq-for-apache-activemq/">blog</a> explains in detail how to set this up.</p><p>Furthermore, as Amazon MQ is a managed service, maintenance on either the hardware, or the supported broker version can have an impact on its availability. AWS will handle all hardware updates to the brokers, and for the software maintenance you can configure it to either have them done automatically as updates become available, or to do it manually. For the automatic updates of both the hardware as well as the software, it is recommended to run the system in high availability mode, so that each AZ will get its updates once at a time, minimizing downtime.</p><p>The most frequently occurring use cases for using Amazon MQ is if you are already using RabbitMQ, Apache ActiveMQ or JMS (or similar brokers) and want to migrate to AWS with minimal impact.</p><h4>EventBridge</h4><p>The last service on our list is EventBridge, which is an evolution of CloudWatch Events. Just like SNS, EventBridge is serverless, and uses a push mechanism to its consumers. It consists of event buses (fanout) and event pipes (point to point). Each account has a default event bus, to which AWS services push events out of the box, but custom event buses can be set up as well. A custom event bus can be created for custom events (in case you do not want these mixed with the system events), but also for capturing third party events (from partner SaaS solutions like Buildkite or Datadog). Furthermore, each event bus can have up to 300 rules set up (at the time of writing). Finally, EventBridge also supports scheduled (cron-based) triggers, meaning it can serve as a serverless trigger for scheduled actions.</p><p>Event buses route the events based on user-defined rules, which are patterns defined in Json to which events can match (see Figure 2 for an example). Based on the rules, EventBridge can be configured to push the event to specific targets. These targets can be AWS services, HTTP endpoints or other EventBridge event buses. Pushing the events to other event buses is not restricted by region or account, making EventBridge a solution when events need to go cross-account (having different teams/systems on each account for example). Each rule can have multiple targets, allowing for a fanout pattern as well. Do keep in mind that event buses do not provide any ordering guarantees, so consumers should handle ordering (if needed) themselves.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w_qrY7OjXFFuhSG9YuDhEA.png" /><figcaption><em>Figure 2: Sample event with a matching event rule</em></figcaption></figure><p>Before events get pushed to their targets, it is possible to transform their format using the input transformation functionality. This can be leveraged for stripping fields from the input or masking sensitive information for example. Like the event rules, the input transformations are also defined using a Json syntax.</p><p>Besides the input transformations, EventBridge has a built-in schema registry. The schema registry can be configured to automatically detect the schema based on incoming events, but schema’s can also be predefined. Do note, the registry is primarily used to analyze the event structures coming in and to optionally generate code based on the schemas. At the time of writing, there is no validation on whether the events match the schemas build-in.</p><p>As mentioned earlier, EventBridge also has event pipes. Pipes can be used for point-to-point communication between services and provide an ordering guarantee. Like event buses, input. can be transformed and filtered before they get pushed to the targets.</p><p>Before wrapping up the section of EventBridge, the last feature I want to highlight is durability. EventBridge supports archive and replay functionality. This can be leveraged for error handling/retries for example. Just like event target routing, event rules must be created to determine which events to archive. For each rule you can also configure the retention period of the events (up to infinite if events should not be deleted). Once archived the events can be replayed based on the archive (which events), the start- and the end time. Furthermore, you can also specify which event bus and to which rules on that bus the events must be replayed to, limiting the number of consumers that the events will get pushed to again.</p><p>Use cases for using EventBridge would be:</p><ul><li>Transfer events between accounts or regions (and ordering is not a requirement)</li><li>Capture and handle system events (security monitoring for example)</li><li>Need for a schema registry to analyze the events going through the system and generating consumer code based on the schema</li><li>Need for input transformation, like masking sensitive data before it goes to other accounts</li><li>A trigger for cron jobs</li><li>Event ordering is not a critical factor in your application</li></ul><h4>Summary</h4><p>Before continuing to the other streaming mechanisms, I would like to present a summary of the event services discussed so far. This summary can be found in Figure 3.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OJaVBRFXvBM6t58XjaCdjA.png" /><figcaption><em>Figure 3: Summary of the event services on AWS</em></figcaption></figure><h3>Other streaming mechanisms</h3><p>For the last section of this blog, there are two other streaming mechanisms I would like to cover which are S3 event notifications and DynamoDB streams. Both services allow for out-of-the-box producing of events whenever something changes with regards to the items stored. While this is usually considered more of a change data capture mechanism rather than an event service mechanism, I feel like these mechanisms can be leveraged in an event driven landscape like event services (or in combination with event services).</p><h4>S3 event notifications</h4><p>S3 event notifications can be leveraged to emit events whenever something happens to an object in the S3 bucket. Some examples are new object creation, object deletion, S3 lifecycle events and restoration of events. S3 events can be configured to be sent to SNS topics, SQS queues, Lambda functions and EventBridge. Do note that for SNS and SQS, FIFO topics/queues are not supported. For SNS, SQS and Lambda, you must enable the bucket and the type of events you would like to stream, for EventBridge this is not the case as EventBridge can be configured to pick up the service events.</p><p>The S3 event notifications provide at least once delivery guarantee, however, to ensure all events are triggered it is important that versioning is enabled on the bucket. Without versioning, some events can get lost when uploading an updated version of an object to the bucket. Finally, by connecting it to SNS &amp; SQS (using the fanout pattern) this means that every update happening to the bucket can be automatically delivered to all interested consumers.</p><h4>DynamoDB streams</h4><p>DynamoDB streams work in a similar fashion to S3 event notifications in that every change made to items in the DynamoDB table is automatically added to a stream, which functions as a change log, which can be consumed by other services. However, as opposed to S3 notifications, the data streamed by DynamoDB can only be directly consumed by compute services (like AWS Lambda). To connect it to other event services, like SNS or SQS, a custom lambda connector must be added which simply consumes from the DynamoDB stream and produces to the event service.</p><p>Out of the box DynamoDB streams support publish and subscribe, as its setup is like KDS. Furthermore, instead of using the low level DynamoDB API, it is possible to add a KDS connector to the streams which will allow consumers to consume events from the stream using the Kinesis Client Library.</p><h3>Wrapping it up</h3><p>In this blog we have touched upon the various event services provided by AWS and when they can be used. If you are interested in how these services work on a deeper level stay tuned as I will write deep dive blogs on how they work &amp; how to integrate with them using lambda in the coming period!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3e01dfa5a394" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Orchestrating workflows with AWS Step Functions]]></title>
            <link>https://xavyr-rademaker.medium.com/orchestrating-workflows-with-aws-step-functions-7629e45ca2ec?source=rss-c670a3fc444b------2</link>
            <guid isPermaLink="false">https://medium.com/p/7629e45ca2ec</guid>
            <category><![CDATA[workflow-engine]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[aws-step-functions]]></category>
            <category><![CDATA[orchestration]]></category>
            <dc:creator><![CDATA[Xavyr Rademaker]]></dc:creator>
            <pubDate>Thu, 03 Feb 2022 18:53:33 GMT</pubDate>
            <atom:updated>2022-02-03T18:53:33.841Z</atom:updated>
            <content:encoded><![CDATA[<h4>Serverless orchestration on AWS</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Sw517rr1-VlBo_sdtgVF6g.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@wocintechchat?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Christina @ wocintechchat.com</a> on <a href="https://unsplash.com/s/photos/diagram?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>In my previous blog I introduced <a href="https://xavyr-rademaker.medium.com/introduction-to-workflow-engines-b0dd6e4b6628">workflow engines</a> and explained what they are, how they work and what considerations to take when deciding to use a workflow engine over custom orchestration. One of the workflow engines mentioned in that blog is Step Functions, which is a cloud-native serverless orchestration service provided by AWS.</p><p>From my experience, AWS Step Functions are good in orchestration if you’re using AWS native technology, as they seamlessly integrate with most AWS services. If you’re not using an AWS native landscape don’t worry, there’s plenty of vendor agnostic alternatives out there. In this blog I will discuss what AWS Step Functions are, how to define, execute and monitor your workflow using AWS Step Functions and how it can be monitored.</p><h3>What AWS Step Functions are</h3><p>AWS Step Functions is a cloud-native workflow engine provided by AWS. It’s serverless, meaning that all infrastructure is managed and provisioned by AWS. All we must do is define our workflow using Amazon’s state language (ASL, a JSON-based language), provide some configurations, and run our workflow. Note that a single workflow is also called a “state machine” within AWS.</p><p>There are two types of workflows that can be defined:</p><ul><li>Standard workflows</li><li>Express workflows</li></ul><p>Standard workflows are used for long-running workflows which are durable and auditable. Their history is preserved for 90 days after the workflow run and they employ an at-most-once delivery model, meaning that your tasks/states are never executed more than once (unless explicitly specified as we’ll see later in this blog). Furthermore, a standard workflow can run for at most one year (a single run), supports a lot of service integration patterns (more on this later) and is billed per state transition.</p><p>Express workflows are more suited for high-volume event processing (for example IOT data ingestion, which gets triggered very often but doesn’t take a lot of time to process). They can only run up to 5 minutes and employ an at-least-once model. This means that every state in your workflow (or even the workflow as a whole) is guaranteed to be executed once but can potentially be executed more than once. Because it can be executed more than once, everything you’ll orchestrate using express workflows should be idempotent (able to be executed more than once with the same inputs without leaving the system in an inconsistent state). They are billed by the number of executions, duration of the execution and the memory consumed.</p><p>For more details on the differences between the two types of workflows, I would recommend going through the AWS <a href="https://docs.aws.amazon.com/step-functions/latest/dg/concepts-standard-vs-express.html">documentation</a> on the subject. For the remainder of this blog, I’ll focus on standard workflows as this is suited for most use cases. Also, after understanding how standard workflows work it’s relatively easy to work with express workflows.</p><h3>Defining a workflow</h3><p>Now that we understand what Step Functions are let’s dive into how they work. I’ll start by going over the building blocks of a state machine, followed by managing input and output parameters and error handling. I’ll end with explaining the execution of a state machine, including the different approaches to do so.</p><p>There’s two ways to define a workflow within Step Functions. The first is by defining your workflow in code using the ASL, the second is to drag and drop your workflow using the visual editor. I’ll start by explaining how to do it in code. Since the visual designer is also based on the ASL, understanding the foundational code before leveraging the designer can be helpful in your understanding of Step Functions.</p><p>Let’s start by explaining how workflows can be defined using the ASL. As with all things code, the first thing we’ll create is a simple Hello world workflow to show the basic workflow definition:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/870/1*I1-fida4j76MAj_u3MObsA.png" /><figcaption>Figure 1: Hello world workflow defined in ASL with visual result</figcaption></figure><p>Let’s go over some of the keys in the example above. The first thing we add is a “Comment”. Comments are optional and can be added to each step to clarify what’s supposed to happen. It’s always good to add comments and keep them up to date so that other developers (and you in the future) knows what the intent of the code is.</p><p>The second line is an important one, it’s the “StartAt” key. StartAt determines which state we should start with, denoting the first step in our workflow. Finally, there’s the “States” key, whose value is a dictionary containing all states (different steps/tasks) of this workflow. Note that you can put your states in any order you like, as the order does not impact the validity of the workflow and each state refers to its successor by name. However, for maintainability purposes I would recommend keeping your states in chronological order, which makes it more natural to read, understand and maintain.</p><p>Each state is an element in your workflow. There are multiple types of states, which are denoted by the “Type” key. Besides the “Type”, they can have the optional “Comment” key and must have either an “End” key (with “true” as value, indicating that this is the last state of the flow) or a “Next” key (with the name of the next state as value).</p><p>The types of states can be divided into two categories: “Flow” states and “Action” states.</p><p>Flow states are steps that don’t perform any work, instead they are used to define special types of flows, like branches or loops. The following flow state types are present in Step Functions at the time of writing:</p><ul><li>Choice: add if-else (if) logic, allowing the workflow to branch out based on a condition</li><li>Parallel: add parallel branches, all states within the parallel state are executed in parallel</li><li>Map: adds a for-loop, iterating over the input of the state</li><li>Pass: Do nothing, can be used to add transform results or as a placeholder for future functionality</li><li>Wait: add a delay for a specified time</li><li>Success: Stop and mark the workflow execution a success</li><li>Fail: Stop and mark the workflow execution as failure</li></ul><p>Action states on the other hand are steps that perform work. All of them have the state type “Task”. Tasks can be used to delegate the work to other services, for example: Invoke a Lambda function, start an AWS Glue job, publish an event to SNS, start the execution of another step function. Recently AWS also added the possibility to perform API calls on AWS services directly from step functions using tasks, for example to perform an S3 CopyObject or even create an IAM policy.</p><h4><strong>Using and manipulating input parameters</strong></h4><p>Defining a static workflow is one thing, but we often want to parameterize it so that it can act based on the inputs (or outputs of previous steps). Whenever we start an execution, we have the possibility to provide a JSON as input. For example:</p><pre>{<br>  &quot;hello&quot;: &quot;world!&quot;,<br>  &quot;foo&quot;: {<br>    &quot;bar&quot;: &quot;baz&quot;<br>  }<br>}</pre><p>We can access this input using the “<em>$</em>” symbol (so <em>$.hello</em> would access the hello variable) and pass it to our steps, for example when invoking a Lambda.</p><p>There are a lot of cases where the provided input isn’t structured in a way that all steps can use it. For such cases AWS Step Functions provides us with two keys to manipulate the input:</p><ul><li>InputPath: used to select a subset of the input of a step</li><li>Parameters: used to manipulate the format of the input and pass task specific configurations to an action</li></ul><p>Let’s start with the most straightforward one. As mentioned, the InputPath is used to select a subset of the provided input to a step, discarding everything except for that specific path. An example of how this works can be found in Figure 2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*tPSHCG0YtvQRVq0bAQIlCQ.png" /><figcaption>Figure 2: Example of input manipulation using the InputPath</figcaption></figure><p>Although this works quite elegantly, there are scenarios where we need more control over how we structure the inputs to our step. If our Lambda expects the input to contain all provided information in a flat structure, we need to do more to the input JSON than just select a subset. To facilitate this there is the “Parameters” key, which allows us to manipulate the input structure. Figure 3 shows how this can be used, note that the “structure” field is populated using a hardcoded value for example purposes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*5ZDXnHDuYAE9afOqQr28wQ.png" /><figcaption>Figure 3: Manipulating inputs using the Parameters.</figcaption></figure><p>Next to transforming the input structure, the “Parameters” key is also used to give extra configurations to actions, for example specify the bucket and object to copy with the S3 CopyObject action.</p><h4><strong>Using and manipulating output parameters</strong></h4><p>Besides the input provided when executing a workflow, we can also leverage the output of steps as input to steps that come after it. By default, the output of a step overrides its input data, essentially replacing the “$” variable. Even though this can be beneficial in some cases, often we want to have more control around this. Luckily, we can do so with the following 3 keys:</p><ul><li>ResultPath: can be used to combine the steps input with its result</li><li>ResultSelector: manipulate the step result to a structure more beneficial to us</li><li>OutputPath: take a subset of the output of a step (after ResultPath and ResultSelector have been applied)</li></ul><p>The ResultPath key is used to prevent the result of a step from overriding our previous inputs. Instead, we can define a path within our input where the result should go, combining the two. It does so by specifying on what path of the input the result should go. Also, if we don’t want to use the output of a step at all, we can disregard it by setting the value of ResultPath to null. Figure 4 provides an example of the ResultPath, showing both the input and result of the step and what the result will be after applying the configuration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/906/1*TJsAn8TGY5BcB5Wvanw1lw.png" /><figcaption>Figure 4: example of the ResultPath configuration, combining in-and outputs</figcaption></figure><p>Looking at the result above there’s parts in there that we might not be interested in, like the statusCode field and maybe we even want to flatten out the rest. To get a cleaner output we can leverage the ResultSelector. The ResultSelector allows us to restructure the steps result completely to our desire, even adding extra information if necessary. Figure 5 provides an example of how this would work, combined with the ResultPath of before.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/906/1*6BpqoEmNnUAwnz8tI3U4pg.png" /><figcaption>Figure 5: Extending our ResultPath example with the ResultSelector</figcaption></figure><p>Finally, the last configuration we can use to manipulate the output of a step is the “OutputPath”. The OutputPath key works like the InputPath in that it’s used to select a subset of the output to continue with. However, as the name implies, it operates on the output of the step (note that output comes after the result parts, meaning ResultSelector and ResultPath go before OutputPath). Figure 6 provides the last example on how this works, combining the ResultPath, ResultSelector and OutputPath in one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/884/1*mGCd0l-BatTZDtYSKTmziA.png" /><figcaption>Figure 6: Combining ResultPath, ResultSelector and OutputPath to have full control over our output</figcaption></figure><p>There are two special cases where the output differs: the Map and Parallel types. Since these perform multiple tasks within them (the explanation above holds for each task in it), they will both output a list containing the full output per iteration/branch.</p><p>As you can imagine, by combining InputPath, Parameters, ResultPath, ResultSelector and OutputPath we have full control over how we want to structure and format our inputs and outputs per step. While defining your workflow, you can leverage the <a href="https://aws.amazon.com/blogs/compute/modeling-workflow-input-output-path-processing-with-data-flow-simulator/">data flow simulator</a> to model the inputs and outputs. This tool can help setting the right configurations to manipulate the inputs and outputs to your needs.</p><h4><strong>Error handling</strong></h4><p>As with all things in life, the task states (actions) can fail. Luckily, AWS Step Functions has built in ways to deal with these issues, namely retries and catches.</p><p>The Retry configuration allows us to define the retry behavior upon failure. This can be configured to behave differently on different exceptions (for example: Retry once for a ServiceException but retry 3 times for a SdkClientException). Per retry we can specify the following:</p><ul><li>IntervalSeconds: how many seconds to wait before retrying the first time</li><li>BackoffRate: multiplier with which the interval seconds increases with every attempt</li><li>MaxAttempts: maximum attempts before calling it a failure</li></ul><p>Do make sure that the task you are trying to execute is idempotent when adding the retry behavior. If this is not the case your state after retrying might end up being corrupted/inconsistent.</p><p>While retries are great for handling intermittent failures (think of network glitches, API throttling limits etc.), sometimes things simply fail due to bugs (or to be implemented features as I like to call them). In such cases we can also decide to handle the error more gracefully than just a hard failure using the catch configuration. Catch allows us to branch out to unhappy flows based on a thrown exception. Just like with the retry configuration, you are free to define multiple branches based on specific exceptions. This is handy if we want to do a cleanup after failure, or maybe send an email to our users notifying them that their input wasn’t proper or any other scenario you can think of where graceful error handling is needed.</p><p>Note that both retry and catch can be combined for a single step (either for the same exception, or for different exceptions). For example, we can say if an API throttling exception is thrown, retry it 3 times first with 3 seconds interval and a backoff rate of 2.0. After 3 times catch the exception, cleanup any processing done so far and send an email to the team managing the API before failing the step function.</p><h4><strong>Defining the workflow using the visual editor</strong></h4><p>As you can probably imagine, knowing all the different configurations for all the different tasks can become quite complex. Also, the JSON definition can grow quite big as well, even for relatively small workflows. To cope with this complexity, AWS provides a visual workflow designer in which you can drag and drop your workflow. I haven’t used it that extensively, but from what I’ve seen so far it works quite well and it’s quite easy to get started with since most configurations for each type of flow/action is well documented.</p><h3>Executing a workflow</h3><p>There are multiple ways to execute our workflow, the simplest being doing it manually. You can start a step function manually via the management console (by pressing the “Start execution” button or by using the AWS CLI to with the <a href="https://docs.aws.amazon.com/cli/latest/reference/stepfunctions/start-execution.html">start-execution</a> command.</p><p>Of course, doing it manually is great for testing and for some production systems, but often we want to automate the start of our workflow, for example whenever the user makes a request, or a file is uploaded to S3. Luckily for us, this is possible as well. Executions can be started using the AWS SDK (via Lambda, or some other service), via the <a href="https://aws.amazon.com/api-gateway/">API Gateway</a> (trigger by HTTP request), via <a href="https://aws.amazon.com/eventbridge/">EventBridge</a> rules and, as mentioned earlier, via other workflows.</p><p>Every step function execution has a unique “name”, which is either a generated UUID or a name provided by you when starting the execution. It’s important that the name is unique for the specific workflow, since the history of that run can be retrieved using this name (it’s not even possible to re-use the same name twice as the console won’t allow it and the cli will just return the old run’s response). Next to the name of the execution, it’s also possible to provide input parameters to the execution when starting it.</p><h3>Monitoring and reporting</h3><p>After our workflow started, we still need to monitor it to make sure it runs well. The act of monitoring and reporting on our workflows can be done in two ways: automated monitoring and manual. Since it’s best practice to automate as much as we can, I’ll start with the automation, followed by how to do it manually (for debugging for example).</p><h4>Automated monitoring and reporting</h4><p>I always recommend implementing passive monitoring tools to have the system tell us about its progress, essentially automating part of the operations. To do so, we can set up the following:</p><ul><li>Alarms on failures (or success if you want to be notified by that as well) using EventBridge events with SNS for notifications</li><li>Use the CloudWatch logs to create dashboards (number of success/failures, average time per step etc.)</li><li>Use the SDK to extract more details about the run and visualize it in dashboards</li></ul><p>The first option in the list is to enable notifications based on the completion of your execution. This can be based on both successes as well as failures based on your needs, but I would recommend to at least have it enabled for failures. Getting these notifications can be done using a combination of EventBridge rules/CloudWatch events together with SNS to send out emails (or whatever form of notification you’d like). Figure 7 shows how this can be set up.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/882/1*UHhOvQDN93tf8JdMvG_JJA.png" /><figcaption>Figure 7: Setting up notifications using EventBridge and SNS</figcaption></figure><p>Besides getting notifications, creating dashboard can also be useful for reporting purposes. Instead of checking every single execution, we are often interested in aggregated overviews for reporting our performance, SLA management, etc.</p><p>We can automate our reports using two approaches. The first is using the metrics and logs already available in CloudWatch to visualize our aggregated information in a dashboard (either CloudWatch dashboards, or if we want to do more customizations use something like QuickSight or another dashboarding tool). This can be used to report things like number of successes/failures, average time taken per step, etc.</p><p>The second approach, which is an addition to the information we get from CloudWatch, is that we can extract more custom information from our workflow executions in an automated way using either the CLI (write custom scripts) or using the SDK (programmatically extract more information about the step function run). This extra information can be used to enhance our dashboards and/or reports without us having to actively do anything (except for setting it up of course). From the CLI we can use the <a href="https://docs.aws.amazon.com/cli/latest/reference/stepfunctions/get-execution-history.html#get-execution-history">get-execution-history</a> command, and from the SDK we can use the <a href="https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/stepfunctions.html#SFN.Client.get_execution_history">get_execution_history</a> method (using boto3 for Python, for other languages the method name might differ). Just like the notifications, we can leverage EventBridge events together with Lambda to automate the extraction of these custom metrics.</p><h4>Manual monitoring</h4><p>Now that are reports and notifications are set up, we also need to know how to get more information on the progress manually, for example to get more details on what went wrong after we’ve received a failure notification. To do this, AWS Step Functions provides us with a few things:</p><ul><li>The UI gives us up-to-date visuals on how our workflow is progressing</li><li>Cloudwatch logs can be used to provide us with details on the progress and error messages</li></ul><p>Let’s start with the first one. After we start the execution of a state machine (regardless of how we started it), AWS provides us with a visual update on its progress. The UI will show the full state machine, where each step can have one of the following colors:</p><ul><li>White: step has not been started (yet)</li><li>Blue: step is currently being executed</li><li>Green: step has completed successfully</li><li>Red: step has completed unsuccessfully; some exception was thrown that has not been caught</li><li>Orange: step has completed unsuccessfully; the thrown exception has been caught</li></ul><p>By simply watching the UI, we can track the progress of our execution. Also, by clicking on each step we can get a detailed summary of its inputs, outputs, time taken to execute the step and, if anything fails, details on the exception. All of this together give us a lot of information about what is happening in more details. Figure 8 gives an example on how this progress is visualized.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*hLxDgK8vMe5kMEEV80gV5A.png" /><figcaption>Figure 8: example of our execution’s progress in the UI</figcaption></figure><p>The second approach mentioned is using the CloudWatch logs to monitor progress. When enabled, and I recommend you enable it, all our execution logs will be written to CloudWatch as well. Actively looking at the updates through the logs can be useful in case you don’t have access to view the execution directly (due to legal/compliance reasons for example). The CloudWatch logs will provide similar information as the UI in terms of progress, successes, and failures.</p><h3>Lessons from production</h3><p>Before wrapping it up I’d like to share some of the lessons I’ve learned from running AWS Step Functions on production, which can help ease your developments and maintenance of your workflows in the future.</p><h4>Split big state machines in multiple smaller state machines</h4><p>When defining your workflow, the ASL can become big. This is due to all the configurations that can be added, and of course all the whitespaces/indents that come with the JSON syntax (often added for readability purposes). At some point your workflow will become unmaintainable simply due to its size. Just imagine having to remove 1 block from a JSON document with over 2000 lines, trust me the indents and forgotten brackets will be something to cry about at that point (speaking from experience here). Instead, try separating your state machine into multiple smaller state machines which are also easier to manage (for example, if you have one Parallel state with X tasks inside, followed by a Map state with Y tasks inside: create 1 state machine for the Parallel and 1 state machine for the Map). Since state machines can start other state machines (and await their result) you can simply add a “main” state machine which calls all the smaller ones in order.</p><p>There are two big benefits to splitting a big state machine into multiple smaller ones:</p><ul><li>Making this split results in multiple smaller files which are often easier to update and keep you sane, whilst retaining the order of your workflow through the main state machine</li><li>It’s easier to change and adapt individual child-step functions as long as its inputs and outputs remain the same. Using the example above, we can easily change the whole content of the Parallel child state machine (making it another Map or sequential or whatever) without affecting the bigger flow</li><li>Multiple files means that multiple people/teams can work on the workflow without interfering with each other if the inputs and outputs remain the same</li></ul><p>Of course, there is a downside to this approach as well, which is that if inputs/outputs change, the change must be made in multiple places (at least the main step function providing the inputs/receiving the outputs and the child step function in which the change has been made). Also, understanding all details of the full workflow means going over multiple files. Do keep these drawbacks in mind when finding the right balance for the split of your big workflow.</p><h4>Be specific in what errors to retry</h4><p>Even though it can save a lot of time just retrying on the general exception (catch all) and continue happily with our lives, I wouldn’t recommend doing so. The first obvious reason is that if your task isn’t idempotent, retrying on an error after saving means that your data is written twice after the retry. Now you might think, we can simply just make our tasks idempotent and then do the retry on all exceptions right? You can of course, but you probably still don’t want to and here’s why. If your task fails on a bug (think of a null pointer exception for example), retrying it 3 times won’t make a change as the issue won’t just magically disappear from your code (oh how much I’ve wished for this). Meanwhile the retry attempts will cost you resources which could either be saved or used for something else (that’s not failing). Therefore, it’s good practice to retry only on the errors that can be caused by unfortunate events, rather than bugs in code (network hiccups, API throttling etc.).</p><h4>Be careful with errors in parallels and (concurrent) maps</h4><p>Whenever a step fails due to some exception that has not been caught, the state machine execution will fail. This failure has been implemented a fail-fast approach, which is helpful as you probably don’t want to waste any resources if your system failed. However, there is one scenario where this can be risky. Whenever a Parallel or a Map with concurrency enabled is running and 1 of the tasks fails, this fail-fast approach will kill all other tasks that are running. Since these other, non-failing, tasks get killed mid-way, there is a chance they will leave your system in an inconsistent state (for example, they wrote 3 out of 5 files, then get the kill signal) or even a corrupted (tasks has written half a file and got aborted) which can be problematic. There are however a few ways to deal with this issue.</p><p>The first, and probably most important one, is to make your tasks idempotent. After fixing the issue you can simply run the full state machine again with the same parameters, leaving the system in a consistent state after the second run. Of course, this means that in between the first and second run the system is inconsistent. Depending on the type of system this can or cannot be acceptable. In case of partial files/writes this solution can still lead to a corrupted state.</p><p>A second solution is to catch all exceptions for all tasks within the map or parallel and lead them to a pass state. By catching the error, the task won’t be marked as failed (but as caught instead) and all other non-failing jobs will continue as usual. After all tasks in the map/parallel have succeeded, add another map containing only a choice step. This choice will check the output of the map/parallel to see if it contains any error messages. If so, perform a cleanup of everything that’s inconsistent/failed and call a “fail” state afterwards, marking the state machine run as failed. This approach is more time/resource consuming since the cleanup will only happen after all tasks have succeeded but will guarantee a consistent and uncorrupted state afterwards.</p><p>The final solution I will discuss is to have all your tasks be transactional. This way, both the failed as well as the aborted tasks will revert to their previous state before shutting down. Of course, this too has its drawbacks where guaranteed consistency comes at the cost of availability in distributed systems (check out the <a href="https://towardsdatascience.com/cap-theorem-and-distributed-database-management-systems-5c2be977950e">CAP-theorem</a> and <a href="https://phoenixnap.com/kb/acid-vs-base">ACID vs BASE</a> for more on this). Also, since the tasks run independently of each other in a map/parallel, there’s no guarantee that a task hasn’t finished already before the first issue. In such scenario no kill signal is given (as the task already finished) so no revert is happening for that specific task.</p><h4>Pass the execution name to each task</h4><p>I mentioned earlier that whenever you start your execution, you can provide a unique execution name (or it will be a random UUID if nothing is provided). It is recommended to use pass this execution name to all your tasks as an input parameter and use it in the logs of the executing services. By adding this to all logs, tracing what happened with a full execution is easier (filter on the execution name). During one of my projects, we even went a step further, and not only passed the execution name to all tasks, but also added it to the data we stored. This way we could trace back every row of data to a specific execution, giving us full traceability in what happened where whenever something went wrong. Do be sure that your execution name is not anything sensitive when propagating it to all tasks as we don’t want to have sensitive data in our logs.</p><p>In case you’ve split up your step function into multiple smaller child step functions, orchestrated by a main parent step function, I’d recommend using the main parent step function’s execution name if present, otherwise if it’s not present, use the child step function (in case the child was run in isolation for some reason). Since the parent step function spans multiple step functions, each with their own tasks, this will allow you to trace the full flow of an execution of your workflow using a single ID. Note that this does mean that the parent step function execution name needs to be passed to all children and then to the tasks within the children to ensure consistency.</p><h4>Version the ASL using version control</h4><p>I would always recommend putting the resulting ASL in a version-controlled repository, as this can be used to go through the peer-review process as well as preserve historic versions. When using the visual designer, which is only present in the management console, we can’t really version control it. Luckily the designer does output its results as the ASL, so even when designing your state machine using the designer, we can copy its result and put it in version control. Also, even though the designer really helps, as the state machine grows bigger, making small changes (like changing the order/links of steps) is probably easier to do directly in the ASL.</p><h3>Wrapping it up</h3><p>That wraps up this blog on AWS Step Functions. We’ve covered what they are, how to define and execute them, how to monitor and some tips and tricks to help you along the way. This should give you everything you need to start running your first workflow on AWS. Before finishing, I’ve created a <a href="https://github.com/Xavyr-R/aws-step-function-examples">repository</a> with multiple examples of everything I’ve discussed during this blog which you can use for more practical examples. I hope you liked it and stay tuned for future blogs!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7629e45ca2ec" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to workflow engines]]></title>
            <link>https://xavyr-rademaker.medium.com/introduction-to-workflow-engines-b0dd6e4b6628?source=rss-c670a3fc444b------2</link>
            <guid isPermaLink="false">https://medium.com/p/b0dd6e4b6628</guid>
            <category><![CDATA[event-driven-architecture]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[workflow-engine]]></category>
            <category><![CDATA[orchestration]]></category>
            <dc:creator><![CDATA[Xavyr Rademaker]]></dc:creator>
            <pubDate>Sun, 14 Nov 2021 12:56:16 GMT</pubDate>
            <atom:updated>2021-11-14T12:56:16.201Z</atom:updated>
            <content:encoded><![CDATA[<p>Orchestration as a service</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*6J8JzNdD_3Md8IotEUhvxw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@campaign_creators?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Campaign Creators</a> on <a href="https://unsplash.com/s/photos/workflow?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>My colleague Oskar uit de Bos recently started a blog series on ‘an engineer’s guide to event-driven architectures’. In the <a href="https://medium.com/swlh/the-6-things-you-need-to-know-about-event-driven-architectures-38e11fdcb5a">second addition</a> of this series he mentioned that one of the important skills to master to get the most out of event-driven architectures is being able to design business workflows using events. In a follow up blog, where I explained the differences between <a href="https://xavyr-rademaker.medium.com/peer-to-peer-choreography-and-orchestration-544af8b1bcfb">peer-to-peer choreography and orchestration</a>, I explained that while peer-to-peer is a logical starting point for simple flows, orchestration is much better at handling increasing complexity in event flows when dealing with unhappy flows, retries, SLA monitoring, sending out reminders etc.</p><p>Besides managing the flow of commands and events, an orchestrator can also be leveraged to trigger unhappy flows. Think about retrying on error, send reminders when a manual step in the flow has been pending for too long, act on timeouts etc. Having to deal with both the happy flows, as well as all unhappy flows can soon lead to a very complex microservice. While it’s viable to build an orchestrator from scratch, as complexity grows it’s worth looking at readily available workflow engines so you can focus on coding your business specific logic.</p><p>In this blog I will explain what a workflow engine is, how they work, considerations to take when choosing between custom orchestration and a workflow engine and I will end the blog by listing some common workflow engines. Note that this blog is just an introduction to workflow engines, in follow up blog(s) I’ll dive deeper into the implementations of various workflow engines.</p><h3>What are workflow engines</h3><p>Let’s begin the introduction by understanding what workflow engines are. To do so, I’ll first explain what a workflow is as this is the foundation of a workflow engine. After we understand the workflow, I’ll continue to explain concept of a workflow engine.</p><h4>Workflows</h4><p>When googling the term workflow, you’ll come across various similar definitions. For example, the Wikipedia definition states:</p><blockquote>“A workflow consists of an orchestrated and repeatable pattern of activity, enabled by the systematic organization of resources into processes that transform materials, provide services, or process information. It can be depicted as a sequence of operations, the work of a person or group, the work of an organization of staff, or one or more simple or complex mechanisms.”</blockquote><blockquote><strong>—</strong> <a href="https://en.wikipedia.org/wiki/Workflow"><strong>Wikipedia</strong></a></blockquote><p>Looking at this definition, we can see that there are a few key elements in there. The first being that it is a <strong>series</strong> of <strong>repeatable</strong> activity (referred to as tasks in the future), meaning that it consists out of multiple tasks that occur in a certain sequence frequently within your organization (or system). Secondly, the sequence of tasks processes a set of data, each step taking something as <strong>input</strong> and giving some <strong>output</strong> after the task is done. Finally, the workflow must lead to a certain goal.</p><p>Even though the definition might hint that the tasks in a workflow are all sequential, there can always be tasks that happen in parallel. If two tasks have the same inputs and can operate independently of one another there’s no reason for them not to start processing in parallel. Furthermore, a workflow can also branch out into multiple sub-flows all leading to a different outcome based on their inputs.</p><p>Let’s look at an example of a workflow which has a clear series of tasks, has a goal, and is used frequently within an organization. We’ll use a bank providing loans to their customers as the example. Whenever a customer requests a loan, a sequence of tasks take place to determine whether the client is eligible for the requested loan, and to be sure that the client isn’t a criminal. This sequence of events can have three different outcomes:</p><ol><li>If a customer fails in meeting the minimum KYC requirements, banks will have to right to refuse to open the account or to terminate the business relationship with that customer.</li><li>The client is not eligible for the requested loan: The client gets informed that he can’t get the loan</li><li>The client is eligible for the requested loan: A contract will be sent to the client so he can sign off on the terms and agreements before providing the loan</li></ol><p>Figure 1 provides two different examples on how this workflow could be implemented. One option is sequential (where of course the order of the checks could be switched around), another option is the checks are executed in parallel and their combined results are processed afterwards. Furthermore, we can see that our workflow branches out to different results based on the outcome the checks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*-6uRzyVpW0iYmDGnu5d9QA.png" /><figcaption><em>Figure 1: an example of the loan request workflow</em></figcaption></figure><h4>Workflow engines</h4><p>The loan request workflow discussed in the previous section is a workflow that is automated by a lot of banks. Similarly, other companies in different sectors have their own automated workflows. For example, you could think of the order-to-delivery workflow of e-commerce companies, encoding and transcribing movies at streaming services, processing batches of data in data processing companies, and the list goes on.</p><p>All these companies have faced a similar challenge at some point (and so will you once you start building such a system): “how do we ensure that our system follows the defined workflow?”. Building your own orchestrator sounds very tempting to start with, as the workflow tends to start off quite small and simple. You just add a new microservice to your landscape and make it responsible for the order of execution of your workflow by storing the progress of each task in some form of storage and triggering the next step when all criteria are met for it to start.</p><p>As the system matures, the workflow grows in terms of size as well as complexity and before you know it, you’ll spend more time maintaining your orchestrator than you are building the new tasks in your landscape. This is where workflow engines come into play. A workflow engine is essentially an “Orchestrator as a service”. To prevent developers from spending so much time in orchestrating their microservices to cope with complex workflows, the workflow engines handle all complexity that comes with orchestration internally and provide you with a simple way to define and update your workflow(s).</p><h3>How workflow engines work</h3><p>Now that you know what workflow engines are you might realize that they are essentially just orchestrators, so how are they relevant for me? The answer is quite straightforward: because it requires less effort. Every workflow engine is a tool developed by different organization/team, so it should be no surprise that all of them have their own implementation. However, on a high level most of them work quite similar.</p><p>Generally, the first step in working with a workflow engine is defining your workflow in some declarative format. Some engines use a JSON like structure, others use REST (which comes down to JSON as well), some expose a library which allows you to code the order in which steps should be executed and the API will take care of tracking progress and unhappy flows, and the list goes on. The workflow definition contains all steps/tasks that need to be executed, together with their order (sequential, parallel or both) and they can even hold placeholders for input parameters for each step/task. Note that these steps do not necessarily have to be automated, they can be manual steps as well. Furthermore, in the workflow definition you can also define what to do on failure like retry errors, deal with timeouts.</p><p>After the workflow is defined, the next step is to run it. How/when to start a run is entirely up to the design of your system. It can be triggered manually, time based or automatically whenever something happens (for example if a user uploads a file, start the workflow). Because every workflow engine is different, the technical implementation differs per engine, but here too most workflow engines make use of known approaches like for example REST or a library call. I mentioned before that the defined steps can have input parameters. One way to provide those is as input parameters to the workflow run. Another option is to use the output of the previous step as input to the next.</p><p>After you’ve started a workflow run, it will go start at the first step in the definition and execute it. Once it finishes, the next step will start to run automatically. Some workflow engines even provide an interactive UI in which you can track the overall progress of the run. Also, all unhappy flows defined in the workflow definition are also handled automatically. This means that if you have defined a retry mechanism for a step, a failure in that step will be retried automatically.</p><h3>Considerations to decide between workflow engines or custom orchestration</h3><p>After reading the previous sections, you’re probably wondering whether you should even consider writing your own orchestrator if you can just use a workflow engine to reduce the work for yourself. However, as with all things in system architecture, it highly depends on the use case you are trying to solve, as well as the situation you are in. In this section I will provide a few considerations to consider when deciding whether you should build your own orchestrator or invest in adding a workflow engine to your landscape.</p><h4>The system’s lifecycle</h4><p>In the early stages of a system’s lifecycle, you’re often validating a new business idea or some form of a concept. The focus is being nimble and achieving quick iterations. If this is your project, strongly consider coding the orchestration to keep the overall system as simple as possible and the knowledge threshold for new engineers to onboard low.</p><p>In later project states where the focus shifts from iterating to scaling and industrialisation, then look at the benefits that a workflow engine could bring. The obvious exception to this advice would be concepts that need a highly sophisticated workflow from the get-go.</p><h4>Complexity of the workflow</h4><p>Another consideration to consider is the complexity of existing workflow and future developments on the known roadmap. As stated earlier, introducing a workflow engine often means introducing a new component to your system. With this come, hopefully obvious, investments:</p><ul><li>In requires the existing engineers to get familiar with the engine.</li><li>It increases the learning threshold to get new engineers productive.</li><li>It increases operational cost, either directly if a managed service is used or indirectly as it increases operational complexity of the system</li></ul><p>For that total cost of ownership to make sense, you either need to have or anticipate having complex workflows that would cause a significant maintenance burden on your teams or require significant development effort to build the appropriate feature-set for.</p><h4>Customisability and constraints</h4><p>Even though, in general, workflow engines allow you to define your specific workflow it remains a product developed by others that is designed to be used within certain constraints of its design philosophy. Which is fine if it matches properly with your problem domain, but if it doesn’t it will cause friction and frustration and results in workarounds that decrease overall robustness and scalability.</p><p>This also applied to future constraints. If possible, look at the roadmap and community communication around a workflow engine to ensure that their roadmap aligns with your future needs.</p><h4>Keep orchestration and tasks properly decoupled</h4><p>Looking at the reasons behind the investment decision, it’s not unlike that a significant portion of teams will start building their own orchestration while monitoring the investment tradeoffs as complexity grows. Replacing components in a system, and the associated refactoring needed, is often costly.</p><p>By having a discipline approach to building your own orchestration, you can reduce the replacement costs significantly. This is done by making sure your orchestration is decoupled from your tasks. In the implementation of your tasks should always be fully workflow unaware and completely ignorant of the overall goal of the workflow. It takes some input, does what it needs to do, and either fails or provides output. All orchestration concerns like state management, retries, notifications etc. should be fully isolated from this. If you start entangling these concerns, it will make migrating to a workflow engine, or a different workflow engine for that matter, more costly.</p><h3>Common workflow engines</h3><p>Before concluding this blog, I would like to present a small list of workflow engines to send you off with. As each of them could fill in a blog of their own, I will just list them and give a brief sentence or to highlighting their implementations.</p><ul><li><a href="https://aws.amazon.com/step-functions/?step-functions.sort-by=item.additionalFields.postDateTime&amp;step-functions.sort-order=desc">AWS Step functions</a>: A cloud-based workflow engine managed by AWS. Workflows are defined using a JSON like syntax or using the visual editor, and the service offers a visual representation of your definition. Executions, which are also visualized, can be triggered manually, or via events.</li><li><a href="https://docs.microsoft.com/en-us/azure/logic-apps/logic-apps-overview">Azure Logic Apps</a>: A cloud-based workflow engine managed by Azure. Workflows are defined using a JSON like syntax or using the visual editor, and the service offers a visual representation of your definition. Executions, which are also visualized, can be triggered manually, or via events.</li><li><a href="https://cloud.google.com/workflows">Google Cloud WorkFlows</a>: A cloud-based workflow engine managed by Google Cloud. Workflows can be defined in either YAML or JSON format. Furthermore, the orchestrator uses HTTP to interact with the tasks.</li><li><a href="https://netflix.github.io/conductor/">Netflix conductor</a>: Netflix Conductor is an open-source workflow engine created by Netflix. It uses REST to define, update and start workflows (make rest calls to the engine with your workflow defined as JSON). It provides a GUI to track progress of an execution and it provides libraries for multiple programming languages which can be used to implement the integration layer on your tasks.</li><li><a href="https://airflow.apache.org/">Apache Airflow</a>: Apache Airflow is an open-source workflow engine created by Airbnb. It allows users to create their workflow definitions using Python code. The workflow can be executed based on a specified time interval (Cron based) or by an external (or manual) trigger (via the cli or web UI for example). Airflow also provides a UI in which you can monitor the progress of an execution</li></ul><p>Of course, there are more workflow engines around than I can possibly list in this blog. For example, on <a href="https://github.com/meirwah/awesome-workflow-engines">this GitHub</a> page a list of open-source workflow engines has been made.</p><h3>Wrapping it all up</h3><p>That concludes this blog on workflow engines, I hope that the concept of workflow engines is now clear to you and, more importantly, that you understand what to consider when deciding whether to use one over custom orchestration. Stay tuned for future blogs where I will dive deeper into some of the workflow engines mentioned earlier in this blog, with some practical examples.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b0dd6e4b6628" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dealing with long-running jobs using Apache Kafka]]></title>
            <link>https://medium.com/codex/dealing-with-long-running-jobs-using-apache-kafka-192f053e1691?source=rss-c670a3fc444b------2</link>
            <guid isPermaLink="false">https://medium.com/p/192f053e1691</guid>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[event-driven-architecture]]></category>
            <category><![CDATA[event-driven-systems]]></category>
            <category><![CDATA[apache-kafka]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Xavyr Rademaker]]></dc:creator>
            <pubDate>Tue, 13 Jul 2021 12:54:20 GMT</pubDate>
            <atom:updated>2021-07-16T01:16:24.849Z</atom:updated>
            <content:encoded><![CDATA[<h4>Five approaches for performing long-running jobs with examples in Java (Spring)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*C2izZ8GCgfFqKBISRIzh5w.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@ikukevk?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Kevin Ku</a> on <a href="https://unsplash.com/s/photos/hourglass?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>As engineers, we always aim to use the right tool for the right job, striving for excellence. However, sometimes we face a situation where we have delivery demands and we just must make it work with the tools available. While that is often a somewhat frustrating experience, it’s also a learning experience that leads to deeper and better understanding.</p><p>This is exactly what happened on one of my recent projects. We used an event-driven microservice architecture mostly using Java with Spring for our microservices and Apache Kafka as our event broker. At some point we needed to add long running jobs to our landscape. Given the time pressure we were under, we decided not to add new components to our landscape at that point in time, and so our long running jobs turned into new microservices that consume events from Kafka and start their processing.</p><p>Even though all seemed to go well at first, we started to run into issues when we increased the number of replicas for our microservices. These issues had everything to do with the default configurations of Kafka consumers, which are built for many fast jobs instead of few long running ones. After doing some research, we managed to get it to work without changing the tools in our landscape (and without any delays to the overall planning). In this blog I aim to show you the issues we encountered, and the various solutions we implemented, based on the different types of jobs.</p><p>With this blog, I do not try to encourage you to use Apache Kafka as message broker for long-running jobs. Its strengths lie in having lots of events in a fast-streaming type of system with small, fast jobs/processes that get triggered often. If you are in a situation that requires long-running jobs, I would advise to look for an alternative solution which is optimized for parallelized long running jobs. Instead, this blog aims to show you how to deal with long running jobs using Apache Kafka with 4 different implementations, in case you are in one of those rare scenario’s where there’s simply no time/budget to get another tool in your landscape.</p><p>Before we get started, some final remarks. This blog expects at least some level of familiarity with the basics of Apache Kafka and concepts of <a href="https://xavyr-rademaker.medium.com/peer-to-peer-choreography-and-orchestration-544af8b1bcfb">peer-to-peer choreography and orchestration</a>. As I will be referring to some of those concepts throughout the problem &amp; solutions. I have also created a repository with some very basic examples for all solutions I will discuss in this blog, which can be found <a href="https://github.com/Xavyr-R/kafka-long-running-jobs">here</a>.</p><h3>Problem</h3><p>Kafka consumers are, in Spring, by default configured to poll at least once every 5 minutes. If a consumer fails to poll within 5 minutes of its last poll, it will be marked as a dead consumer and leave the group. When using a Spring Kafka consumer, it will poll continuously on the consumer thread after booting up, so you don’t have to do anything for this to work. Once an event is polled the system will start processing this event on the consumer thread until its finished. This means that by default, the consumer won’t be able to poll again until its done processing (since the consumer thread is busy processing).</p><p>Below you can find a small piece of pseudo code to explain the consumer processing a bit better, please note that with long running jobs I refer to anything that takes longer to process than the default of 5 minutes.</p><pre>While(true){</pre><pre>  event = poll();</pre><pre>  //since this happens sequentially, the next iteration &amp; poll call    only happen after the method is done</pre><pre>  runLongRunningJob(event);</pre><pre>  commitOffset()</pre><pre>}</pre><p>Now that we understand the default behavior, let’s illustrate the scenario where things go wrong. In the following example we have a consumer group with 2 consumers in it, consumer A and consumer B. The consumers listen to topic T1 which has 2 partitions TP1 &amp; TP2, meaning that each consumer has 1 partition assigned: consumer A has TP1, and consumer B has TP2. Furthermore, there is 1 new event on partition TP1 called ETP1. This initial situation is illustrated in Figure 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/1*Or5qaZwXcYEXFxi5Y5FB-g.png" /><figcaption><em>Figure 1: Initial state of the system</em></figcaption></figure><p>Consumer A just consumed event ETP1 and started processing. Processing this event takes approximately an hour, so it just starts with it. After 5 minutes of processing (and thus not polling) consumer A gets marked as dead and leaves the group. These steps are illustrated in Figure 2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/866/1*ne686_Ft5cEOnqc_eMPo0Q.png" /><figcaption><em>Figure 2: Consumer A takes too long processing the event and leaves the group</em></figcaption></figure><p>This triggers a rebalance and the partitions get redistributed, assigning TP1 and TP2 to consumer B. As consumer A didn’t commit its offset yet, it will consume event ETP1 as well and start processing. This too will take longer than 5 minutes, so we can probably guess what the future hold for this consumer. Figure 3 visualizes this process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/858/1*OdaxeKkvz_4tmtBgfyDkWg.png" /><figcaption>Figure 3: Consumer B takes over, and the cycle continues</figcaption></figure><p>Besides the fact that every consumer that consumes ETP1 will have the misfortune of having to leave the group after 5 minutes, all of them are still busy processing the event even after leaving the group. This means that event ETP1 will be processed twice in our example. Just imagine having 10 or 20 replicas. Sooner or later all of them will be stuck processing the exact same event. This of course is a huge waste of time, resources and, maybe even worse, this can leave the system in an inconsistent state if the events aren’t designed to be idempotent.</p><h3>Solutions</h3><p>Now that we have an idea of the problem that occurred, let’s look at several solutions to tackle it. This section will cover the following five different approaches to solving the polling issue:</p><ul><li>Optimising the code</li><li>Increase the timeout</li><li>Fire-and-forget threading</li><li>Pause consumer with threading and callbacks</li><li>Split up the job into microprocesses</li></ul><p>Keep in mind that even though the five solutions are described independently of one another, they aren’t necessarily mutually exclusive. Combining microprocesses with increased timeouts or fire-and-forget threading for example works just fine.</p><p>The examples given in this blog use either pseudo code or Java with Spring, but of course the solutions work in other languages as well. For example, we have also implemented some of them in Python.</p><h4>Optimising the code</h4><p>The first, and most obvious, solution is to optimize the code you have written. Sometimes using the right datatypes can save a ton of time. For example, if your code involves looping through a list looking for an object with id 123 scales linearly (<em>O(n)</em>) with the size of the list. Loading your data into a HashMap instead of a list, and using the ID as key is likely to increase performance since HashMap lookups generally scale constantly (<em>O(1)</em>) (on average).</p><p>Besides using the right datatypes, also check whether there are redundant loops and/or calculations. If there aren&#39;t any redundant pieces of code, try some sanity checking of the all integrations as well. Some examples of questions to ask yourself are: Are we loading data multiple times? Did we optimise our writes to the database (think bulk inserts instead of normal inserts/upserts)? Are our queries optimised and do we have indexes on tables where we need them (or maybe too much indexes)? Can we combine certain computations in the same loop, preventing us from having to iterate over the same list again? All of these questions can lead to optimisations to be made in our system.</p><p>Of course, this is a simplified scenario, and sometimes the code is as optimised as it can be, but the job just takes a long time to process. In such cases the other solutions discussed in this blog might help. However, this doesn’t take away that it’s always worth looking at whether the code can be optimised.</p><h4>Increase the timeout</h4><p>When I described the problem earlier, I mentioned that the default configuration of max poll interval is 5 minutes. So, a second solution is to increase the value of this configuration. The specific Kafka configuration to set for this is “max.poll.records”, which in Spring can be set as follows (note that the 300000 is the default of 5 min):</p><pre>spring.kafka.consumer.properties.max.poll.interval.ms= 300000</pre><p>As simple as this solution might sound, there are some drawbacks to it. The biggest drawback is the fact that if things go wrong with your main processing thread (consumer thread), it will only be detected after the configured poll interval. If we set its value to 1 hour, it means that it will take 1 hour for the broker to realize something is wrong and trigger a rebalance. In a lot of cases 1 hour of doing nothing before recovering is not acceptable.</p><p>Secondly, how much time is enough? If you know that the process will always take at most 6 minutes than upping the configuration might be feasible. However, in a lot of cases finding the right value can become (educated) guesswork at best. Setting it too low means the same problem will occur after a longer period, while setting it too high means that it will take longer to trigger a rebalance when things really are going wrong.</p><p>To summarize the pros and cons for this approach:</p><p><strong>Pros:</strong></p><ul><li>Code is not affected, its pure configuration</li><li>Excels when a job takes more than 5 minutes, but is still predictably fast</li></ul><p><strong>Cons:</strong></p><ul><li>If the threshold is not known up front it’s just (educated) guessing</li><li>Has an impact on rebalancing of consumers, especially when the configuration is set to a high value</li></ul><p>Finally, some scenario’s where you can use this approach to solve this problem:</p><ul><li>When the max runtime of the job is predictable</li><li>When the runtime of the job time is not much longer than the default</li></ul><h4>Fire-and-forget threading</h4><p>The third approach on the list is fire-and-forget threading. Looking closely at this issue, we see that it lies in the fact that the long running jobs block the polling loop on the consumer thread, preventing it from polling again until the job is done. Now what happens if we offload the work to separate worker threads? In that case the polling loop just continues while the job runs.</p><p>Starting a job in a fire-and-forget manner using Spring is quite straight forward. Start by adding the following annotation to either your configuration class (if you have one) or your main class:</p><pre>@EnableAsync</pre><p>This enables Spring’s asynchronous method execution capability. The second, and last, addition to our code needed is to add the following annotation to the public method that starts the long running job:</p><pre>@Async</pre><pre>public void run(String event) {</pre><pre>   //some long running job</pre><pre>}</pre><p>Simply calling this method from your consumer will run it as a background job while the polling loop of the consumer continues without being interrupted. Spring will handle the thread management for you.</p><p>As you can see, this approach requires little changes to the code base. The solution also works regardless of the processing time. The sheer ease of use, minimal code changes and the fact that Spring handles the concurrency make this approach quite attractive.</p><p>However, there are some downsides to the approach as well. When your job is very resource intensive (high CPU/Memory usage), running the job concurrently for multiple events means that you risk running out of resources, which means either slow performance due to max CPU usage or even worse, running out of memory.</p><p>Besides being resource intensive, dealing with failures also becomes more complex with this approach. Due to the fire-and-forget nature of this approach, the worker thread needs to contain its resilience logic as well. This can be anything from calling itself on failure (as retry mechanism) to producing an event to a dead letter topic (or to the original topic, putting it back on the queue) for later reprocessing.</p><p>Furthermore, since the consumer won’t wait for the event to be processed until consuming the next event, we lose the queuing behavior of Kafka. This means that all events, even the ones on the same partition, must be able to be processed out of order or an internal queue needs to be built in the microservice (to be sure to follow the queues of the Kafka partition) which increases complexity.</p><p>What I found working quite well with this approach is the orchestration strategy. Since the core of that strategy is to have an orchestrator that handles flow-management, it can deal with the error flows of the fire-and-forget style long running jobs. All the microservice needs to assure is to always produce its outcome back to the orchestrator, whether its successful or not.</p><p>Summarizing this approach:</p><p><strong>Pros:</strong></p><ul><li>Minimal code changes</li><li>High concurrency</li><li>Works regardless of how long job takes</li></ul><p><strong>Cons:</strong></p><ul><li>Resources get sparse when lots of long running jobs are triggered</li><li>Error handling like retries become more complex as this logic must be added to the processing logic</li></ul><p>When to use this approach:</p><ul><li>I/O intensive jobs that don’t take a lot of resources</li><li>Jobs can run independent of one another</li><li>Unpredictable/long runtimes</li><li>There is an orchestrator to keep track of success/error/retries (all flow wise logic)</li></ul><h4>Pause consumer with threading and callbacks</h4><p>The fourth solution to the problem is to pause the consumer. This approach is also described in the documentation <a href="https://kafka.apache.org/25/javadoc/org/apache/kafka/clients/consumer/KafkaConsumer.html">here (under detecting consumer failures)</a>.</p><p>When pausing a consumer, you typically pause specific topic partitions. The consumer will still poll the broker however, it will simply not accept any new events from the specified topic partitions until its resumed again. The poll simply works as a health check. To ensure that the polling really continues, we still offload the work to a worker thread (since otherwise the polling loop will be blocked as explained in solution 2). The difference is that we don’t use fire-and-forget style processing, we actively add a callback to the job which resumes the processing again.</p><p>Code wise the pseudo code would look something like this:</p><pre>while(true){</pre><pre>event = poll();</pre><pre>consumer.pause(topicPartition);</pre><pre>thread.runLongRunningJob(event)</pre><pre>      .callbackSuccess(resume(topicPartition))</pre><pre>      .callbackError(handleError());</pre><pre>commitOffset();</pre><pre>}</pre><p>The offset will still be committed automatically (alternatives to this will be discussed later), but we have added a callback to the long running job. In this callback we can also handle error scenario’s (in Spring we can add both success and error callbacks) where we can add our retry or Dead Letter Topic logic, making it suitable for peer-to-peer choreography as well without having to modify our worker logic.</p><p>Implementing this approach in Java using Spring looks as follows:</p><pre>@KafkaHandler</pre><pre>public void handleEvent(@Payload String event) {</pre><pre>  log.info(“Handling the event with body {} the pause container way”, event);</pre><pre>  //pauses the container</pre><pre>  containerSupportMethods.pauseConsume(containerId);</pre><pre>  executor.submitListenable(() -&gt; longRunningJob.run(event))</pre><pre>  .addCallback(result -&gt; {</pre><pre>    containerSupportMethods.resumeConsumer(containerId);</pre><pre>    log.info(“Success callback”);</pre><pre>  },</pre><pre>  ex -&gt; {</pre><pre>    //perform retry mechanism like a dead letter queue here</pre><pre>    containerSupportMethods.resumeConsumer(containerId);</pre><pre>    log.warn(“Error callback”);</pre><pre>  }</pre><pre>  );</pre><pre>}</pre><p>Where pause and resume functionality is implemented like:</p><pre>private final KafkaListenerEndpointRegistry registry;</pre><pre>public void pauseConsume(String containerId) {</pre><pre>  getContainer(containerId)<br>    .ifPresent(MessageListenerContainer::pause);</pre><pre>}</pre><pre>public void resumeConsumer(String containerId) {</pre><pre>  getContainer(containerId)<br>    .ifPresent(MessageListenerContainer::resume);</pre><pre>}</pre><pre>private Optional&lt;MessageListenerContainer&gt; getContainer(String containerId) {</pre><pre>  return Optional<br>    .ofNullable(registry.getListenerContainer(containerId));</pre><pre>}</pre><p>One thing to note is that the low-level Kafka library allows you to call pause on the consumer directly, specifying exactly which partitions to pause. Spring has added a layer of abstraction on top of the low-level consumer called the MessageListenerContainer (Spring container that runs the consumer) from where you call the pause method. This container does not allow you to specify which topic partitions should be paused, instead it pauses all partitions assigned to the consumer for all topics the consumer listens to. On the flipside, this container does provide thread safety allowing us to resume the container on the worker thread (in the callback), where the low-level consumer object is not thread safe (and doesn’t resume when called from the callback thread).</p><p>When resources become scarce in the fire-and-forget approach, this solution will work quite well for you. This is because you limit the amount of concurrency, making it much more stable. Also, we regain the freedom to handle errors gracefully without adding too much complexity and the queuing behavior from Kafka partitions are retained (due to the limited/no concurrency). However, we do have to add more logic to our consumer to implement this, and we lose the speed benefits concurrency can give us.</p><p>Summarizing this approach:</p><p><strong>Pros:</strong></p><ul><li>Stable, even for resource (CPU/Memory) intensive jobs</li><li>The callback can be used for error handling, retries etc., making it suitable for choreography patterns as well</li><li>Retain the natural queuing behavior of Kafka partitions</li></ul><p><strong>Cons:</strong></p><ul><li>Requires more code changes than the previous approaches</li><li>Limited/no concurrency, which can result in longer overall processing time</li></ul><p>When to use this approach:</p><ul><li>You have unpredictable or very long runtimes</li><li>CPU/Memory intensive jobs</li><li>Order of job execution matter</li></ul><h4>Split the job into microprocesses</h4><p>The last solution which can be feasible depending on the nature of the job is to split it up into smaller processes. This solution works well in situations where the job is quite compute-heavy and can be parallelized. Do note that this is more of a design solution which is technology agnostic.</p><p>For example, if our job performs three steps with each new event called A, B and C, and each of them take at most 4 minutes to process as in the pseudo code below:</p><pre>While(true){</pre><pre>  event = poll();</pre><pre>  resultA = performA(event); //max 4 minutes</pre><pre>  result B = performB(resultA); //max 4 minutes</pre><pre>  finalResult = performC(resultB); //max 4 minutes</pre><pre>}</pre><p>This example job can be split up into three <a href="https://medium.com/creditorwatch/microprocesses-a-new-architectural-design-pattern-for-background-jobs-on-a-microservice-172a8a19ba8f">microprocesses</a>, each having their own consumer and running within the default time limitations. After refactoring the (pseudo) code base would be:</p><p>Consumer A:</p><pre>While(true){</pre><pre>  event = poll();</pre><pre>  resultA = performA(event); //max 4 minutes</pre><pre>  produce(resultA);</pre><pre>}</pre><p>Consumer B:</p><pre>While(true){</pre><pre>  resultA = poll();</pre><pre>  resultB = performB(resultA); //max 4 minutes</pre><pre>  produce(resultB)</pre><pre>}</pre><p>Consumer C:</p><pre>While(true){</pre><pre>  resultB = poll();</pre><pre>  finalResult = performC(resultB); //max 4 minutes</pre><pre>}</pre><p>There are multiple benefits to dividing long running jobs into microprocesses, such as it being easier to maintain &amp; deploy. Each microprocess can be its own microservice so they can be deployed while other stages run. Also, each microprocess can be giving appropriate resources, tailored to the needs of that specific stage and of course it removes the issue with long running jobs and Kafka.</p><p>However, it does come at a price: added overall complexity in your system. Understanding that a single long running process means that you must go over all the individual microprocesses to find what they all do and how they tie together. Also, since the processes are split up into smaller parts, coordination over these processes need to happen as well either using peer-to-peer choreography or orchestration. Not to mention that not all jobs can be stripped down to microprocesses so granular that each stage fits the max poll interval duration.</p><p>Given this information, I’d say that this approach has the following pros and cons:</p><p><strong>Pros:</strong></p><ul><li>Individual stages can be deployed and scaled separately</li><li>Maintainability of individual stages is likely to go up (due to their limited scope)</li></ul><p><strong>Cons:</strong></p><ul><li>Overall complexity of your jobs likely to increase due to separation of code</li><li>Process needs to be coordinated, which adds (even more) complexity or components to the system</li><li>If one (or more) of the parts can’t be scoped so granular that it fits the default 5 minutes, a different solution needs to be found for that specific case</li></ul><p>Some scenarios were dividing the job into microprocesses would be feasible:</p><ul><li>The job is splitable in smaller units of work</li><li>The job is critical enough for the system to justify the added complexity</li></ul><h3>Some tips to take along</h3><p>While implementing the five solutions above, there were some implementation details that I found handy which are detailed out in this section.</p><h4>Partitioning strategy</h4><p>If the order of execution is irrelevant, make sure the partitioning strategy used by your system distributes the long running jobs evenly among partitions. In our case we used round robin partitioning to ensured that work got distributed approximately evenly over all replicas in de consumer group handling the long running jobs.</p><p>Good to know, round robin partitioning was the default partitioning strategy for Kafka 2.3 and below (when producing without a key). However, this is replaced with the sticky partitioner in version 2.4 and above. Even though the sticky partitioner provides a lot of benefits in terms of <a href="https://www.confluent.io/blog/apache-kafka-producer-improvements-sticky-partitioner/">performance</a> in scenario’s where you have lots of small jobs, it is not helpful when having a few long running jobs (where even distribution leads to more parallelism).</p><p>Besides using the round robin partitioner, it is of course always possible to write a custom partitioning strategy suitable to your use case.</p><h4>Limit number of events consumed per poll</h4><p>In resource intensive jobs where we used the pause consumer approach, we found it useful to limit the max polled records per poll (we limited it to 1). This can be done by setting the following spring configuration:</p><pre>spring.kafka.consumer.max-poll-records=1</pre><p>This forces the consumer to process 1 event at the time, limiting the amount of time the consumer is paused to an absolute minimum. Also, in scenario’s where you want to scale up replica’s while some consumers are still processing data, this approach gives the highest chance of parallelism after scaling. This scenario is illustrated in the two GIFs below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*ztY3GcvKq2qBXaQXCJKkpg.gif" /><figcaption><em>Default behavior, polling multiple events at once</em></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*72Irk6RfmKLfo_OsR8fYew.gif" /><figcaption><em>Behavior when polling one event at the time</em></figcaption></figure><h4>Use manual commits</h4><p>This too holds especially for the resource intensive jobs, where the consumer is paused and resumed using the callback. Instead of having spring auto-commit upon successful deserialization of the event, commit the events yourself in the callback of the event processing logic. This allows you to build proper error handling scenario’s as well by using a Dead Letter Topic, retries (adding the event to the back of the partition or really retrying the logic) or “nack”-ing the event.</p><p>Spring provides a nice wrapper class to handle acknowledgements of events, called “Acknowledgment”, which you can get as a parameter to your Kafka handler in your listener (consumer). To get access to this object, set the following configuration in your application.properties:</p><pre>spring.kafka.listener.ack-mode=MANUAL_IMMEDIATE</pre><p>After successful processing, the event can be acknowledged by calling acknowledgement.acknowledge(). Similarly, upon failed processing of an event it can be nacked using acknowledgement.nack() or, as mentioned before, acknowledge it in combination with some retry logic.</p><h3>Wrapping it up</h3><p>That finalizes this blog on dealing with long running jobs using Kafka consumers. In case you want to have some working examples for the different approaches, have a look at this repository: <a href="https://github.com/Xavyr-R/kafka-long-running-jobs">https://github.com/Xavyr-R/kafka-long-running-jobs</a>. The modules in the repo map to the solution as follows:</p><ul><li>Not-async: the problem illustrated, also contains the configuration of the first solution</li><li>Spring-async: Fire-and-forget threading</li><li>Pause-container: Pause consumer with threading and callbacks</li><li>Pause-container-with-acknowledge: Pause consumer with threading and callbacks combined with the tips of manual commits and limit number of events polled</li><li>Microprocesses: Split the job into microprocesses</li></ul><p>Before leaving you to it, I’d like to repeat that, if your situation allows for it, you will likely be better off using an alternative for running/orchestrating long running jobs instead of Apache Kafka. In my next blog I will introduce workflow engines, which could serve as one of those alternatives. So, stay tuned for future blogs!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=192f053e1691" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/dealing-with-long-running-jobs-using-apache-kafka-192f053e1691">Dealing with long-running jobs using Apache Kafka</a> was originally published in <a href="https://medium.com/codex">CodeX</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Peer-to-peer choreography and orchestration]]></title>
            <link>https://xavyr-rademaker.medium.com/peer-to-peer-choreography-and-orchestration-544af8b1bcfb?source=rss-c670a3fc444b------2</link>
            <guid isPermaLink="false">https://medium.com/p/544af8b1bcfb</guid>
            <category><![CDATA[event-driven-architecture]]></category>
            <category><![CDATA[orchestration]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[event-driven-systems]]></category>
            <category><![CDATA[choreography]]></category>
            <dc:creator><![CDATA[Xavyr Rademaker]]></dc:creator>
            <pubDate>Mon, 08 Mar 2021 16:14:14 GMT</pubDate>
            <atom:updated>2021-03-08T16:29:52.872Z</atom:updated>
            <content:encoded><![CDATA[<p>Designing event flows in an event driven microservice architecture</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-Xkk1LLyMVcL2dIZo30nCQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@matthardy?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Matt Hardy</a> on <a href="https://unsplash.com/s/photos/flow?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>My colleague Oskar recently started a series on event-driven architectures. In the latest addition he shared <a href="https://medium.com/swlh/the-6-things-you-need-to-know-about-event-driven-architectures-38e11fdcb5a">six things that every engineer should know about event-driven microservices</a>. One of those six items was the ability to architect event flows. In this blog I will explore that topic in much more detail.</p><p>With an event driven architecture, all microservices interact with each other asynchronously using events, with the event broker as the intermediate traffic controller. This means the microservices are loosely coupled by nature making the overall system more maintainable, scalable and extensible. However, there’s also new challenges to compose business flows using loosely coupled microservices. To deal with this challenges, different strategies have emerged as a best practice to design and implement extensible event flows.</p><p>There are two main strategies when it comes to building your event flows: peer-to-peer choreography and orchestration. Before I dive into details and providee some example implementations for both approaches, let’s take a very high-level overview and discuss the key differences between both approaches.</p><p>Similar to a group of dancers following a predetermined choreography where each dancer knows exactly what (s)he should do and when (s)he should do it, microservices following the peer-to-peer choreography pattern know exactly what they should do, and when they should do it.</p><p>The orchestration strategy, on the other hand, is similar to an orchestra (as the name implies) where there is a microservice that has the role of an orchestrator. The orchestrator microservice is responsible for the event flow, instructing other microservices to act at the appropriate moment.</p><p>In the rest of this blog, we will first dive deeper in the peer-to-peer choreography strategy, followed by the orchestration strategy. Afterwards we will go over some complex scenarios with the two strategies.</p><h3>Peer-to-peer choreography</h3><p>As explained, in the peer-to-peer choreography strategy all microservices will know exactly what to do, and when to do it. The microservices operate individually without being aware of the bigger system and without any centralized authority telling it what to do. Each microservices listens to the events it is interested in and performs its operation based on it. Due to this publish and subscribe nature, it is very easy to extend the system with more microservices that listen to the same events.</p><p>Let’s take a small example to show how this works. We are building a system that allows users to apply for a loan. The system will then review the request and either approve or deny it. We will start building this system in its simplest form by creating two microservices:</p><ul><li>The Loan request service which is responsible for handling user input (user input validation etc.)</li><li>The Offer service which determines whether we can or cannot offer the requested loan by applying risk factors and performing additional business rules</li></ul><p>Figure 1 shows this implementation using peer-to-peer choreography.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/661/1*9tgkodLl43vlnezuvwG7ig.png" /><figcaption><em>Figure 1. The basic loan request flow</em></figcaption></figure><p>After setting up the core loan processing flow, we now shift our attention to informing the user of the outcome. So, we decide to extend our system with an Email service, which will take the loan approved event and send an email to our user. Since we are using peer-to-peer choreography, extending the system with a new microservices that listens to existing events is easy. Adding more and more microservices that are dependent on existing events is pretty straightforward and does not require any of the existing microservices to change. We just add another microservice to the end of our flow, and it will all work out of the box, because of the loosely coupled nature of this strategy. Figure 2 shows the extension of our system with an Email service.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/671/1*ow49-chUG1UBMx-PtCxFbg.png" /><figcaption><em>Figure 2. Extending our system by adding the Email service</em></figcaption></figure><p>Since both the Email service as well as the Profile service work independently, there is no single point of failure in the system. If the Email service goes down for 10 minutes, the loan requests of new users are still processed. When the Email service eventually recovers, it will continue to pick up the events it missed and start sending out those emails. An important thing to take into account is that if such scenario occurs (a microservice going down while the rest of the system functions properly), it means that there could be a spike load after recovery. It is important to design your microservices in a way that can handle these spikes (for example setting a hard limit on the number of events being processed at the same time in the microservice).</p><p>At this point we have a flow that is able to process and approve loan requests and inform the users of this process. However, before we approve loan requests, we need to verify the credibility (meaning the user’s ability to pay off the loan and interest) of our user. Based on his/her credibility, we can either approve or deny the loan request. To facilitate this change, we need to add a credibility check to our system. The result of this credibility check will be additional input to the Offer service, so that we can determine the risk factors of our user more accurately. We decide to add the credibility check in a new microservice called the Credit service. Its output will be used by the Offer service to determine whether to approve or deny the loan request.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/671/1*FYoOfMScXG2X9SapvVymHw.png" /><figcaption><em>Figure 3. Changing the flow of the system by adding a credit service</em></figcaption></figure><p>As we can see in Figure 3, changing the flow by adding a microservice in the middle isn’t as straightforward as extending the system. This has to do with the fact that even though the microservices operate independently and are loosely coupled by nature when using peer-to-peer choreography, a certain degree of coupling is still present because of the events being a contract for the microservices to collaborate. If we generalize the coupling we’ve seen, a rule of thumb for adding a new microservice would be:</p><ul><li>If no existing microservice needs the output of our new microservice: no changes to microservices other than the new one is needed. For example, think of either extending an existing sequential flow with another step at the end (our Email service) or introducing a new parallel flow based on an existing event</li><li>If any existing microservice needs the output of our new microservice: at least 2 microservices need to be updated (the new one and the existing one(s) that need the output). An example of this was adding our Credit service</li></ul><p>Another important thing to note, is that we now have 2 different possible flows we need to maintain in different places, both the “approved” flow as well as the “denied” flow need to be implemented and maintained in the Offer service as well as the Email service.</p><p>Before going into this implementation using the orchestration strategy, let’s add one more feature to our system. Since we are in the business of financing our users, we need to add at least one extra check that weighs in on whether we should or should not approve the loan request. This check is to verify whether or not the user is known or suspected to be performing criminal activities. If a user is suspected of performing criminal activities, the request should be denied, and the authorities should be informed of this user in the form of another email.</p><p>The first thing we need to do to implement this, as we are applying the peer-to-peer choreography strategy, is to add another microservice that listens to the LoanRequested event as well. There are however multiple ways to process its output:</p><ul><li>Solution 1: Update the Offer service and the LoanRequestProcessed event to contain extra information on whether the authorities should be informed or not and update the logic in the Email service</li><li>Solution 2: Have the Email service listen to the CriminalActivityChecked event (output of the new microservice) and act independently on this</li></ul><p>To show some of the challenges that can sneak in when doing peer-to-peer choreography, we will go for solution 2. The Email service will know what to do whenever it consumes the CriminalActivityChecked event. This solution is shown in Figure 4.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/781/1*kGjIMsJD737EA51VGVr1Lw.png" /><figcaption><em>Figure 4. Adding a criminal activity service to the flow, which in some cases leads to an extra email being sent. Note that 4a, 5a and 6a form the main flow, and 4b and 5b form a parallel flow</em></figcaption></figure><p>Even though we have a system that works perfectly fine, with every addition we make (especially the additions of parallel flows like we just did) the complexity increases, and our systems gets harder to understand. Just imagine what happens if the Offer service only receives one of the two events. Since it depends on two events to start doing something, it has to deal with eventual consistency and out of order events, next to its own responsibility and complexity. And what happens if we decide we need a manual intervention to verify whether the criminal activity checked is not a false positive, we will have to update at least three microservices (Criminal activity service, Offer service and Email service) to deal with this change. How do we keep track of such scenarios and where a user’s request possibly failed?</p><p>Before we discuss scenarios like these, let’s summarize what we’ve learned implementing our system using peer-to-peer choreography and implement the same system using the orchestration strategy. Having seen the evolution of our system using peer-to-peer choreography, we have seen some of its strengths and challenges in action:</p><p><strong>Strengths</strong>:</p><ul><li>It’s easy to extend the system with new functionality without having to adjust any other microservices</li><li>The autonomy of microservices results in high overall availability</li><li>There is no single point of failure</li></ul><p><strong>Challenges</strong>:</p><ul><li>Understanding everything that happens in the system becomes hard over time</li></ul><h3>Orchestration</h3><p>As opposed to the decentralized nature of the peer-to-peer choreography strategy, the orchestration strategy relies on a single, centralized microservice that orchestrates the workflow. The sole responsibility of this orchestrator is to listen to events that happen in the system and send out commands to other microservices to start performing their task.</p><p>Figure 5 shows how our initial, simple loan request flow would look like when following the orchestration strategy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/731/1*Pygf0MSz0hLhEwAgVoOawA.png" /><figcaption><em>Figure 5. The initial loan request flow with an orchestrator</em></figcaption></figure><p>Comparing this flow to the choreography implementation, the main differences lie in the fact that the Offer service no longer listens to the loan requested event. Instead, the orchestrator listens to this event, and sends out a command to the Offer service to start performing its operation. Looking at the design with a critical eye, it might actually seem like an overkill to have an orchestrator for such a simple flow. Let’s extend the flow with the Email service in figure 6.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/741/1*ky74u5Ne2ZuTgv5hOm3LtA.png" /><figcaption><em>Figure 6. Adding the Email service to our orchestrated flow</em></figcaption></figure><p>Here too, the orchestrator listens to the user registered event and sends out two commands (where an event communicates that something happened, a command communicates that something needs to happen) for the other microservices to start performing their action. As opposed to the choreography strategy, where one microservice going down has a minor impact on the overall availability, the orchestrator going down for 10 minutes would result in the whole system being unavailable for 10 min since both the Offer service as well as the Email service will not receive any of the commands to start working. Besides that, we can also see that extending the system in the peer-to-peer choreography strategy meant only adding a new microservice that listens to existing events, using an orchestrator means that this extension impacts two microservices.</p><p>If, like before, we continue to update our system by adding a Credit service we notice something interesting. Even though extending a system using peer-to-peer choreography requires less (no) changes to existing components, altering the workflow means changing (at least) two microservices in both strategies. Where in peer-to-peer choreography, adding the Credit service before the Offer service meant updating those two microservices, and updating the rest of the existing flow to deal with this newly created alternative flow, in our orchestration implementation it means adding the new microservice to our system and updating the orchestrator to deal with the different workflows. In other words, the number of updates is almost the same in both cases! Figure 7 shows how our systems looks after we’ve added the Credit service.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/731/1*5Kk3rD259w2FjMqymetNKQ.png" /><figcaption><em>Figure 7. The credit service being orchestrator</em></figcaption></figure><p>To finalize our system, let’s end by adding our criminal activity flow to our orchestrated system. Just like with the Credit service, this means adding a new microservice and updating all microservices that depend on its output (including the orchestrator).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/732/1*uG_V-H7v9vn7JWWOCuVcpw.png" /><figcaption><em>Figure 8. Our final, orchestrated loan request flow</em></figcaption></figure><p>When dealing with larger systems that require complex flows, the orchestration strategy gives you the great benefit of centralizing both the flow coordination, making it easier to understand what happens when. In addition, as the orchestrator centralizes the workflow logic, the risk of getting distributed business rules is reduced. Of course, these benefits also come with limitations, where your system is not as extensible as it was before (adding the Email service required both creating the Email service as well as updating the orchestrator). Besides being less extensible, there is also the matter of having a centralized microservice responsible for coordinating the flow, meaning that there is a single point of failure in the system.</p><h3>Complex scenarios</h3><p>So far in this blog we have covered how to build and evolve event flows, and some pros and cons of both strategies. However, as systems become bigger and more mature, we always tend to get to a point where we hit more complex scenarios like:</p><ul><li>Implementing non-happy flows where a technical error happens halfway through the flow</li><li>Being able to automatically act on incomplete processes</li><li>The need for SLAs and metrics to measure the system’s performance and health</li><li>Building and maintaining a custom orchestrator or leveraging a workflow engine</li></ul><p>In this section, we will briefly go over these four scenarios and explain how to deal with them using both approaches.</p><h4><strong>Non-happy flow</strong></h4><p>If we take a look at the final design of our loan request system, there are a lot of things that can go wrong. Let’s take a non-happy flow to explore further — what happens if an email fails to send due to an unexpected error, or even worse due to a network issue the event never arrives in the Email service.</p><p>In both the peer-to-peer choreography and the orchestration implementations, the unexpected errors can be tackled by applying some form of retrying on the Email service itself. This retrying behavior can range from something as simple as not acknowledging the event and processing it again upon failure, to more complex implementations like implementing a dead letter queue which gets retried every <em>x </em>amount of time.</p><p>What is harder to tackle using peer-to-peer choreography is the scenario where an event gets lost (due to a network hiccup or a consumer that acknowledged an event right before it died off for example). Because each microservice is unaware what happens to the rest, there is no simple solution to automatically recover from this due to the fact that the microservice that missed the event, is unaware of the fact that it missed it.</p><p>In the orchestration implementation on the other hand, these types of failures (as well as timeouts and the need to rollback certain actions) are easier to detect and to be acted on automatically because the orchestrator is aware of what has happened, and what was supposed to happen. For example, if we expect the email to be sent within at most 5 minutes, it’s easy to check whether the email send event has been produced at within 5 minutes after the send email command was produced. Do make sure that your events are idempotent to prevent accidental retries in such cases (we don’t want to send the email out twice because our Email service took longer than expected).</p><h4>Acting on incomplete processes</h4><p>Just like unhappy flows due to errors in the system, acting on incomplete processes is easier to do with the orchestration implementation. Let’s say that after we approved the loan request and we’ve sent the email to our user, we expect our user to acknowledge the offer. Since the orchestrator knows exactly when the email was sent, we can send time-based reminders to the user if (s)he did not approve the offer after <em>x</em> days. The same holds for a process that gets stuck halfway through due to a manual intervention that is needed, for example if we want one of our employees to double check randomly selected credit checks on false positives. The logic works similar to the earlier discussed timeout scenario. If after <em>x</em> period a manual intervention did not take place, send a reminder to make sure the process gets completed. In peer-to-peer choreography this becomes harder because the information about the full flow is distributed, so a microservice is not aware that a flow is incomplete.</p><h4>SLAs and metrics</h4><p>As the system matures, either you as the developer, or the business, will want to have some metrics and numbers on the performance of the system. This can of course have multiple reasons like defining an SLA, understanding the bottlenecks in the system, being able to see whether all microservices are healthy etc. In the peer-to-peer choreography implementation, the only way to get this information is to have every microservice export its metrics to a centralized monitoring system. In the case of our loan request system, from the Loan request service all the way to the Email service, all microservices need to export when they started processing an event and when they finished. By aggregating this information, we can than create a dashboard that gives us the insights we need. Although this solution also works for the orchestration implementation, it can be done easier. The orchestrator is already aware of everything that has happened, and when it all happened. In other words, all the metrics that need to be exported and centralized in the peer-to-peer choreography implementation are already present in the orchestrator itself. This means that all we really need to do is to visualize this (or export this information from the orchestrator to the monitoring application to save us some visualization time).</p><h4>Custom orchestration and workflow engines</h4><p>When implementing the orchestration strategy, especially for a simple flow as the loan request system we’ve just designed, the orchestrator can be implemented by simply building another microservice that coordinates the rest. However, as your system grows and the flows become more complex, it can be worth it to start looking into open-source workflow engines like for example Netflix’s Conductor, Apache Airflow, Argo and Camunda (of course the list is longer than this) or even workflow engines provided by cloud vendors like AWS Step Functions, Azure Logic Apps and Google Cloud Workflows.</p><p>One of the reasons to consider this movement to workflow engines is that at some point, a lot of time and effort will be spend on updating the orchestrator instead of building the functionality that fulfills the business needs. Workflow engines often have a simple way to define the steps in a workflow via either a graphical user interface or a domain specific language (Netflix conductor for example is REST/JSON based). Often times defining and updating workflows like this is both faster and reduces the risk of making a mistake. The flip side of it is that we need to add a new component to our landscape and, like most out of the box solutions, they won’t always fit your use case.</p><h3>In conclusion</h3><p>In this blog we dove deeper into the two main strategies when designing event flows, peer-to-peer choreography and orchestration, where they excel and what their drawbacks are and what considerations to take into account when choosing the strategy that works for you. It is important to know that both are tools to keep in your pocket to use at the appropriate times. We didn’t go into it explicitly, but they can even be combined in some cases like having an Audit service listening to all events in a peer-to-peer choreography style where the rest of the system follows the orchestration strategy. Just be careful when doing this, as mixing strategies can make things more complex.</p><p>In future blogs I will discuss popular workflow engines, like ones mentioned earlier, and what their added value is compared to doing it yourself.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=544af8b1bcfb" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>