<?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 Devora Roth Goldshmidt on Medium]]></title>
        <description><![CDATA[Stories by Devora Roth Goldshmidt on Medium]]></description>
        <link>https://medium.com/@debyroth340?source=rss-fb5f5e4986c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*m3uVALPyIfKvpuI7dawIYA.jpeg</url>
            <title>Stories by Devora Roth Goldshmidt on Medium</title>
            <link>https://medium.com/@debyroth340?source=rss-fb5f5e4986c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 16:57:37 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@debyroth340/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[Consumer Throughput? I don’t care. Kafka Time Lag is my uber-metric for SLO Monitoring.]]></title>
            <link>https://medium.com/@debyroth340/consumer-throughput-i-dont-care-kafka-time-lag-is-my-uber-metric-for-slo-monitoring-d846c171b61c?source=rss-fb5f5e4986c------2</link>
            <guid isPermaLink="false">https://medium.com/p/d846c171b61c</guid>
            <category><![CDATA[slo]]></category>
            <category><![CDATA[consumer]]></category>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[time-lag]]></category>
            <category><![CDATA[offset-lag]]></category>
            <dc:creator><![CDATA[Devora Roth Goldshmidt]]></dc:creator>
            <pubDate>Tue, 07 Jan 2025 05:49:25 GMT</pubDate>
            <atom:updated>2025-01-07T05:49:25.898Z</atom:updated>
            <content:encoded><![CDATA[<p>More than a year has passed since I published <a href="https://medium.com/@debyroth340/slo-monitoring-of-event-driven-architectures-b35d2a2d8043">SLO Monitoring of Event-Driven Architecture</a> which essentially suggested starting with monitoring the service Throughput (processing rate) and Kafka Lag and adjusting the formula later on.<strong> </strong>I must admit that I have since changed my mind. After tweaking and re-formalizing the formula several times, I realized I was measuring the wrong aspect: I shouldn’t care about throughput. The only relevant and important aspect in my case (and maybe in yours as well?) is <strong><em>time</em></strong>.</p><p><strong>Let me provide some context</strong></p><p>The system architecture I’m responsible for consists of dozens of services. Some are HTTP services (Spring Boot-based), while others are stream processing services (Flink-based, consuming Kafka topics). The purpose was to measure the Service SLO, the internal objective assigned to a particular service, considering the different application SLAs and the number of tenants hosted in the grid. Generally speaking, there are three types of Service SLOs: Uptime SLO, Response-Time SLO, and <strong>Data-Freshness SLO</strong>. While the first two are relevant for HTTP services and are relatively easy to measure, the Data-Freshness SLO is the most important indicator for our stream services. Data freshness means how long an event is waiting to be processed by the service, which implies how fresh the already processed data is. What sounds pretty natural for stream processing turned out to be not so easy to compute and monitor.</p><p><strong>We started with the obvious metrics: Throughput and Offset Lag</strong></p><p>This article relies on the reader’s basic knowledge of Kafka, but in case you are less familiar with the terms: Consumer Offset Lag in Kafka is the difference between the last offset stored by the broker and the last offset committed by the consumer for that topic partition. Throughput, in this context, is defined as the last committed offset minus the committed offset as it was a one-time unit ago. So if the unit is EPM (Events per Minute), it’s the delta between the committed offset of the current minute and the committed offset a minute before for the particular topic partition and consumer.</p><p>The initial idea was that Throughput would reflect the processing rate, while the Offset Lag would indicate how much work the service has to do (if any) and show the trend, whether it keeps growing or stays consistent. So a typical service dashboard may look something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CNG_uS2q2rLMJajttdlrCg.png" /><figcaption>Throughput — EPM (blue) vs Offset Lag (green)</figcaption></figure><p>You can see that at 22:37 the Throughput was zero, but this is absolutely acceptable since the Offset Lag was zero too, meaning the service didn’t have any work to do. But at 22:31, the lag was around 100 — is that OK? And what about a lag of 1 million?</p><p>Just to demonstrate the challenge, let’s have a look at the max offset lags of two different topics consumed by the same service:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-0NM4gY-I6Kr6WeHa70xyg.png" /><figcaption>Data Events offset lag (yellow) vs Contorl Messages offset lag (green)</figcaption></figure><p>For control messages that notify the service that the business user updated the configuration, bucketing of 10 events is reasonable. But 100 is not! Such a lag practically means the service doesn’t consider the updated business configuration for a week or two… On the other hand, bucketing 80K data events is OK, since they are generally produced very quickly. Such a lag of 100K can practically mean that the service is in a single-minute delay which is fine, according to the Data-Freshness SLO of this particular service. Now, the formula becomes very complex and hard to maintain — the threshold for when the lag becomes problematic should be fine-tuned per topic per service (consumer group) and can differ in order of magnitude between the services.</p><p><strong>But wait. Why monitor the rate rather than the time lag itself?</strong></p><p>Then it hit me: I was focusing on the wrong metric. The service rate doesn’t matter as long as it closes the gap in the desired time. A service can be “lazy” or “very quickly responsive” depending on the business logic. For example, a service can bucket 3-items-tiny lag and be marked red because those items have been waiting for a long time. Conversely, it can bucket a 1MM-huge lag and still be marked green if it can process 1MM events in a second. The queue size doesn’t really matter! The only factor is how long items are waiting in the queue.</p><p>Another way to think about it is that freshness time translates technical KPIs into a term humans can easily understand and feel the impact of. Consider the potential complaints we may get from our customers if the services are out of their SLOs: “<em>The report I see in the portal looks out-of-date</em>,” “<em>I expect to have items for investigation at 08:00 AM but got them only at 09:45. Waste of my team’s time</em>!” or any similar complaint. OK. I convinced you. Time is the way to go. But which time? how do we measure time lag in Kafka-based services?</p><p><strong>Maybe we can simply estimate the future Time Lag?</strong></p><p>One could argue that the time it will take for a service to empty the queue can be estimated by <em>OffsetLag\LastObservedThroughput. </em>This assumes that the <em>LastObservedThroughput </em>is representative enough to be “the best rate the service can perform”. So if the service can handle a max of 1k EPS and the current offset lag is 60K, the estimation is that it will take 60 seconds for the service to process all items in the queue.</p><p>However, our reality showed that this estimation is useless, especially with high traffic peaks (e.g., for two minutes the load can be a million per second, and then the load is reduced to zero) and dynamically scaled services. You can never find “the most representative” throughput since the throughput itself is derived dynamically from the load.</p><p>The following dashboards show that at 19:58 the estimated lag was ~4k minutes (25 weeks! :)), while in reality, the service closed the gap within a few minutes — at 20:01 the offset lag became zero.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kkNSP5qIDdnOVIxSa5Ljug.png" /><figcaption>Estimated time lag</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t3hSJXDMkvCNjtJpbZWWjg.png" /><figcaption>Offset Lag (green) became zero much earlier</figcaption></figure><p><strong>No future estimation. We need the actual Time Lag!</strong></p><p>To be honest, I don’t know how this metric is not exposed out-of-the-box by third parties like <a href="https://github.com/linkedin/Burrow">Burrow</a>, a linked-in project that does a perfect job of monitoring Kafka consumer groups, or by “Kafka-as-a-Service” providers like AWS MSK.</p><p>The idea is simple: keep an index of the maximum offset produced per topic partition per time unit, which will be used to compute how long events that are still not processed have been waiting.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vMlwZs6oryQkp2LGrOnqlw.png" /></figure><p>If it’s 08:40 now, and the service just consumed offset 10, it means that offset 11 (which was produced at 08:30) has been waiting for 10 minutes.</p><p>To formalize it, the Time Lag is actually:</p><blockquote>CurrentTime — LastTimeConsumedOffsetWasLatest</blockquote><p>By other words, the Time Lag is the time difference between the system time and when the consumed offset was the last item to process. The “age” of the message produced after it represents the data freshness of the service.</p><p>Once we have this Time Lag metric, the SLO dashboards of those stream services become much simpler. Returning back to the 25-weeks estimated time lag example mentioned above, now the SLO dashboard is based on a Kafka reality check:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JUVLoWaj6ZSOFtAiD1HkvQ.png" /><figcaption>25 weeks estimated time lag</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ARvQHwFMF5uLeD3ZPoRCQA.png" /><figcaption>11 minutes actual time lag</figcaption></figure><p><strong>The Architecture behind the scene</strong></p><p>To achieve this, I built a small “sub-system” with a very simple mission in life: compute the Time Lags for all monitored consumer groups based on information fetched from Kafka Admin API and push them to the monitoring system.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eid2gZ3vTUVRaiv2YVQiTA.png" /></figure><p>As a 1-minute time interval is granular enough for our use case, the <strong><em>Time-Lag Compute</em></strong> lambda is triggered by the Scheduler every 1 minute. It calls the required Kafka Admin APIs to get the produced offsets of all relevant topic partitions and the consumed offset for all topic partitions and consumer combinations. The consumed offsets are kept in a DynamoDB table (just because it’s the easiest to deploy, unlimited-scaled, and available DB I could find in AWS) with a TTL of 2 weeks. The <strong><em>Time-Lag Compute</em></strong> fetches the produced offsets only for the last 2 hours, as a time lag higher than 2 hours is bad enough to mark the SLO as red, so the actual time lag is not needed in this case. This can be easily adjusted to an higher value.</p><p>The produced offsets are loaded into <a href="https://docs.python.org/3/library/sqlite3.html">sqlite3</a> in-memory DB table which is created with the following structure:</p><pre>cursor.execute(&quot;DROP TABLE IF EXISTS producers_offsets&quot;)<br>cursor.execute(&quot;&quot;&quot;<br>            CREATE TABLE producers_offsets (<br>                epoc INTEGER,<br>                topic TEXT,<br>                partition INTEGER,<br>                produced_offset INTEGER<br>            )<br>        &quot;&quot;&quot;)<br>cursor.execute(&quot;DROP INDEX IF EXISTS idx_topic_partition_offset&quot;)<br>cursor.execute(&quot;&quot;&quot;<br>       CREATE INDEX IF NOT EXISTS idx_topic_partition_offset <br>       ON producers_offsets(topic, partition, produced_offset);<br>       &quot;&quot;&quot;)</pre><p>After data is loaded into the table, the code loops over the relevant topic partitions and consumers. If the consumer offset equals the produced offset, the time lag is set to zero to save the computing time. Otherwise, a simple query against the in-memory table is executed to get the max time when the produced offset is less or equal to the consumed offset. The gap between the monitoring time (“now,” which is set at the beginning of the lambda invocation) and the time returned by the query is the time lag.</p><pre>get_time_lag_query = &quot;&quot;&quot;SELECT max(epoc) as max_epoc FROM producers_offsets WHERE topic = ? AND partition = ? AND produced_offset &lt;= ? &quot;&quot;&quot;<br>for ((_group, _topic, _partition), _consumer_offset) in all_consumers_offsets.items():<br>    try:<br>        last_produced_offset = produced_offsets.get(TopicPartition(topic= _topic, partition=_partition)).result().offset<br>        if _consumer_offset == last_produced_offset:<br>            consumers_time_lags.setdefault((_group,_topic, _partition),(last_produced_offset, _consumer_offset, 0))<br>        else:<br>            cursor.execute(get_time_lag_query, (_topic, _partition, _consumer_offset))<br>            time_epoc = cursor.fetchall()[0][0]<br>            if time_epoc is None:<br>                # in case there is not any producer offset info collected for the last 2 hours, set 200 as default<br>                consumers_time_lags.setdefault((_group,_topic, _partition),(last_produced_offset, _consumer_offset, 200))<br>            else:<br>                time_lag = (minute_epoc - time_epoc) / 60<br>                consumers_time_lags.setdefault((_group, _topic, _partition), (last_produced_offset, _consumer_offset, time_lag))<br>    except KeyError as e:<br>        .....</pre><p><strong>So what have we achieved so far?</strong></p><ul><li>First and most important — the SLO dashboards and alerts are now based on the <strong><em>actual time lag.</em></strong></li><li>Business Orientation — The data-freshness metric has a great correlation to the <strong><em>business SLA</em></strong> as everyone can understand the business impact of data that is out-of-date.</li><li>Simple and elegant formula — The formula is useful even if the producer and consumer stop committing. The metric value keeps increasing as it’s bound to the system time.</li><li>Zero dependency on service reporting \ Watchdog approach — Even though metrics are emitted by a shared common library, the SLO sub-system doesn’t depend on numbers reported by the service itself. The SLO judgment relies on Kafka only as a source of truth and run as an external system. This aspect was so important that it became the main reason to reject the alternative approach of every consumer computing the time lag based on a time property/header embedded within the message itself.</li></ul><p><strong>There are some downgrades, as always.</strong></p><p>The approach makes perfect sense for our use case, but some aspects should be considered before adoption:</p><ul><li>Kafka broker load — as it heavily relies on data constantly fetched by the Admin APIs, there is additional load on the brokers. Scheduling 1-minute intervals didn’t impact our brokers dramatically but computing it more often probably will do, and maybe even require a different approach.</li><li>Bounded to commit offset cadence —this approach relies on Kafka offset committing to represent the service progress. If your service commits offsets periodically (like in Flink applications, where the offset is committed once the checkpoint is completed successfully, and checkpoints are generally scheduled in a few minutes’ time intervals), keep in mind that Time Lag value accuracy will be impacted by the offset update cadence.</li></ul><p><strong>What’s next?</strong></p><p>As you can see, a proper approach for SLO measurement and visualization was, and still is, a journey. After a few days of thinking and even starting to implement it, I found <a href="https://www.warpstream.com/blog/the-kafka-metric-youre-not-using-stop-counting-messages-start-measuring-time">this article</a> which basically served as “additional approval” of my thoughts and direction and also explained how time-lag is computed within WarpStream.</p><p>Since I didn’t find any OS project for computing Kafka Time Lag, my plan is to organize the code (terraform deployment + Python) and share it with the community.</p><p>Another aspect that will be addressed hopefully soon is the “Application SLO”, which will enable us to monitor the SLO of the entire application based on multiple services under the hood. The obvious approach that is already supported right now is to mark App SLO green only if all relevant services are green, but this may be too aggressive as a “Red” service may be covered by a “Green” one.</p><p>Sometimes, the approach to measuring and monitoring the system becomes pretty interesting and challenging, much more than you would expect. In the case of Kafka consumers, switching from message counts (offset lag) to time (time lag) simplified the SLO monitoring and made it much more connected to the business needs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d846c171b61c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Identify Job Completion in multi-phase Kafka consumers]]></title>
            <link>https://medium.com/@debyroth340/identify-job-completion-in-multi-phase-kafka-consumers-33ee8a974963?source=rss-fb5f5e4986c------2</link>
            <guid isPermaLink="false">https://medium.com/p/33ee8a974963</guid>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[architecture]]></category>
            <category><![CDATA[streaming]]></category>
            <dc:creator><![CDATA[Devora Roth Goldshmidt]]></dc:creator>
            <pubDate>Thu, 11 Jan 2024 08:01:38 GMT</pubDate>
            <atom:updated>2024-01-11T08:03:01.178Z</atom:updated>
            <content:encoded><![CDATA[<p>Even the title raises some questions. If it’s a job that partially has a start and end, why run it over an unbounded stream system like Kafka?</p><p>There are some cases where the system should identify when the end-to-end processing of an unbounded stream is completed. One could argue that this is a kind of abuse of running a batch job in a streaming system, and she’s probably right! But sometimes this “<em>abuse</em>” is a “<em>reuse</em>”: when there is a need to leverage an existing streaming system for batch processing as well.</p><p>For example: the architecture of the AML Detection in our company consists of several event-driven services that interact between them by Kafka even bus, so the ongoing production data is flowing through Kafka topics and processed by a streaming framework (Apache Flink). But there is another business case where the user wants to trigger a Back Testing Job which simulates a given detection configurations set over a historical data set to measure the quality and accuracy of the detection results. As part of the job submission, the user selects the specific time range she wants to simulate hence the job has very concrete boundaries. This job should be monitored and its status communicated to the user. Once marked as completed, the user should be able to analyze the results.</p><p>But this simple requirement raises a challenge: how can the system identify the “completion” of a job in stream processing? And this becomes even more tricky when a few different stream processes are involved…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2Yqby9gjVvAlqccQs1nyzw.png" /><figcaption>Identify job completion in multi-phase stream processing</figcaption></figure><p>As you can see in the diagram, there are multiple services involved. Some of them are sequential, meaning handling different types of events, while others are consuming events from the same topic in parallel. More than that, for any given input event a service may produce zero or more output events, based on its business logic.</p><h4>Approach #1: Every producer emits a max offset record when reaching the previous max offset</h4><p>We are lucky enough and we are using Kafka. As you know, Kafka manages and tracks the offsets. The offset actually identifies the unique position that the record has inside the partition. Kafka also tracks the latest offset committed by any consumer group of a particular partition.</p><p>The very fundamental assumption here is that every service in the chain <strong>commits the offset of the input topic only after the event is processed completely</strong>, including writing to all relevant sinks. Sinks can be one or more target topics and one or more target DBs. Only once all of them are updated successfully (if needed), the offset of the input topic is committed.</p><p>The idea is that every producer should track the max offset per partition it produced into for a given job, and produce this info as a <em>Max Offset</em> system event into the <em>Job Tracking</em> topic. The Max Offset event contains Job ID, Topic Name, Partition Number and Max Offset. When the <em>Job Trigger </em>service finishes producing events into the first topic, it should emit the <em>Max Offset</em> events into the <em>Job Tracking</em> topic. Those events are consumed by all other services, each one in its own consumer group.</p><p>Once the next service which is <em>Service #1</em> consumes a <em>Max Offset</em> event, it compares the offset to the latest one that it’s currently processing. If its current offset is equal to or higher than the max offset, it produces its own current offset as <em>Max Offset</em> events into the <em>Job Tracking</em> topic and only then commits the offset of the input topic. If it hasn’t reached the <em>Max Offset</em> yet, it keeps processing input events, until it’ll reach it.</p><p>The <em>Job Monitor</em> is an external component that consumes the <em>Job Tracking</em> topic as well as the internal Kafka <em>__consumer_offsets</em> topic to identify a job completion. To do that, it has access to the <em>Job Type Topology</em> that defines the different steps every job type is consisting of. This typology information is needed for keeping every process in the chain agnostic to the previous and next processes and also enables parallel processes in the chain. The Job Monitor keeps tracking the relevant consumer groups and waits until all consumer groups are reaching the desired max offset for a given job. Once all consumer groups of all topics’ partitions required for a specific job reach the max offset, it marks the job as Done!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dxwlBfKzhI1UtkSAkWEvhg.png" /></figure><h4>OK. But this sounds very complex!</h4><p>Indeed one of the downgrades of this approach is the complexity. Even though it can be mitigated by some code sharing and abstractions, it still means that every Service should add a piece of code (sources and sinks) to handle this job tracking. This code will be used only for batch running (like Back Testing, Maturation, etc) and not for the ongoing pure event-driven flow coming from production data.</p><p>This made me think about alternatives. Can we achieve the same goal by external monitoring only?</p><h4>Approach #2: Offsets “snapshot” is taken and monitored externally by the Job Trigger</h4><p>Like the previous approach, the assumption here is that every process in the chain commits the offset of the input topic only after the event is processed completely, including writing to all relevant sinks.</p><p>But the main difference here is that the only impacted component is the first <em>Job Tigger</em> which should produce a <em>Job Load Finish</em> system event that indicates the job data was successfully ingested into the first topic. That’s all. No offset information is provided!</p><p>The <em>Job Monitor</em> is the only consumer of the <em>Job Tracking</em> topic. Once it gets a message that Job J1 data events were loaded successfully, it takes an “offset snapshot” by asking the Kafka Admin for the latest offset per partition as it is right now in topic T1, and keeps it. The <em>Job Monitor</em> keeps tracking the relevant consumer groups based on the Job Typology (CG1 in this example) until they reach the desired offsets defined in the snapshot. Once done, it takes an “offset snapshot” of the next topic (in this case topic T2) and starts tracking the relevant consumer groups (CG2 and CG3 in this example). Once there are no more topics and CGs to track, the job is marked as completed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gjchOxI1FLunIfugos4bnA.png" /></figure><h4>This is much simpler!</h4><p>Indeed, this approach keeps the service code clean and simple. There is not any change in the services themselves, all tracking is done externally.</p><p>Indeed, it means that we are tolerant for a delay in the job completion identification which is acceptable in this case. Anyway job can be running for hours and even for days, so no user really cares if they are marked as “Completed” in 20 20-second delay…</p><p>An additional technical point to mention is that currently the <em>__consume_offsets</em> topic doesn’t include any header that can be used to filter offsets changes only about topics T1 and T2. So the <em>Job Tracking</em> may consume all offset commits of every topic that exists in the cluster. One approach is to manage all those relevant topics under a dedicated broker, which may be very hard to operate. Another alternative in case other topic updates are very busy and increase significant overhead is to continuously poll the Kafka Admin API to fetch the latest consumer groups’ offsets only for the required topic. As long as it’s acceptable to limit the polling rate to ~1-second interval, this approach can perfectly work.</p><h4>To Summarize</h4><p>So you probably already realized that tracking a bounded-stream job in an unbounded-stream system may be pretty tricky. But if the accuracy is not critical, the Kafka Offset is a robust mechanism that can be leveraged for that.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=33ee8a974963" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The hidden cross AZ cost: how we reduced AWS Data Transfer cost by 80%]]></title>
            <link>https://medium.com/@debyroth340/the-hidden-cross-az-cost-how-we-reduced-aws-data-transfer-cost-by-80-836b6d06886d?source=rss-fb5f5e4986c------2</link>
            <guid isPermaLink="false">https://medium.com/p/836b6d06886d</guid>
            <category><![CDATA[cost]]></category>
            <category><![CDATA[availability-zone]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[istio]]></category>
            <category><![CDATA[data-transfer]]></category>
            <dc:creator><![CDATA[Devora Roth Goldshmidt]]></dc:creator>
            <pubDate>Thu, 26 Oct 2023 12:15:18 GMT</pubDate>
            <atom:updated>2023-10-26T12:15:18.404Z</atom:updated>
            <content:encoded><![CDATA[<p>As expected, AWS services are not for free. And we, as BTB SaaS, are not free either. We definitely try to minimize the infrastructure cost as much as possible to increase the gross profit margin.</p><p>When I started my journey as a Cloud Software Architect a few years ago, I heard many stories about huge unnecessary instances that were kept up and running for days or how to leverage spot instances optimization (which I’m not sure are still so economic those days, but this is subject to another article). Everything sounded pretty straightforward: we mainly need to track resource consumption and automate the shutdown of unused ones.</p><p>But nothing prepared me for the supersize in our AWS production billing report: the most expensive service, the one that takes 25% of the cost, is cross-AZ data transfer! Not the compute of running a 100 nodes EKS cluster, nor the various types of Databases, while some of them are pretty “managed and expensive” like AppStream, Dynamo, and ElasticSearch, not our MSK Kafka cluster, but the amount of data transferred between AZs within the region…</p><p>After talking to our AWS account manager, the assigned solution architect, and the AWS billing expert I realized we are not alone. Many companies suffer from this hidden cost, both in the aspect of not estimating it correctly or struggling with investigation and optimizations. I can think of several reasons why this is so common:</p><ul><li>Highly Available Distributed Systems — we are all encouraged and educated to use multiple AZs to increase service availability. Multiplying it by the number of microservices that talk to each other, DBs, Kafka topics, and all sorts of data that should be replicated, increases the cross-AZ traffic. Even though it doesn’t necessarily mean that every hop/API call between microservices should necessarily cross the AZ boundary, it increases the probability, especially if you are not aware of it.</li><li>Hard debugging — even if you have the correct tooling (like <a href="https://docs.aws.amazon.com/vpc/latest/userguide/flow-logs.html">VPC Flow logs</a> which is indeed very useful), it’s pretty complicated to consider where the traffic is coming from and where it’s going. This becomes more challenging when it comes to running EKS (k8s) across multiple availability zones with all its internal components, including control and data planes.</li><li>Bi-directional pricing — without debating if AWS documentation is misleading or not, but when you read “<em>cross AZ data transfer within the region costs $0.01/GB” </em>don’t be confused: effectively, it’s 0.02$ per GB since each transferred gigabyte counted as 2GB on the bill: once for sending and second for receiving. If you have 2 EC2 instances on different AZs and 1 GB is transferred between them, it’ll pay 0.02$ under different <em>operations </em>in Cost &amp; Usage terms: <em>InterZone-in</em> and <em>InterZone-out</em>. But from the other hand, it also means that once you optimize and reduce x transferred GBs, you get back 2x cents :)</li></ul><h4>We got the challenge. What can we do with that?</h4><p>The first step is obvious but may be misleading: monitor the different components located on AZs but focus on the right resources and the right metrics.<br>Luckily enough, <a href="https://docs.aws.amazon.com/account-billing/">AWS Cost &amp; Usage reports</a> support resource level granularity, so I could easily aggregate the amount of data transferred out from or transferred into a specific instance per hour. This way I noticed that there are actually 7 problematic instances, all of them EKS k8s nodes, that are responsible for 70% of the traffic, while all other 73 nodes consume 30% only. It was also pretty clear that it’s not a k8s common issue but more about specific PODs running there… This helped me focus on <strong>the right resources</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wFZjxJubfgksRtpfSrjQLw.png" /><figcaption>Few resources are responsible for most of the traffic</figcaption></figure><p>When presenting the <em>kubernetes.network.tx_bytes</em> metric per every POD located in any of those nodes, it was clear that we have two interesting directions: the blue one which statistically transmitted 100 MiB/s, and the purple one with many picks that on average transmitted 20 MiB/s. Remember that transmitted out from the POD doesn’t necessarily mean out from the node (and cross nodes traffic doesn&#39;t necessarily cross AZs), it may be POD internal communication within the node.<br>For that, I added <em>aws.ect.network-out</em> metric which is at a node level and verified that summing up those PODs traffic is aligned with the traffic that went out from the mentioned 7 nodes. So looks like I’m focusing on the <strong>right metrics</strong> which gave me an idea of which services to blame…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DH2xEiNUO18MkOS8_6Hnsg.png" /></figure><h4>Istio certification refresh issue</h4><p>The blue line presented <a href="https://istio.io/">Istio</a> PODs. For one who is less familiar with that, Istio is a service mesh that can be used for traffic management, observability, and security. In our case, it’s used mainly for role-based access, authentication, and authorization across k8s services. The interesting point was that the continuous traffic was coming from <a href="https://istio.io/latest/docs/ops/deployment/architecture/#istiod">istiod</a> PODs that are part of the Control Plane and mainly used for certificate management, so why they kept working so hard, even when there were not any new deployments in the cluster and nothing really changed there?</p><p>When digging into istio logs, it showed like istiod Pilot triggered a full push of certificates to all PODs, even if they are not changed at all! Notice the <em>full=true </em>at the end of the log message. The average certificate size is 100–300 KB multiplied by ~900 PODs, you can imagine how much traffic is going out from istiod…</p><pre>2023-09-27T11:51:33.844081Z info ads Push debounce stable[59230] 3 for config ServiceEntry/prod-0-flink-jobs/prod-0-594133-p-con-flink-mgmt-s1-196a81c4-e-rest.prod-0-flink-jobs.svc.cluster.local and 1 more configs: 100.052469ms since last change, 102.888669ms since last push, full=true<br>27-9-2023 14:53:04.862<br>2023-09-27T11:53:04.862282Z info ads Push debounce stable[59250] 3 for config ServiceEntry/prod-0-flink-jobs/prod-0-594133-p-con-flink-mgmt-s1-6c2fac16-8-rest.prod-0-flink-jobs.svc.cluster.local and 1 more configs: 111.327819ms since last change, 111.332977ms since last push, full=true<br>27-9-2023 14:53:49.739<br>2023-09-27T11:53:49.735887Z info ads Push debounce stable[59267] 3 for config ServiceEntry/prod-0-flink-jobs/prod-0-594133-p-con-flink-mgmt-s1-10509001-3.prod-0-flink-jobs.svc.cluster.local and 1 more configs: 104.05515ms since last change, 104.06017ms since last push, full=true<br>27-9-2023 14:55:20.810</pre><p>When trying to understand where the full pushes are coming from, we noticed that we have a single k8s deployment in a <em>CrashLookBackOff </em>state, and together with <a href="https://github.com/istio/istio/pull/40595">istio dead-loop bug</a>, it caused a constant certificates refresh for all PODs in the cluster…</p><p><strong>Two important takeaways:</strong></p><ul><li>Keep monitoring your cluster healthiness — don&#39;t ignore any deployment with an unhealthy state. You can never know how costly they are…</li><li>Debugging cost issues is a great way to discover functional bugs! If something costs us too much, it may be just implemented wrongly.</li></ul><p>Once we fixed the issue by removing <em>CrashLookBackOff </em>deployment<em>, </em>the daily cross AZs data transfer by 95% which cut our AWS daily cost by 23%. Crazy.</p><h4>Data Shuffling between stream operators</h4><p>But the story didn’t finish… After a few more days, I realized the cost had risen again. Not to the original high value, but still:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yX3rbCAJY4fokLJ0BX_NGA.png" /></figure><p>The same production traffic and data volumes, the same services, what’s going on?</p><p>Then I returned back to the original <em>kubernetes.network.tx_bytes</em> metric graph and noticed that the purple line was not reduced, meaning the service kept consuming 20MiB\s. But I need to answer two questions: (1) why was production cost not stable if the service behaved like this during the entire period? (2) why did the service behave like this? 20MiB\s is very high!</p><p>So the purple line presented a service whose job is to consume all data in our events bus, meaning every topic, and persist them parquet files stored in S3. When this service was initially designed, a decision was that S3 objects would be created at a level of a tenant, event type, and time bucket. For example, a file per <em>[tenant-123]-[event-type-A]-[26.10.2023-10:50] </em>that contains all events of type A for tenant-123 consumed at this minute. This service is implemented, like all our streams processed, as a <a href="https://flink.apache.org/">Flink</a> job with multiple operators. First operators consume from Kafka and decrypt the messages, which are then sent to <a href="https://nightlies.apache.org/flink/flink-docs-master/docs/dev/datastream/operators/overview/#keyby">KeyBy</a> operator that logically partitions a stream into disjoint partitions so that all records with the same key are assigned to the same partition and will be stored in the same file.</p><p>But here is the point: this operator is pretty expensive! the fact that all data flowing through Kafaka should be grouped logically, crossing the boundaries of the Kafka partitioning strategy, may create huge data re-shuffling between the operator instances!</p><p>Just to reflect the current behavior visually, if we take the <em>kubernetes.network.tx_bytes </em>of one consumer (or actually a Flink task manager that executes this operator) and add <em>kubernetes.network.rx_bytes </em>of a second consumer, those two lines are almost identical which means that almost all data is shuffled between the two!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/893/1*TasURoVxhM_DKoHp0yohOQ.png" /><figcaption>Graph representing the data shuffling</figcaption></figure><p>So what can we do with that? very simple: we could decide that a file per <em>[tenant-123]-[event-type-A]-[26.10.2023–10:50]-[consumer-id]. </em>And no client really cares, since anyway get a list of objects per S3 bucket path and know how to handle multiple ones. If we are adding the consumer level, the data grouping is internal to the operator and doesn’t require physical data shuffling.</p><p>Returning back to the first question of why production cost was not stable? Now we can understand it: because it’s traffic between two PODs, we are very dependent on where k8s locate them. If by any chance they are co-located under the same node or different nodes on the same AZ, no cost. If they are located on different nodes on different AZ — we’ll pay for 1TB data transfer daily…</p><p>When I added additional k8s metrics tags (host and AZ), I realized that this is exactly what happened in Prod: the cost is directly driven from those PODs locations.</p><p><strong>Two important takeaways:</strong></p><ul><li>Even if you think the issue was fixed, keep monitoring your cost! It may be changed even with the same code base and the same data volumes…</li><li>Any simple design decision can dramatically impact the cost! It’s obvious when you choose DB technology but even when choosing the exact granularity of the S3 objects you store (and no one really cares about it, just a decision), it may impact the cost significantly…</li></ul><h4>Rack-aware Kafka consumers</h4><p>When it comes to Kafak consumers, one of the features that were introduced by Apache Kafka 2.4 is <a href="https://cwiki.apache.org/confluence/display/KAFKA/KIP-392%3A+Allow+consumers+to+fetch+from+closest+replica">Kakfa consumers fetching the from closest replica</a> which can definitely optimize the reduce the cross AZs traffic in multi-AZ Kafka cluster. The idea is very simple: if the consumer knows in which rack it’s located, the broker can let it consume from the in-sync-replica of the partition located on the same AZ and not necessarily from the partition leader.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vXoQ7DtJf8QjHGG8nZXN7g.png" /></figure><p>As long as replicas #1 and #2 are kept in sync, every consumer consumes the data from the closest respective replicas.</p><p>This change was not yet implemented, but by looking on <em>aws.kafka.bytes_out_per_sec</em> metric which represents the number of bytes sent to kaka consumers, we can reduce the daily data transfer by an additional ~30GB which sounds pretty low but can increased dramatically relative to the input data volumes.</p><h4>Conclusions (as-for now :))</h4><ul><li>Tracking cross AZs data transfer cost may be pretty challenging but if you go with a data-driven approach based on the “correct data“ (in this case metrics mainly), you’ll probably find a lot of space for optimizations.</li><li>As mentioned earlier, cost issue investigation is not for reducing your expenses. It’s also a great way to find bugs, which I’m sure everyone has.</li><li>And finally, the main idea here is to eliminate the cross-AZ data transfer. But reducing the <em>hidden one</em>: knowing where it comes from, whether it makes sense, and whether you are willing to pay for it…</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=836b6d06886d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SLO Monitoring of Event-Driven Architectures]]></title>
            <link>https://medium.com/@debyroth340/slo-monitoring-of-event-driven-architectures-b35d2a2d8043?source=rss-fb5f5e4986c------2</link>
            <guid isPermaLink="false">https://medium.com/p/b35d2a2d8043</guid>
            <dc:creator><![CDATA[Devora Roth Goldshmidt]]></dc:creator>
            <pubDate>Tue, 18 Jul 2023 12:33:23 GMT</pubDate>
            <atom:updated>2023-07-18T12:33:23.419Z</atom:updated>
            <content:encoded><![CDATA[<p>Every SaaS journey probably begins with observability, which is the essential capability to gather data from metrics, logs, traces, and other sources, and use that data to form a complete picture of a system’s behavior, performance, and health.</p><p>One of the most critical aspects we aimed to accurately and efficiently monitor is the SLO (Service level objective) that provides clear targets around the system performance and focuses the development teams. The SLO is derived from the <strong>SLA </strong>(Service level agreement), the legal agreement with our clients. For example, the SLA may state that the system will complete the full processing of an uploaded file with <strong><em>1MM input events within 4 hours</em></strong>. Out of it, we estimate how many tenants will be deployed in a particular environment, how many parallel tenants will upload files concurrently, and what buffer we should take. Taking all those parameters into consideration, we may end up with a system <strong>SLO of </strong>processing <strong><em>5MM events within 3.5 hours</em></strong>.</p><p>So far so good. The challenge starts with measurement: how can we continuously make sure that the system meets this SLO? how can we predict a future SLO violation as soon as possible (preferably not after all 3.5 hours were passed…)</p><p><strong>Why is it so challenging?</strong></p><p>First, it’s a distributed asynchronous system. Multiple services are involved in this data processing flow, most of them consume events from one or more Kafka topics and either produce new events or do something with them (most commonly — persist to DB). We have to build a solution that will monitor all relevant services as each may impact the overall SLO.</p><p>Secondly, the processing is not one-to-one. Every consumer can emit zero or multiple output events per single input event. Also, a consumer may group several input events into a single output one. So knowing when a specific event is “completely processed” is not a trivial task, since even if the service already produced output for the incoming event, who knows if additional output will be produced a second after? and if no output, who knows if the event is discarded correctly?</p><p>This gets even harder when those output records are derived from the business logic which is fully configurable by the tenant’s user. Our customers can tune the system by updating thresholds and defining their own logic to meet their business strategies. So that even if there are rough estimations of the amount of the output every “tenant type” may expect, the number of output events for any given input event at any given point in time is unpredictable.</p><p>The below diagram presents just a subset of the different services involved in the data pipeline, with the estimated ratio between the input and output events for a well-tunned system:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SikIY59GI9L0-hla9ONBrw.png" /></figure><p>So what is the most efficient way to measure this system’s SLO?</p><p><strong>Approach #1: Continuously upload a synthetic file and expect to get the Y known results within X minutes</strong></p><p>This is the most native and simple way we started with. We assume the system is scaled almost linearly so if 5MM events processing takes 3.5 hours, 1K events processing should take less than 5 minutes. So every 5 minutes the system uploads a file with 1k synthetic events of an artificial test tenant with pre-defined business logic and thresholds, leading to a known number of expected output events. The test is green only if the time between file ingestion to the point all expected outputs are generated is below 5 minutes.</p><p>This was pretty easy to start with but the disadvantages were:</p><ul><li><strong>Aggressive Sampling</strong> — it considers only this particular test tenant data. If this specific file is completed within the expected time but all other real tenants are stuck, the SLO dashboard is still green.</li><li><strong>Synthetic data only</strong> — it doesn’t consider any real tenant data, so the high change is that it doesn’t reflect the actual output events created in reality.</li><li><strong>SLO violation alarm only after 10 minutes</strong> — only after the 10 minutes are passed and no expected results, the alert is created. It may be too late…</li></ul><p>Worth mentioning that even if this approach is less useful for SLO monitoring, it is very useful for <em>system health. </em>For example,<em> </em>detecting a scenario when the processing is so fast and meets the SLO just because all business logic was deleted or turned off for some reason…</p><p><strong>Approach #2: Distributed Tracing of a single event through the entire pipeline</strong></p><p>Then we started thinking about a more accurate way to monitor the SLO, considering the real tenants&#39; traffic in production.</p><p>The idea we thought about is fixing a timestamp on every event going into the system (let’s say, ingestion time), and propagating this ingestion time through the entire pipeline for calculating the event processing latency: the time it takes to flow through the entire system. This timestamp needs to be assigned to all intermediate events that have been created, potentially from multiple input events. Whenever an input event is discarded (either due to a failure, issue or this is the business logic) this particular service should mark this event as done and emit the latency. If parallel processors may not complete the processing yet, we need to deal with multiple “latencies” for the same input event and compute the “overall event processing time” by taking the max, considering some timeout.</p><p>This is probably the most precise way to measure the SLO, it’s based on real tenant data and also enables us to identify issues pretty soon. The estimated throughput is 1/AVG(latencies) * available parallelism so pretty soon we can identify that there is an issue and the system is not going to handle 5MM within 3.5 hours.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HFwlpbNOPi7hS8pHo0e55Q.png" /></figure><p>The main disadvantage of this approach is <strong>Cost. </strong>Omitting so many traces from a system that handles millions of events, multiplied by multiple services is very costly. Either from the persistence aspect of keeping all this info in a DB and also from the need for computing the latencies\throughput\SLO over them in near real-time.</p><p><strong>Approach #3: Measuring the success rate between input and output events within a pre-defined time window</strong></p><p>The next thought was relying on the above ratio between input and output events and measuring the success ratio between them. For example, we assumed above that for given 1MM input events, only 1K patterns will be identified by the last service in the chain.</p><p>So we can create a metric M1 that counts the number of input events ingested per second and another metric M2 that counts the number of output events (patterns in this case) produced at the end of the process. Because we expect only 0.1% of the input events to result in output events, then we set the SLO to be green if the current value of M2 is 0.01% of the value of M1 from 5 minutes ago.</p><p>The disadvantage is clear: <strong>Success Rate assumptions. </strong>The approach assumes the number of output events that should be produced for a given input event. It may not accurately reflect the actual success rate needed for the system to function properly. Additionally, as stated above, the success rate can be influenced by various factors such as business configuration and system tuning. So an estimated number of outputs can not be the measurement…</p><p><strong>Approach #4: Measuring service processing rate and Kafka lag</strong></p><p>Then we switched our minds and agreed that those ratios are useful but not as measurements.</p><p>The ratios are used for <em>estimating </em>the required throughput from every service. How is it done? dividing the overall time of 3.5 hours between the different phases will cause underutilization and over-provisioning as events can be handled in parallel. A more efficient approach is to calculate the desired throughput by subtracting all other phase latencies of a single event from the total time, divided by the estimated number of events (i.e. the required throughput from Validator service is: 3.5 hours minus 2 minutes latency to handle a single event w/o Validator, divided by 1MM).</p><p>In order to verify that the service handles the desired throughput expected from it, we monitor the <strong><em>Service Processing Rate </em></strong>metric which is the number of input events that have been processed completely in this time unit (regardless of how many output events have been produced).</p><p>In addition, a very important metric to consider is the <strong><em>Service Kafka Lag</em></strong> which presents how far this particular consumer(s) is from the last offset committed to the topic. Considering the lag is crucial for two reasons:</p><ul><li>Even if the <strong><em>Processing Rate</em></strong> is low, the SLO should be green in case the lag is (almost) zero. Meaning, it’s ok that a service reports low throughput if no work for it…</li><li>Even if the <strong><em>Processing Rate</em></strong> is bigger than the pre-defined desired service throughput, in case the lag is too big it may mean that the system is not sized efficiently and we are not going to meet the 3.5 overall SLO. Remember, the ratios were just estimated. If in reality there are more events to handle, the desired throughput should be adjusted.</li></ul><p>In addition, the formula should be tolerant to the service scaling time, as low throughput may be reported for the service just ramping up or during scaling time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/957/1*k1hQLMDEJo3X1rCIKwbnTQ.png" /></figure><p>This can be achieved by different approaches: simply increasing the time window and verifying that the max metric value within the window is bigger than the threshold. We could compute a moving average and track the growth rate or use any other exponential smoothing technique (simple or Holt-linear) for tracking the trend and making sure it’s high enough.</p><p><strong>So what am I saying, actually?</strong></p><p>At this phase, I can’t share with you the exact formulas used under our SLO Monitoring dashboard, as it still requires some tuning and adjustments.</p><p>But the first goal was to decide on the measuring approach and identify the relevant metrics. And it feels like this was achieved. The only way to “measure” the measurement is to use it over time and track how many real production issues have been identified and solved even before they “occurred”, at least from the client side.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b35d2a2d8043" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How we (almost :)) achieve End-to-End Exactly-Once processing with Flink]]></title>
            <link>https://medium.com/codex/how-we-almost-achieve-end-to-end-exactly-once-processing-with-flink-28d2c013b5c1?source=rss-fb5f5e4986c------2</link>
            <guid isPermaLink="false">https://medium.com/p/28d2c013b5c1</guid>
            <category><![CDATA[stream-processing]]></category>
            <category><![CDATA[apache-flink]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[exactlyonce]]></category>
            <dc:creator><![CDATA[Devora Roth Goldshmidt]]></dc:creator>
            <pubDate>Mon, 29 Aug 2022 04:33:09 GMT</pubDate>
            <atom:updated>2022-09-08T01:51:06.642Z</atom:updated>
            <content:encoded><![CDATA[<h3>How we (almost :)) achieve End-to-End Exactly-Once processing with Flink</h3><p>Distributed stateful stream processing is challenging, especially in regard to handling failures and recovery. In stream processing, one of the most frequently asked questions is “<em>does my stream processing system guarantee that each record is processed once and only once, even if some failures are encountered in the middle of processing</em>?”</p><p>By saying “<em>exactly-once</em>” semantic I mean that each incoming event affects the final results exactly once. Even in case of a machine or software failure, there’s no duplicate data and no data that goes unprocessed. We are using Apache Flink, a distributed stream processing engine that has long provided exactly-once semantics <em>within</em> the Flink application itself. Flink generates checkpoints on a regular, configurable interval and then writes them to a persistent storage system with the attached position in the input stream. During recovery from a failure, Flink resumes processing from the most recent successfully-completed checkpoint. Flink’s checkpoint algorithm is based on a technique introduced in 1985 by <a href="https://en.wikipedia.org/wiki/Chandy%E2%80%93Lamport_algorithm">Chandy and Lamport</a> to draw consistent snapshots of the current state of a distributed system without missing information and without recording duplicates</p><p>But by saying “<em>end-to-end</em>” I mean extending the exactly-once semantic to the external system which involved — which Flink sends data after processing. Imagine a very standard and simple process that consumes events from Kafka topic, performs tumbling windows of 1 minute and once the window is expired, writes all events to a DB. So that events are grouped into 1m buckets and written by a single bulk insert operation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ntHdQGaUOAA5pk0B-k0m2w.png" /><figcaption>Stream processing with external state</figcaption></figure><p>Obviously, the desired situation is that all incoming events will eventually appear in the DB but only once.</p><p><strong>Idempotent Writing</strong></p><p>In case the application writes records with associated consistent unique identifiers, exactly-once can be achieved by an idempotent implementation of writing to DB. This means, instructing the DB to just ignore or override duplications so that even in case of re-processing of the same events there won’t be a real impact on the external table.</p><p>Returning back to the example application which writes the raw events to DB once a minute, every event has an associated ID that can be used as table PK. Assuming Flink checkpoint is triggered every 5 seconds, a failure may happen between two checkpoints. In this case, Flink will recover from the last checkpoint and replay from there. Actually, all messages from the last checkpoint will be re-processed and sent to the DB (all events within the <em>dotted red line</em> in the diagram below) but they’ll be ignored since this is an attempt to write the same event ID twice.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AuJ3q1mWEg1nbh1ZqSk8Vw.png" /><figcaption>Re-processing of the dotted timeline events, but DB ignores them</figcaption></figure><p>One can argue that this pattern is actually stateless events processing which Flink might be an overkill solution for. The complicated Flink checkpoint mechanism is very useful when there is a state distributed across multiple nodes and should be persisted properly but this app could be simply implemented by native Kafka consumer/produce APIs, group the events, write them down and only then commit the Kafka offset. In case of any consumer timeout or re-try, the same message will be re-processed but w/o a real impact. I agree. If every application was deterministic and idempotent, our life would be much easier (or boring :)).</p><p><strong>Kafka Transaction</strong></p><p>In case the application is in a form of consume-process-produce from an inbound and into an outbound topic, producing messages through Kafka Transaction API may be a good choice of consuming, processing and producing a message by an atomic operation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sBusG7_Xy5krRQ7xYM1eng.png" /></figure><p>The key here is that any downstream Kafka consumer that polls the outbound topic will only ever receive those resulting messages once — it is guaranteed there will not be duplicates, even if the data sink needs to retry producing the message. Failure scenarios may mean that the original message is consumed and processed (or partially processed) multiple times, but this will never result in duplicate outbound events being published.</p><p>In order to leverage this technique, all those three operators (source, window and sink) should run on the same component so that the producing of any outbound message will be surrounded by the same transaction that commits the consumer offset. The following is the transactional flow:</p><ol><li>Service calls beginTransaction for initiating a new transaction</li><li>Service publishes messages by the Producer</li><li>The consumer offsets are also sent to the Producer for being included in the same transaction</li><li>Service calls commitTransaction to complete the transaction</li></ol><p>For supporting transactional producing, Kafka introduces new components and concepts like Consumer Coordinator, Transaction Coordinator, and Transaction Log which are detailly described in <a href="https://docs.google.com/document/d/11Jqy_GjUGtdXJK94XGsEIK7CP1SnQGdp2eF0wSw9ra8/edit">their &gt; 60-page design document</a>, but it’s important to realize that all other actions occurring as part of the processing can still happen multiple times, on the occasions where the original message is redelivered. If, for example, the application performs REST calls to other applications or performs writes to a database, these can still happen multiple times. The guarantee is that the resulting events from the processing will only be written once.</p><p><strong>Two-Phase Commit Approach</strong></p><p>There is another type of application that consumes from Kafka, performs some aggregation and then writes results to external DB. It’s generally pretty hard to implement idempotency since aggregation values may be changed, but on the other hand, they can not really benefit from Kafka transaction since it’s anyway not bounded to the DB transaction.</p><p>Let’s change our original example a little bit so that instead of writing the raw events, it counts the number of events that happened during the 1-minute window and writes this aggregated value (just the number) to a DB. Obviously, our topic has several partitions and several instances of the source, windowing and data sink operators running in parallel. There isn’t any keyBy or logical partitioning required by the business, we simply want to count events in a minute granularity. Trying to achieve idempotent writing: what should be our record identifier in the aggregation table? Defining it like <em>&lt;Sink Instance ID, minute&gt;</em> is problematic because nothing guarantees that the same events will be sent to the same operator instances after the recovery. The below diagram presents a potential situation where a specific sink operator instance originally processes e45, e47, and e52 events but after the recovery from the last checkpoint, it gets e48, e49, and e50 (just because it now gets windows different upstream windows operator).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wFBKuQVSRD-X47Nf3yZZBg.png" /></figure><p>Flink feature of <a href="https://nightlies.apache.org/flink/flink-docs-master/api/java/org/apache/flink/streaming/api/functions/sink/TwoPhaseCommitSinkFunction.html">TwoPhasedCommitSink</a> feature can be really useful. For achieving exactly-once in this scenario, Flink enables coordination of writing to an external system with its internal checkpoint mechanism. The external systems must provide a means to commit or roll back writes so that those events can be triggered and coordinated with Flink’s checkpoint management. One common approach for coordinating commits and rollbacks in a distributed system is the <a href="https://en.wikipedia.org/wiki/Two-phase_commit_protocol">two-phase commit protocol</a>. The two-phased-commit sink should implement four different methods that Flink will call during the various phases of the checkpointing process:</p><ol><li>beginTransaction a transaction bundles all writes between two checkpoints, so writes are always within a scope of a transaction. This function is called at the beginning of a new checkpoint. So here you can open a DB transaction if your DB supports it, or create a temporary file in the file system. All subsequent event processing will use it until the next checkpoint.</li><li>preCommit the pre-commit is called by the sink once it gets the checkpoint barrier after successfully persists its internal state. This will be called by every sink so that Flink JobManager (the coordinator) can commit the checkpoint only after all sinks perform the pre-commit successfully. Here, you can flush the file, close it and never write to it again. Or alternatively, start a new DB transaction for any subsequent writes that belong to the next checkpoint.</li><li>commit the commit will be called by every sink only once the JobManager notifies them that the checkpoint is completed. In this phase, you can atomically move the pre-committed file to the actual destination directory or alternatively commit the DB transaction.</li><li>abort abort function will be called as distributed checkpoint has been aborted or when aborting a transaction that was rejected by a coordinator after a failure. Here, for example, you can delete the temporary file or abort the DB transaction.</li></ol><p>Notice that this sink implementation is working natively with DB that does support transactions. But even in our case where the sink writes down the aggregations to AWS AppStream (TimeSeries DB), a custom implementation of the TwiPhasedCommit function is possible and the actual DB writing should be postponed to the commit phase.</p><p>The important point to notice is that after a successful pre-commit, the commit <em>must</em> be guaranteed to eventually succeed — both our operators and our external system need to make this guarantee. If a commit fails (for example, due to an intermittent network issue), the entire Flink application fails, restarts according to the user’s restart strategy, and there is another commit attempt. This process is critical because if the commit does not eventually succeed, data loss occurs.</p><p>Therefore, we can be sure that all operators agree on the final outcome of the checkpoint: all operators agree that the data is either committed or that the commit is aborted and rolled back.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bv77amtrpdUXGens6dyofg.png" /><figcaption>DB Writing is attached to the Checkpoint mechanism</figcaption></figure><p>So what we eventually achieved is that the actual DB writing is performed in the same “transaction” of the persisted checkpoint and the consumer offset.</p><h3><strong>Summary</strong></h3><p>Dealing with stateful processing in a distributed system, especially when different external data sources or sinks (Kafka and DB) are involved, is challenging. Duplicate messages are an inevitable aspect of the fact that every component may fail temporarily or forever. Flink’s checkpointing system serves as Flink’s basis for supporting a two-phase commit protocol and aims to provide end-to-end exactly-once semantics. As stated above, there may be rare cases where the transaction won’t be completed, Flink will re-start and re-try forever (or until AWS will solve their AppStream outage…) but this is supposed to be a really rare case that probably this famous joke is considering:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/539/1*hb_vWnvj2wORSsyDJ_L85w.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=28d2c013b5c1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/how-we-almost-achieve-end-to-end-exactly-once-processing-with-flink-28d2c013b5c1">How we (almost :)) achieve End-to-End Exactly-Once processing with Flink</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[Synchronize Different Consumers of the Same Kafka Topic]]></title>
            <link>https://medium.com/codex/synchronize-different-consumers-of-the-same-kafka-topic-23b30851158e?source=rss-fb5f5e4986c------2</link>
            <guid isPermaLink="false">https://medium.com/p/23b30851158e</guid>
            <category><![CDATA[microservices-pattern]]></category>
            <category><![CDATA[system-architecture]]></category>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[microservice-architecture]]></category>
            <dc:creator><![CDATA[Devora Roth Goldshmidt]]></dc:creator>
            <pubDate>Thu, 28 Jul 2022 08:08:00 GMT</pubDate>
            <atom:updated>2022-08-30T07:37:09.405Z</atom:updated>
            <content:encoded><![CDATA[<p>Synchronization in distributed systems is tough. You probably aim to prevent it as much as you can. But sometimes business requirements introduce a need to coordinate different services that have a hard dependency on data freshness.</p><p>For the sake of generalization, suppose the architecture is consisting of <em>Service-A, Service-B </em>and <em>Service-C. </em>All of them consume messages from the same Kafka topic but obviously process them differently according to their respective business logic, APIs and SLAs. When <em>Service-A </em>processes a message,<em> </em>it calls the APIs of <em>Service-B</em> and <em>Service-C</em> and expects this message to be included there. This is why <em>Service-A</em> can process a message only after <em>Service-B </em>and <em>Service-C </em>have<em> </em>processed this message successfully. If one of them<em> </em>is down or data is not updated there, the only thing <em>Service-A </em>can do is stop and wait. By other words, <strong>there is a hard dependency on Service-B and Service-C from both <em>Availability</em> and <em>Data Freshness</em> aspects</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/695/1*Namzulrgkmoc_GzfuAYuig.png" /><figcaption>Service A should process a message only after the message processed by B and C.</figcaption></figure><p>The architecture challenge is how to synchronize between the <em>Service-A</em> and its dependencies<em> </em>by the most scale-able, cost-effective and <strong>simple </strong>approach. Yes, I believe that the huber system design principle is complexity reduction. (and if you are not convinced enough, have a look at this great book <a href="https://www.amazon.com/Philosophy-Software-Design-2nd/dp/173210221X"><strong><em>Philosophy of Software Design</em></strong></a><em> </em>which starts with a high-minded explanation of the dangers of complexity in software as well as in system design).</p><p><strong>So why did we initially create this problem for ourselves?</strong></p><p>Now you probably asking yourself, if <em>Service-A</em> is so sensitive to message order, the simplest (and maybe the only one!) way to guarantee order is performing the processing that is done by <em>Service-B</em> and <em>Service-C</em> as serial steps within <em>Service-A</em>. Why did you distribute them all around?</p><p>So no doubt micro (or mini) service architecture comes with its cost, but this architecture style improves the team velocity as every single service is easier to develop, test, deploy and more importantly — scale, maintain and operate. It’s definitely not unique to our organization but personally, I’ve already been convinced and appreciated those benefits by observing the Dev org’s reality. Imagine that <em>Service-A</em> is an AML detection process that consumes payments and evaluates their risk. <em>Service-B</em> is handling entity-relations extracted from the same payments topic and <em>Service-C</em> is the one responsible for aggregating those payments and providing effective time-aware aggregation queries over them. Like AML detection (<em>Service-A</em>), there is also Fraud (let’s name it <em>Service-A1</em>) with completely different business logic but still requires querying over entity-relationship-graph and aggregated profile. We don’t want every team to invest in Time-Series DB and Graph DB technology selection, gain the experience of how those are scaled (or not… ) and operated, instead of focusing on their respective business which is AML or Fraud detection.</p><p><strong>Returning back to our initial problem…</strong></p><p>If we keep using AML detection as a concrete example of <em>Service-A</em>, how can it make sure that once it calls relationships API (exposed by <em>Service-B</em>) or aggregation API (exposed by <em>Service-C</em>), it’ll get up-to-date results? What if they are temporarily down or slow down for some reason? The detection process can NOT process the message until all required information is available. Progressing with stale info may end up with missing a Money Laundering of millions of dollars!</p><h3>The Architecture Pattern</h3><p>The core idea here is leveraging Kafka offset management as a single source of truth for tracking the progress of the various services. The offset is a simple integer that is used by Kafka to maintain the current position of a consumer. The current offset is a pointer to the last record that Kafka has already sent to a consumer in the most recent poll. So that the consumer doesn’t get the same record twice because of the current offset. As Kafka manages offset per topic, consumer group and partition, it actually means that each individual record can be identified only by &lt;topic, partition, offset&gt;. There are different strategies of how consumers can commit offset to Kafka, here we rely on a commit which is done only after a message is processed successfully by the consumer.</p><p>When <em>Service-A</em> polls a message from the topic, it should first extract the partition and offset of this message. Then, it calls Kafka admin API to verify that this offset is already processed by the consumer groups associated with <em>Service-B</em> and <em>Service-C</em>. Kafka admin API is called per each consumer group for retrieving a map of topic partitions to the offset (have a look at <a href="https://kafka.apache.org/20/javadoc/org/apache/kafka/clients/admin/AdminClient.html#listConsumerGroupOffsets-java.lang.String-">listConsumerGroupOffsets</a> function of Kafka admin Java client). The minimal offset per partition presents the offset of the slowest service.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yRz28w-os0OC7hj7eSvG-w.png" /><figcaption>Kafka’s admin is used for determining Service-B and Service-C progress</figcaption></figure><p>Notice that service may potentially consume from various topics, like <em>Service-C </em>that consume different event types to aggregate, so <em>Service-A</em> should clearly define its dependency as a combination of &lt;service, topic&gt; which technically is translated to a single consumer group.</p><p>As long as the minimal offset between <em>Service-B </em>and <em>Service-C</em> is lower than the message offset that is consumed by <em>Service-A</em>, it just waits.</p><h4>The algorithm in more detail…</h4><p>Let’s assume a situation where the committed offset of topic T1 is as the following:</p><ul><li>Consumer Group CG-A (Service-A):<br> partition p1 (C1): 0<br> partition p2 (C1): 0<br> partition p3 (C2): 0</li><li>Consumer Group CG-B (Service-B):<br> partition p1 (C1): 30<br> partition p2 (C2): 30<br> partition p3 (C3): 10</li><li>Consumer Group CG-C (Service-C):<br> partition p1 (C1): 23<br> partition p2 (C2): 52<br> partition p3 (C3): 15</li></ul><p>As you can see, t1 topic is partitioned into 3 partitions. CG-A and CG-B groups consist of 3 consumers each so every consumer handles a single partition only. But in CG-A, both p1 and p2 are handled by consumer C1.</p><p>Every consumer in CG-A should keep an updated partition map. This map can be updated periodically:</p><pre><strong>for</strong> each dependency consumer group // CG-B, CG-C</pre><pre>{  <br>admin.listConsumerGroupOffsets <br>/// (CG-B -&gt; ( p1 -&gt; 30, p2 -&gt; 30, p3 -&gt; 10)), (CG-C -&gt; ( p1 -&gt; 23, p2 -&gt; 52, p3 -&gt; 15))<br>update partitionMinOffset map <strong>with</strong> minimal offset <br>/// (P1 -&gt; 23), (p2 -&gt; 30), (p3 -&gt; 10)<br>}</pre><p>During the ongoing message polling:</p><pre><strong>for</strong> every consumed message /// (sorted from early to latest) <br>{</pre><pre>set message.offset  = extract the offset of the current message<br>set message.partition  = extract the partition of the current message</pre><pre><strong>while</strong> (message.offset &gt; partitionMinOffset[message.partition])</pre><pre>     wait</pre><pre>process /// only now service-A can process the message</pre><pre>manual commit offset /// commit offset after processing successfully</pre><pre>}</pre><p>Since the best practice is to prevent a static assignment of partition to a consumer, the consumer can’t assume the list of handled partitions but need to keep all topic partitions offsets as potentially it can handle any one of those partitions at any given point in time.</p><h4>Assumptions</h4><p>This approach is heavily based on Kafka&#39;s offset for reflecting the actual progress of service. Actually, there are different strategies for how to commit offset to Kafka. We internally use <a href="https://javadoc.io/doc/org.apache.flink/flink-connector-kafka_2.12/1.12.2/index.html">flink-connector-kafka</a> that commits the offset only after checkpoint completion (when <a href="https://nightlies.apache.org/flink/flink-docs-master/api/java/org/apache/flink/streaming/connectors/kafka/config/OffsetCommitMode.html">OffsetCommitMode</a> is set to <a href="https://nightlies.apache.org/flink/flink-docs-master/api/java/org/apache/flink/streaming/connectors/kafka/config/OffsetCommitMode.html#ON_CHECKPOINTS">ON_CHECKPOINTS</a>). Anyway, regardless of the specific technology, the assumption is that consumers are disabling the default auto-commit but manually commit the offset only after the message has been processed successfully, even in the case of asynchronous operations.</p><h3>Suggested Alternative</h3><p>Another approach that has been considered is that <em>Service-B</em> and <em>Service-C</em> will omit the message ID of the processed messages into a dedicated output topic and <em>Service-A</em> will join the output topics and the original topic for getting the full payload. Only once the message ID is consumed from all three topics, <em>Service-A</em> will process the message.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sODZdSVlB_MCZ2E_tiqNgw.png" /><figcaption>Output topics approach</figcaption></figure><p>This approach has been rejected due to the following downsides:</p><ul><li><strong>Complexity </strong>from the Producer side: the fact that <em>Service-B</em> (and <em>Service-C)</em> need to write to its own internal DB as well as to an output topic (and commit the Kafka offset, of course) increases the probability that in some cases those two sinks, of DB and Output topic, will be out of sync.</li><li><strong>Complexity </strong>from the Consumer side: <em>Service-A</em> needs to join between the original T1 topic and the two output topics and carefully handle a situation where one (or more) of them is very behind. It can NOT crash (due to OOM), but just stop consuming and wait. It’s true that stream processing engines like Flink can handle <a href="https://www.ververica.com/blog/how-flink-handles-backpressure">backpressure</a> by managing a blocking queue per source, but this increases the complexity dramatically.</li><li><strong>Massively messages volume</strong>: this approach just increases the number of messages significantly as every message will practically be duplicated (or tripled) and can impact the event bus performance and cost.</li></ul><h3><strong>To Summarize</strong></h3><p>If you are a Kafka expert, it might be obvious to you but surprisingly enough, this was not so trivial to convince people to get rid of additional output topics as those are basically already captured by Kafka offset itself.</p><p>This pattern works perfectly for multiple consumers of the same topic. Actually, it can be extended even for cases where they consume different topics as long as they have all initiated from a single common topic. But this is absolutely more complex pattern and justifies a follow-up article…</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=23b30851158e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codex/synchronize-different-consumers-of-the-same-kafka-topic-23b30851158e">Synchronize Different Consumers of the Same Kafka Topic</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>
    </channel>
</rss>