<?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 Nicola Atorino on Medium]]></title>
        <description><![CDATA[Stories by Nicola Atorino on Medium]]></description>
        <link>https://medium.com/@nicola.atorino?source=rss-b6cac4f54099------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*_OwaSyD0CyfXwk5I</url>
            <title>Stories by Nicola Atorino on Medium</title>
            <link>https://medium.com/@nicola.atorino?source=rss-b6cac4f54099------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 05:51:43 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nicola.atorino/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[Enhancing Quality and Resiliency: DraftKings Isolated Testing Solution — Part 1]]></title>
            <link>https://medium.com/draftkings-engineering/enhancing-quality-and-resiliency-draftkings-isolated-testing-solution-part-1-7f08bb8dd4a7?source=rss-b6cac4f54099------2</link>
            <guid isPermaLink="false">https://medium.com/p/7f08bb8dd4a7</guid>
            <category><![CDATA[quality]]></category>
            <category><![CDATA[architecture]]></category>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[testing-tools]]></category>
            <dc:creator><![CDATA[Nicola Atorino]]></dc:creator>
            <pubDate>Tue, 16 Apr 2024 12:00:05 GMT</pubDate>
            <atom:updated>2024-09-23T14:07:57.222Z</atom:updated>
            <content:encoded><![CDATA[<h3>Enhancing Quality and Resiliency: DraftKings Isolated Testing Solution — Part 1</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EgVuzZT68pSeK4hDc_z5Tg.png" /></figure><h3>Introduction</h3><p>When dealing with a microservice-based architecture, it&#39;s often the case that the complexities of a system are hidden in the integration between services more than inside individual components. Given a fixed-scope solution, the rule of thumb is that the simpler the logic defined for each service, the more complex the interaction between them would be. This is one of the reasons why the implementation of nano-services is considered an anti-pattern. Lots of challenges lie in the shadows when different systems need to be orchestrated to provide a solution, for example :</p><ul><li><strong>Communication</strong>: services can experience network issues and must be able to react correctly in case of temporary disruption of communication.</li><li><strong>breaking changes</strong>: microservices that evolve independently may unexpectedly produce a change in their contract that is not compatible anymore with the contracts implemented by other services that depend on them;</li><li><strong>Separation of concerns</strong>: The logic for implementing functional requirements must be spread through multiple components. This can be challenging (primarily when different teams own different components) and requires additional care around testing and work breakdown;</li><li><strong>transactionality</strong>: operations that could be easily made atomic in a monolith infrastructure are now more complicated to handle due to the system&#39;s distributed nature.</li><li><strong>Fault tolerance</strong>: each service may experience failures at any point in time, and a proper resiliency strategy must be implemented to reduce the impact on the solution as a whole at a minimum.</li><li><strong>Observability: </strong>the state of a distributed system is only possible to report and troubleshoot with a powerful and flexible monitorability strategy.</li></ul><p>One of the most critical aspects for DraftKings is the reliability of our services: there is no sense in further improving the system capabilities if what already exists is not up to the quality standards that we adhere to — the system must be stable, performant, and accessible at all time, and it&#39;s not acceptable for new functionalities to disrupt the existing ecosystem and worsen the customer experience throughout the rest of the product.</p><p>With all this in mind, <strong>covering each service in isolation, even if very well covered, is no longer a guarantee that the system as a whole can behave as expected</strong>. It is crucial to cover scenarios that span a long list of different components with diverse characteristics in terms of languages, communication protocols, storage providers, etc.</p><p>At DraftKings, we also faced these complexities. We were determined to find a way to solve them efficiently and cost-effectively, as our existing solutions did not give us the reliability we needed. To solve this problem, we built an isolated testing environment called CleanRoom, utilizing fundamental Kubernetes components, infrastructure as code, and a CI/CD system. This enabled our engineers to quickly spin up and tear down customized isolated environments to address the complexities of our microservice architecture. This article will walk through some of our CleanRoom case studies and dive deeper into the system&#39;s architecture.</p><h3>Introducing CleanRoom</h3><p>Over the past few years, many of our efforts have been dedicated to migrating our existing software infrastructure to Kubernetes. Due to this transition, our development teams became familiar with working with Kubernetes manifests and Helm charts. In turn, CleanRoom was designed to leverage our engineers&#39; existing knowledge. The solution we devised entails the following key components:</p><ol><li>Creation of a New Kubernetes Cluster for Isolated Testing: We established a dedicated Kubernetes cluster specifically tailored for isolated testing purposes. This cluster mirrors the configurations of our shared environment clusters to ensure consistency and compatibility of their software.</li><li>Unique Namespace for Each Environment: Every environment an engineer creates has its unique namespace within the Kubernetes cluster. This isolation ensures that each testing environment remains independent and does not interfere with others.</li><li>Infrastructure as Code Configuration: The configuration of isolated environments is stored as Infrastructure as Code (IaC) in a Git repository. This approach allows for versioning, reproducibility, and easy management of environment configurations.</li><li>Time-to-Live (TTL) for Namespaces: Engineers must define a Time-to-Live (TTL) for each namespace before deployment. Upon reaching the TTL threshold, the namespace is automatically deleted, promoting efficient resource utilization and preventing clutter.</li></ol><p>In the sections below, we will discuss the setup of CleanRoom further and some of the benefits we received from it here at DraftKings.</p><h3>What Clean Room Enabled us to do</h3><p>CleanRoom is a versatile system. DK used this technology to cover a wide range of different needs creatively. In this section, we&#39;re going to cover four different scenarios where CleanRoom proved invaluable and allowed our development teams to provide :</p><ul><li>on-time delivery</li><li>great quality at launch</li><li>maintenance of acceptable performances during the lifecycle of a system</li><li>ongoing assurance of software robustness even during several external disruptions.</li></ul><p>We will explore different developer use cases below, starting from the ones that provided us with more benefits.</p><h3>Automated Load Testing</h3><p>The usual approach in DK for load testing is to reserve a certain number of developers and QA capacity to provision data and execute load testing on a shared testing environment. This process is often executed during particular situations during the year:</p><ul><li>launch of a new product</li><li>significant changes over a system logic</li><li>In particular times of the year, the traffic expectation for the domain as a whole is expected to grow significantly (e.g., the first week of the NFL or Super Bowl night).</li></ul><p>The reason for these cases to be so sparingly and carefully chosen is that a comprehensive load test that can mimic a natural production environment as closely as possible is a task that requires considerable effort by multiple teams, with necessary coordination between different verticals. What we wanted to achieve with Cleanroom was the possibility of automating our load testing system in a way that would not require any more of this capacity strain, generating acceptable results in a steadier way that could fit nicely into the existing Software Development Lifecycle.</p><p>DraftKings launched a new product in 2023 called Pick6. The architecture team wanted to provide the development team with a way to continuously validate that the improvements and features implemented in the day-to-day application maintenance kept the system performance intact when under load. For example, it may be straightforward to seriously impact the performance of a stored procedure by implementing a new index for a completely unrelated task (ex., reporting). <br>Running a complete suite of manual load tests for each change (completely mimicking the production environment) is not feasible due to the required effort mentioned before. However, with Cleanroom, it is possible to completely automate a load test suite running in an on-demand environment for each and every release candidate. The system would:</p><ul><li>Start up an on-demand environment with a scaled-down version of the system.</li><li>Provision this environment with a critical mass of data using automated scripts.</li><li>Run a load test and produce a detailed report of the performance of the key areas. This report will then be used as a baseline.</li><li>Allow developers to compare their release candidate report against the baseline to quickly notice any relative improvement or degradation due to the changes introduced in the release candidate.</li></ul><p>Because it wouldn&#39;t be feasible to provision the exact same amount of data that a real production environment has to deal with, a process like this cannot be 100% reliable when it comes to reproducing production behavior. However, it provides fast feedback to the team, signaling possible issues that could occur on production BEFORE the new version was to be shipped. Combining this system with traditional manual load testing, processed on a shared environment, provides several advantages. This is the final process that the Pick6 development team adopted:</p><ul><li>A particular software version has been manually tested on a shared load environment, provisioned with 400 million entities in the database, and scaled up to the same Database instance size and number of replicas used on production. The result of this load test has proven that this version of the application can withstand a peak of 20 thousand entries per minute.</li><li>The identical version of Cleanroom, with 30 million entities stored, a much smaller database instance, and a much smaller number of replicas for the microservice, can withstand a peak of 5 thousand entries per minute. This will be our baseline, and a report will be generated.</li><li>From now on, every new release will be tested with the same configuration. One of the reports shows that a release candidate could handle a peak of 2 thousand entries per minute. In that case, the development team will notice this as part of their software lifecycle in a matter of minutes. It will be allowed to investigate the reason and take corrective actions, significantly reducing the risk of regression in production.</li><li>On the other hand, it will be possible to quickly validate that a change meant to improve the system&#39;s performance did its job correctly: CleanRoom can be used as an initial validation before the actual change, if necessary, gets tested following the manual load testing approach. At this point, a new performance baseline will be generated and used from now on as a comparison against subsequent releases.</li></ul><p>A complete automated test, from the commit of the release branch up to the generation of a report, will take, at most, a few minutes. This is a great tool to confirm that a system is always in the best shape possible, moving from a reactive approach to a proactive one. This avoids cases where significant degradations are noticed only a few days before an expected stressful period for the system — or even worse, DURING the stressful period — leaving no time to react.</p><p>The following images show two examples of a load test report for two separate releases. The second release performances have worsened, requiring more investigation from the development team before shipping to production.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9cC3WQ4WfbsU_XqJGVObDA.png" /><figcaption>this is our initial baseline, used for comparison against other subsequent releases of the application.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*49iYfZ9wGnip9dBw3wWcTA.png" /><figcaption>the performances here are clearly degraded — something in the new version needs to be checked again before shipping.</figcaption></figure><h3>Automated system functional testing</h3><p>As mentioned earlier in this article, when dealing with a microservice-based architecture, it&#39;s often the case that the complexities of a system are hidden between the integration of different services more than inside each component. If a team is ready to release multiple features and they want to ensure everything is working as expected:</p><ul><li>The team creates a branch ready to be promoted to a shared environment (or multiple branches if the feature requires changes to several services).</li><li>In CleanRoom, a dedicated environment tailored to the release is automatically provisioned with a unique namespace and short Time-to-Live (TTL).</li><li>A set of functional system tests is kicked off.</li><li>Results are promptly reported back to the team for immediate insights into system performance and reliability.</li><li>The team retains the flexibility to manually test use cases and visually inspect system elements within the CleanRoom environment. This allows for real-time debugging and manual validation of feature functionality if necessary.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UfeiqIrqhH8ibFibwKuHBQ.png" /><figcaption>High-level diagram of the automated testing infrastructure</figcaption></figure><p>To show an example of this, we can discuss the implementation of a 3rd party odds provider into our sportsbook system. When a new provider is integrated, several concerns need to be handled, and usually, for each of them, a separate component takes care of that responsibility. Some of these concerns are :</p><ul><li>Communication with the 3rd party following specific protocols and rules;</li><li>Processing of the fast changes of probabilities for different sports and events that the 3rd party provides;</li><li>Association between the 3rd party entities (games, teams, leagues) and DraftKings entities.</li></ul><p>Here is a small diagram showing the integration&#39;s high-level architecture (up to a certain point). Each box represents a different deployed microservice that takes part in the integration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mZX4sZtmTAVCr0HT6TD96w.png" /></figure><p>Each one of the components can be heavily covered with Unit tests, usually executed during the Continuous Integration process. However, using CleanRoom opens up opportunities to test the system end-to-end : it will be up to the engineering team to understand to what level of coverage they should aim for, and to balance coverage advantages with the efforts required to implement them.</p><p>The way this was implemented for this particular integration would look like this :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iD4qgWfdwBRYBSOcqyrBSQ.png" /></figure><p>Specifically, we agreed to cover the integration between distribution and odds processing and the integration between distribution and events mapping. The decision is usually made following the 80/20 principle — 80% of the coverage would be completed with 20% of the effort needed to cover the solution in every possible aspect.</p><p>This kind of testing is entirely functional — end-to-end testing aims to describe and validate behaviors, not implementations. For this reason, we used SpecFlow to define the system behavior without referencing the actual internal service implementations or communication protocols. This is a sample of some scenarios for the first set of tests involving odds processing. Notice there is no reference to communication protocols, storages, or how many components are involved in fulfilling the business requirement.</p><pre>Scenario: Update DoubleChance markets only when 3rd party provides all selections <br>       Given 3rd Party has new available fixture<br>        When 3rd Party provides selection update for market &lt;market&gt; with the price &lt;homePrice&gt; and points &lt;point&gt; and selection type Home<br>        Then eventTypeId &lt;eventTypeid&gt; should not be updated <br>        When 3rd Party provides selection update for market &lt;market&gt; with the price &lt;awayPrice&gt; and points &lt;point&gt; and selection type Away<br>        Then eventTypeID &lt;eventTypeId&gt; should be updated with values 1: &lt;homePrice&gt; 2: &lt;awayPrice&gt;</pre><pre>    Examples:<br>      | market                 | homePrice | awayPrice | eventType |<br>      | DoubleChance	       | 120       | -110      | 0         |<br>      | 1st Half Double Chance | 130       | -120      | 3302      |</pre><p>This scenario covers a slightly convoluted test that ensures DK internal updates are correctly generated based on the 3rdParty specific logic. This confirmed not only that the internal logic of each component works as expected but also that the communication between the various components behaves according to specifications and is not disrupted by any internal implementation change.</p><p>This is instead a sample of a scenario for the second set of tests involving events mapping :</p><pre>Scenario: 3rd party event is mapped to DK event<br>    Given a DK event exists for the 3rd party event<br>     When 3rd party produces event update <br>      and there is an association between the 3rd party event and the DK event<br>     Then the 3rd party is mapped to the DK event</pre><p>A simple scenario ensures that the communication between the components is valid and that any change in the mapping system (maybe implemented to cover a different 3rd party&#39;s use case) does not affect the expected business behavior.</p><p>Thanks to this system, our sportsbook team could substitute many detailed tests with a much smaller number of end-to-end test and maintain a similar, if not higher, coverage of use cases. These tests validate the behavior of a system as a whole and can catch issues that cannot be easily found by covering each component in isolation. While this solution cannot remove the need for more detailed tests, it&#39;s a great addition to our tools that change how systems are tested to focus on a holistic approach.</p><h3>What&#39;s next</h3><p>In the second part of the article, <a href="https://medium.com/draftkings-engineering/enhancing-quality-and-resiliency-draftkings-isolated-testing-solution-part-2-dfa6c8638514">linked here</a>, we will discuss the architecture of Cleanroom and how it allows us to cover the use cases just described.</p><p>Want to learn more about DraftKings’ global Engineering team and culture? Check out our <a href="https://careers.draftkings.com/life-at-draftkings/engineering/?utm_source=medium&amp;utm_medium=medium&amp;utm_campaign=medium_blog">Engineer Spotlights</a> and <a href="https://careers.draftkings.com/jobs/?utm_source=medium&amp;utm_medium=medium&amp;utm_campaign=medium_blog">current openings</a>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7f08bb8dd4a7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/draftkings-engineering/enhancing-quality-and-resiliency-draftkings-isolated-testing-solution-part-1-7f08bb8dd4a7">Enhancing Quality and Resiliency: DraftKings Isolated Testing Solution — Part 1</a> was originally published in <a href="https://medium.com/draftkings-engineering">DraftKings Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Apache Kafka as a centralized state management platform — Part 2]]></title>
            <link>https://medium.com/draftkings-engineering/apache-kafka-as-a-centralized-state-management-platform-part-2-980631412a5a?source=rss-b6cac4f54099------2</link>
            <guid isPermaLink="false">https://medium.com/p/980631412a5a</guid>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[state-management]]></category>
            <category><![CDATA[software-architecture]]></category>
            <dc:creator><![CDATA[Nicola Atorino]]></dc:creator>
            <pubDate>Fri, 07 Jul 2023 15:31:01 GMT</pubDate>
            <atom:updated>2024-09-23T15:44:02.824Z</atom:updated>
            <content:encoded><![CDATA[<h3>Apache Kafka as a centralized state management platform — Part 2</h3><h3>Kafka for centralized storage and state sharding</h3><p><em>Apache Kafka, an open-source distributed streaming platform, is used by DraftKings (DK) for data management and streaming applications due to its high scalability, low latency, and fault-tolerant storage. Kafka allows for various use cases such as data streaming, and state management. DraftKings employs Kafka as a push-based mechanism to distribute data from a database to multiple services, reducing strain on the database and internal traffic, following several architectural patterns that can cover different use cases. In the previous article, we explored the capabilities of Apache Kafka for state management and described a pattern to leverage its use to offload database traffic. In this article, we’re going to describe two additionally useful patterns that will solve some of the problems outlined in the previous cases and will extend our possibilities in terms of distributed processing.</em></p><p><em>The first part of this article can be found here : </em><a href="https://medium.com/draftkings-engineering/apache-kafka-as-a-centralized-state-management-platform-part-1-aa6d3fe4024b">https://medium.com/draftkings-engineering/apache-kafka-as-a-centralized-state-management-platform-part-1-aa6d3fe4024b</a></p><h3>Use Kafka as Centralized Store for Distributed Applications</h3><p>This pattern is useful to distribute a stateful application. In these cases, a microservice would need to consume a stream of messages that sends updates for particular events, then maintain an aggregate of information for each event, in order to handle further processing. It’s not unusual for this kind of stream to produce thousands of messages per second, so the partitioning capabilities of Kafka are extremely valuable to orchestrate the consumption. By implementing a set of consumers in the same consumer group, processing will be distributed correctly between the many instances of the application, and rebalancing in case of crashes, deployments, or change in the number of instances will be correctly handled by the broker and the consumer group coordinator out of the box.</p><p>Use cases example:</p><ul><li>updates of probabilities for sport events that need to be compared to the previous values</li><li>stock exchange price fluctuation — to generate an analysis of changes overtime or produce an average per day</li><li>wallet management — maintain a log of transactions together with a real-time snapshot of the balance in order to accept/refuse new transactions processing</li><li>fraud detection — keep track of behavioral patterns and detect anomalies over an established flow</li><li>shared sessions in multiplayer games — keep a centralized leaderboard up to date by events coming from different producers</li></ul><p>To handle state management, it is possible to implement a dedicated ledger topic where each instance of the service can read from and write to. The ledger topic will then act as a centralized, persistent store for the system, surviving service crashes and redeployments. To allow this, a ledger consumer can be implemented in the service, this time with a different consumer group per instance, to ensure that each instance has the entire state at its disposal, including everything that was published by any other replica. The service can then maintain the ledger in its own memory, populate it in full form at the startup, and receive updates when they are produced, this way achieving almost real-time synchronization between the various components.</p><p>In case of rebalancing, the stream topic will be evenly distributed following the new topology, and every consumer can then resume from the last committed offset for its own consumer group, with the guarantee that the ledger already contains all necessary information processed up until this point.</p><p>There is a short-circuit mechanism in place to avoid concurrency issues due to the fact that a published message has to be consumed by the instance that published it. This allows every instance, upon publishing the state update to the ledger, to populate its own internal memory. This means the published message does not have to wait the round-trip to the Kafka broker between publishing and re-consuming the same message that it produced in order to populate its own state. This guarantees protection against race conditions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-eGwMGnQ4DaI3i9UYoNpDw.png" /><figcaption>Design Pattern for a centralized ledger</figcaption></figure><h4>Considerations</h4><p>One thing to take into consideration when planning a solution like this is the actual coordination between stream processing and ledger processing. To achieve 100% data consistency, the offsets of the processing topic must be committed only after there is a guarantee from the broker that the ledger has been correctly updated. Otherwise, in case of crashes or ungraceful shutdown there is the risk of committing an offset — thus marking a stream message as consumed — before the ledger is updated with the result of the processing. This kind of synchronization, however, can be costly in terms of performance, so the decision to handle these edge cases explicitly instead of relying on a simpler solution has to be taken based on the criticality of the business case, the impact of potential data loss, and the possibility of this happening in a given infrastructure.</p><p>One other consideration to take is data retention. The TTL of the items in memory do not necessarily have to match the retention of the ledger topic, however, is usually advised to do so in to have consistency between the two layers. An example of this is to set the same retention period between the items in memory and the Kafka ledger. Alternatively, the topic can be set to have no retention at all. This is useful in cases when the decision to remove an item from the ledger is taken explicitly by the application, that can send a deletion request when it deems a specific item not necessary anymore. In this case, the ledger will receive what it’s called a ‘tombstone’ message, that will trigger removal of all messages with the same key upon compaction. Tombstone messages are consumed like any other message, and the service can react to this particular message type by removing the item from the memory state, thus keeping synchronization with the state of the ledger. It is important to make sure that memory purging is properly handled in the application, time-based or explicitly, otherwise memory leaks are guaranteed in the long run.</p><h4>Use Cases</h4><p>A pattern like this is very useful when the partitioning logic of the stream topic does not match the partitioning logic of the ledger. If this is the case, there is no guarantee that an instance processing a message from a specific partition may never require data that was retrieved and published by another instance. Another use case is when the complete state is needed for overall processing, like notifying the system with an atomic update that any of the events is in a particular state.</p><p>An example for the first case described above may be an application that maps external data to internal entities. In this case, the input topic may be partitioned based on the 3rd party event Id, while the output topic will need to be partitioned by the internal event Id. Of course, the Ids won’t match in this case, so there is no way of knowing in which partition the published internal event will end up. When, instead, the state of an instance can be properly isolated from the state of the others, we could spice this pattern up a notch and introduce state sharding.</p><h3>Use Kafka to Handle State Sharding</h3><p>Let’s now consider a slightly different use case when each instance of a distributed system does NOT need to handle state management outside of the partitions that have been assigned to it. In this situation, it is not necessary for each replica to consume the entire ledger topic, but instead, it will be enough to consume only the part of it that is usually tied to the partition that has been assigned to it for the stream.</p><p>In this case, the configuration of the ledger topic must match the configuration of the stream topic, in terms of number of partitions and partitioning key. This way, every event that is streamed from partition 1 will store its current state in partition 1 of the ledger, and so forth. With this approach, each instance does not have to maintain the entire ledger in memory, only the shard related to the partitions it has been assigned to. This has obvious advantages in terms of scalability and resource management when it comes to high volume of items to track.</p><p>However, there is a complication. When rebalancing, partition reassignment is automatic and the default mechanism of the broker is to assign them based on load. Therefore, predicting what partitions would be assigned to a specific consumer can be complicated. The consumption of the ledger must follow the assignment of the stream topic partitions, with the instance explicitly consuming a specific set of ledger partitions, based on the stream partitions that were assigned to it by the consumer group coordinator for the stream topic.</p><p>When a group rebalancing for the stream topic is triggered:</p><ul><li>The consumer will stop consumption from the currently assigned partitions. This ensures no concurrency issues can happen during the rebalancing process</li><li>The consumer will receive a notification that the currently assigned partitions have been removed. This can be used as a trigger to stop consumption of the ledger partitions that have been removed and remove every item in the state coming from the removed partitions</li><li>Once all consumers have confirmed that they have handled the PartitionRemoved event correctly, the consumer will receive a notification that a new set of partitions have been assigned. When this happens, the consumer needs to react by requesting consumption of the same partitions that were assigned to it</li><li>Once the ledger partitions have been consumed and the state is populated in memory, consumption of the stream topic can resume.</li><li>There is no possibility of race conditions here as the instance that was responsible to populate the state in those particular ledger partitions had their stream partitions removed already as part of the second step, so consumption and processing have been stopped already</li></ul><p>This diagram shows a potential initial state of an application exploiting this pattern:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5Vx6fMaKOReloG8jqCCO4g.png" /><figcaption>Design Diagram for state sharding in Kafka — initial state</figcaption></figure><p>While this one shows the state of the system after a rebalancing caused by the removal of one of the instances :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L5ehNkv6NlER5QulFfUXCg.png" /><figcaption>Design Diagram for state sharding in Kafka — state after removal of a consumer</figcaption></figure><h3>A deeper look on various concerns</h3><h4>Performance</h4><ul><li><strong>In Kafka there is usually a tradeoff between throughput and latency.</strong> For moderate traffic there is usually no need to delve deep into this, but when the amount of data to process becomes very high it is important to properly configure the system to behave exactly as expected</li><li><strong>Producer Configuration — </strong>Every producer can have a batch size defined that can be configured, and that would allow the client to ‘batch’ multiple messages into a single request to the server. The higher the batch size, the higher the potential throughput of the application, since there will be fewer trips to the server. However, a batch size too large could impact the memory consumption of the application and could even increase latency, since the client will linger for a certain period of time waiting for messages to accumulate. <strong>properties</strong> : <a href="https://kafka.apache.org/documentation/#producerconfigs_batch.size">batch.size</a> — <a href="https://kafka.apache.org/documentation/#producerconfigs_linger.ms">linger.ms</a> — <a href="https://kafka.apache.org/documentation/#producerconfigs_max.request.size">max.request.size</a></li><li><strong>Consumer Configuration — </strong>Consumers can define different configurations based on the use case<strong>. </strong>For example, it is possible to configure a minimum amount of data to be returned from the server to allow accumulation of more messages before returning to the client. This could increase throughput, at the cost of additional latency. <strong>properties </strong>: <a href="https://kafka.apache.org/documentation/#consumerconfigs_fetch.min.bytes">fetch.min.bytes</a> — <a href="https://kafka.apache.org/documentation/#consumerconfigs_fetch.max.bytes">fetch.max.bytes</a> — <a href="https://kafka.apache.org/documentation/#consumerconfigs_max.partition.fetch.bytes">max.partition.fetch.bytes</a> — <a href="https://kafka.apache.org/documentation/#consumerconfigs_fetch.max.wait.ms">fetch.max.wait.ms</a></li><li><strong>Timeouts and heartbeats — </strong>How long the broker should wait for confirmation before starting the rebalancing process, in the case of a consumer losing connection (or crashing). We want to be reactive in these cases to quickly recover proper state of processing, however we do not want to cause unnecessary rebalancing in case of a network blip that would be solved quickly. <strong>properties</strong> : <a href="https://kafka.apache.org/documentation/#consumerconfigs_session.timeout.ms">session.timeout.ms</a> — <a href="https://kafka.apache.org/documentation/#consumerconfigs_heartbeat.interval.ms">heartbeat.interval.ms</a></li><li><strong>Compression — </strong>Kafka allows messages to be compressed in several codecs, to reduce both the storage needed and the network bandwidth, at the cost of more CPU cycles and a slight delay in message dispatch. There are several codecs to choose from that all define different balances between gains and tradeoffs. Compression effectiveness also depends on producer batching configuration (the higher the batch size, the more effective compression will result, especially if the data is fairly repetitive, like XML or JSON data). <strong>properties </strong>: <a href="https://kafka.apache.org/documentation/#brokerconfigs_compression.type">compression.type</a></li></ul><blockquote>there are deep dives available online, one example is this : <a href="https://developer.ibm.com/articles/benefits-compression-kafka-messaging/">Message compression in Apache Kafka — IBM Developer</a> .</blockquote><p>There are several other considerations to make in regard to performance tuning that would deal with:</p><ul><li><strong>proper number of partitions based on the use case</strong> — usually a higher number of partitions would ensure a higher potential throughput, but too many partitions may have significant tradeoffs in term or rebalancing speed or cluster performances.</li><li><strong>partition replication and producer acknowledgment</strong> — partition replica would ensure better availability in case of broker failures, but acknowledgment of confirmation for all replica can be costly in terms of producers’ throughput.</li><li><strong>producer and consumer buffer size</strong> — a higher buffer size for clients would allow for a potential higher throughput and diminished latency, or even better resiliency in case of unexpected spikes of messages to be produced/consumed, but at cost of more resources necessary for the clients.</li><li><strong>data retention policies, segment size, and cleanable dirty ratio</strong> — smaller segment sizes and highest dirty ratio would ensure that topics are better maintained and unneeded data is removed quickly, but this could be costly for the broker to maintain since it increases the amount of work in the background.</li></ul><blockquote>A good starting point for some of these configurations can be this article : <a href="https://strimzi.io/blog/2021/12/17/kafka-segment-retention/">Deep dive into Apache Kafka storage internals: segments, rolling and retention (strimzi.io)</a></blockquote><blockquote>All the configuration details for the broker, the topics, the producers and the consumers can be found here: <a href="https://kafka.apache.org/documentation/#configuration">Apache Kafka Configuration</a></blockquote><h4>Fault tolerance</h4><p>Given the rebalancing system that the broker has in place, with multiple services deployed, the solution is able to withstand failures of one or more consumers automatically. The result of rebalancing is a short interruption of processing of the partitions that are being rebalanced. There are different ways to manage these cases, and they depend on how we have configured the consumer to ‘confirm’ to the broker that a message has been processed. Kafka can be configured to confirm the consumption of a message to the broker explicitly for each message, or instead have a asynchronous automatic commit system that sends the confirmation in bulk at an interval. If the consumer does not have a chance of gracefully shut down, there is the possibility that some of the processed messages could be consumed again after rebalancing has completed. The consumers need to take this into account and define an AtLeastOnce consuming approach to be able to deal with potential duplicates correctly. <strong>properties </strong>: <a href="https://kafka.apache.org/documentation/#consumerconfigs_enable.auto.commit">enable.auto.commit</a> — <a href="https://kafka.apache.org/documentation/#consumerconfigs_auto.commit.interval.ms">auto.commit.interval.ms</a></p><p>As in every microservice architecture, the overall health of the system depends on the health of the individual services and being capable of handling failures is an integral part of every solution design. When dealing with Kafka applications, there are other things to take into consideration apart from the consumer health that we just discussed. A consumer service may need to confirm that the producer of the messages it expects is healthy. This is often done by implementing a ‘heartbeat’ kind of message in the stream, that the consumer expects at regular intervals even if there are no other messages generated as part of the normal flow. Failure to receive this heartbeat message may mean that the producer is unavailable and thus the system may not be healthy as a whole. Usually, a heartbeat message is expected every few seconds, and the consumer defines a grace period after which it needs to react based on the use cases, by sending an alert to a monitoring system, or by stopping processing any internal work that relies on data being correctly up to date. For example, a processing stream that relies on real-time information for a sport event may react to this by stopping accepting bets in case the heartbeat message is not received, since there is a reasonable suspicion that we are failing to get the latest information about the event.</p><blockquote>There is a dedicated DK article that explains in detail how components manage resiliency in case of failures of external dependencies: <a href="https://medium.com/draftkings-engineering/resiliency-in-feeds-integration-4f31ff2bb04e">Resiliency in Feeds Integration | DraftKings Engineering | Medium</a></blockquote><p>Even tough Kafka ensures data retention via partition replica, at DraftKings there is an additional layer of resiliency. Compacted topics that are expected to be the single source of truth are also backed up at regular intervals (usually once per day). This is done in order to ensure disaster recovery capabilities if for any reason the production cluster gets corrupted or is completely unavailable and data cannot be recovered easily. Not every topic has a backup. Most of the data does not need to be recovered this way as it can always be retrieved from other sources. This backup is more of an exception than a norm.</p><h3>Monitoring and alerting</h3><p>Kafka exposes a good number of metrics to be monitored to ensure the system is healthy. It exposes commit latency, used buffer size, rebalancing latency, throughput of producers, and much more. A complete list of metrics is available at <a href="https://kafka.apache.org/documentation/#monitoring">Apache Kafka / Monitoring</a> . The client libraries expose a way to retrieve these metrics to be sent to any monitoring solution. At DraftKings, <a href="https://www.app-metrics.io/">App Metrics</a> backed up by <a href="https://grafana.com/">Grafana</a> or <a href="https://www.datadoghq.com/">Datadog </a>is the most commonly used framework.</p><p>However, one of the main metrics used is simply the latency of processing. Each Kafka message has a timestamp that defines the moment in which the producer has produced the message. By comparing this timestamp against the one recorded when the consumer has received the message, and then again once the message has been processed, we can have a clear number explaining the consumer delay and the processing time for each message. With this minimal setup, is pretty simple to understand if the consumer is ‘falling behind’ and is not able to catch up with the rate of messages being produced upstream.</p><p>Another valid way of measuring consumption delay is comparing the latest committed offset of a consumer group on each partition against the latest produced offset: also in this case, if the gap between the two values increases too much, an automatic alert can be implemented in order to notify the possibility of data being delayed over an accepted threshold.</p><p>These alerts could be then used to evaluate how to improve the system — for example, scaling up or scaling down the consumer, change the configuration at cluster, topic, producer or consumer level, increase or decrease the resources dedicated to each instance of the service, and so on.</p><p>Want to learn more about DraftKings’ global Engineering team and culture? Check out our <a href="https://careers.draftkings.com/life-at-draftkings/engineering/?utm_source=medium&amp;utm_medium=medium&amp;utm_campaign=medium_blog">Engineer Spotlights</a> and <a href="https://careers.draftkings.com/jobs/?utm_source=medium&amp;utm_medium=medium&amp;utm_campaign=medium_blog">current openings</a>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=980631412a5a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/draftkings-engineering/apache-kafka-as-a-centralized-state-management-platform-part-2-980631412a5a">Apache Kafka as a centralized state management platform — Part 2</a> was originally published in <a href="https://medium.com/draftkings-engineering">DraftKings Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Apache Kafka as a centralized state management platform — Part 1]]></title>
            <link>https://medium.com/draftkings-engineering/apache-kafka-as-a-centralized-state-management-platform-part-1-aa6d3fe4024b?source=rss-b6cac4f54099------2</link>
            <guid isPermaLink="false">https://medium.com/p/aa6d3fe4024b</guid>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[state-management]]></category>
            <category><![CDATA[kafka]]></category>
            <dc:creator><![CDATA[Nicola Atorino]]></dc:creator>
            <pubDate>Fri, 07 Jul 2023 15:30:41 GMT</pubDate>
            <atom:updated>2024-09-23T15:44:59.253Z</atom:updated>
            <content:encoded><![CDATA[<h3>Apache Kafka as a centralized state management platform — Part 1</h3><h3>Introduction</h3><h4>Overview &amp; Capabilities of Apache Kafka</h4><p>The main mission of the Sportsbook domain in DraftKings (DK) is to provide a comprehensive sport offering, near real-time, to allow customers to enjoy their experience with a constant growing set of products, events, and capabilities. To handle this, the underlying infrastructure that powers the entire sportsbook system must adhere to strict criteria in terms of performance, stability, and fault-tolerance. Most of DK’s infrastructure is designed to be horizontally scalable, in order to accommodate for high volumes and to leave room for further growth, when necessary.</p><p>In order to reach the desired state, the DK architecture team needed a way to manage the data flow that would allow for high flexibility, low latency, and high stability. While the entire infrastructure uses several different technologies in different contexts, the focus of this article will be on one of the most used tools, Kafka.</p><p>Apache Kafka is an open source, distributed streaming platform that is used for building real-time data pipelines and streaming applications. It is designed for high scalability and high throughput, and can handle millions of events per second. Kafka is used for various use cases such as logging, data streaming, event sourcing, and more. It also provides durable, fault-tolerant storage and can be integrated with other systems and tools.</p><p>Kafka leverages a wide variety of patterns. The first one that usually comes into mind is data streaming, for communication between two different services, and that is one of the patterns that is widely used at DK. However, Kafka also has high potential as a platform for caching and state management. We’re going to explore 3 different patterns:</p><ul><li>distributor of data stored in a SQL database for read-only purposes</li><li>centralized persistent layer for distributed applications</li><li>data sharding in order to allow for distributed processing</li></ul><p>Before diving into these use cases, let’s have a small recap of some of the concepts leveraged by the architecture team when designing systems around Kafka.</p><h4>Partitioning and Consumer Groups</h4><p>Kafka works by allowing producers to publish a stream of messages in a topic, that is a logical grouping of different files (called ‘partitions’) where the actual messages are stored. It is essentially an append-only log where each message contains a key, a value, and optionally some headers. When a publisher pushes a message to a topic, the actual partition to which the message is pushed is defined by a partitioning mechanism usually based on the message key, although it may be possible to implement different partitioning logics. Typically, in our domain, partitioning is done based on the key, so messages with the same key will be stored in the same partition.</p><p>The concept of partitioning is important when it comes to consumption distribution: a set of consumers can leverage partitioning to evenly distribute the load. When a consumer registers to a topic, it provides the Kafka broker with a key called ‘consumer group’ that will identify the group this specific consumer is part of. Multiple consumers sharing the same group will distribute the consumption of the topic, sharing the partitions between them. This way, a topic that contains multiple partitions can be split between multiple consumers, with the upper limit being the total number of partitions the topic is composed of. Since a partition can only be consumed by a single consumer at a time for each consumer group, this guarantees ordering in the consumption of the messaging while allowing horizontal scalability.</p><p>Each consumer group can optionally register an offset, or “pointer,” in the partition, indicating the last message that was correctly consumed by any consumer of the consumer group. When a partition switches consumers within the group (as a result of changes in the topology of the system, redeployment, or scaling) the new instance will resume consumption starting from the last committed offset left from the previous consumer in the consumer group. This is made possible by a special node in the cluster that takes care of coordinating the consumer groups. If the offset is missing, the consumer can be configured to read the topic from the beginning or from the end, based on the use case that makes sense for that application.</p><p>More information can be found in the official Kafka documentation : <a href="https://kafka.apache.org/documentation/#impl_offsettracking">https://kafka.apache.org/documentation/#impl_offsettracking</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P2JESbqAdkUjvjqffZLs1g.png" /><figcaption>Partition Balancing in Kafka</figcaption></figure><h4>Retention Policies</h4><p>Storage space is not infinite. One of the key features of Kafka is its ability to retain data for a specified period of time. This is known as the retention policy. Retention policies are used to control how long data is kept in a topic before it is deleted. It can be set on a per-topic basis, and defined using either time or size-based criteria. This way, our topics used for streaming data will keep messages only for a certain period of time. This is known as the ‘delete’ retention policy.<br>The most interesting policy for our use cases, though, is the ‘compact’ policy. When setting this policy on a topic, the cluster will delete duplicate messages, while keeping the latest or most recent version of each message. It is also incredibly useful to handle state management of an application, because there are several cases where we are interested only in the most recent version of the data, like when implementing a caching mechanism.</p><p>The two policies can be combined. A message can have all its duplicates removed and the most recent version can then be deleted from the topic following the delete retention policy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BQreR4O3JBsdGWCjMQIzfg.png" /><figcaption>Compact retention policy in Kafka</figcaption></figure><p>Although there are multiple other configurations and concepts to explore that would take a lot of time to cover properly, and several considerations to make when choosing the proper strategy in terms of partitioning and data retention, these are some of the concerns to have when planning an architecture using this technology:</p><ul><li>cluster performances</li><li>storage</li><li>producers’ speed</li><li>serialization</li><li>consumption strategies</li></ul><p>More information about log compaction can be found in the official Kafka documentation: <a href="https://kafka.apache.org/documentation/#design_compactionbasics">https://kafka.apache.org/documentation/#design_compactionbasics</a></p><h3>Use of Kafka as a DB Cache Distributor</h3><p>Several services in DK need to constantly evaluate incoming messages against the most recent version of data stored in the database. Given the number of services that require this info, a direct connection to the database for each one of these components would put too much strain on the database instance. Also, the amount of data that need to be retrieved by the application would generate too much internal traffic. To solve this situation, Kafka is used as a push-based mechanism to allow applications to store the data they need in memory, be notified when data changes, and be able to handle all their processing internally.</p><h4>The distributor</h4><p>A Cache Distributor is a microservice whose only responsibility is to interrogate the database at regular intervals using predefined queries. When the application starts, the entire dataset is retrieved and pushed into a dedicated Kafka topic. After initial load, only updates are retrieved and published, using the datetime of the last request that was successfully processed. The queries could involve complex joins of different tables, thus effectively generating a view that will be then exposed to every consumer, which won’t need to connect directly into the database (or handle their own caching system) as long as the staleness of the data is acceptable for their purpose. On less frequent intervals, the entire dataset is fetched and republished in order for the older data to not be removed from the topic due to retention. The interval for re-fetching the entire dataset must be shorter than the topic’s retention period to ensure that consumers do not miss infrequently updated data.</p><h4>Topic configuration</h4><p>The data is pushed to a compacted topic, with the key being the primary key of the main entity that was retrieved. This way, when compaction is executed, only the most recent version of the item will be kept in the topic. When a consumer needs to read the entire topic in order to populate its own internal state on startup, they will avoid consuming a huge number of messages while ignoring everything apart the last one, speeding up the startup time.</p><p>The topic also contains a delete policy retention, that will remove data after a certain amount of time. This is necessary to clean the topic from entities that have been deleted from the database.</p><p>The cache topic has a single partition. This is done because, in this particular use case, every consumer should consume the topic in full to maintain the entire cache in memory. By having a single partition, the broker performances improve. since it has to deal with less communication overhead.</p><h4>The consumer</h4><p>On the consumer side, the data is stored in memory. At startup, the topic is read from the beginning, and the messages are used to create an internal memory dictionary. If necessary, each application can create additional custom indexes to query the data based on their own needs. After the initial startup, the consumer keeps listening to the topic to receive regular updates, as they are going to be published by the producer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*05dHoEVU_lScRlXENBFJQQ.png" /><figcaption>Design Pattern of the DB Cache Distributors</figcaption></figure><h4>Considerations</h4><p>This system has several advantages, but also some drawbacks that need to be pointed out. First of all, it is memory intensive for the consumers, but this is true for every state management system that involves the use of Kafka, including the ones being discussed next. The full reload that happens on regular intervals can cause memory spikes while the application processes the set and discards the old values for the updated ones. This can be mitigated by reducing the amount of data the service stores from the topic to the minimum. If the cache contains an object with a lot of properties, but not all of them are necessary, it is better to define a lightweight object on the consumer side and store only what is needed.</p><p>Secondly, the staleness of the data cannot be configured at the consumer side, only at the distributor side. If a consumer requires data that is more up to date than what the cache provides, it will have to handle this in different ways. One of the classical problems found with this approach is the retrieval of information from the database that was changed as a result of the processing of the microservice itself. A possible workaround for this would be to update the internal dictionary (if all the data is known) before submitting the database change, but this can lead to data inconsistencies (especially if the update needs to be validated downstream) and is generally regarded as a sub-optimal solution.</p><p>In short, this system is not suitable to be used with components that are expected to update into the database (directly or indirectly) the same set of data they are going to retrieve from the cache.</p><h4>Next</h4><p>In the next article, we’re going to explore two other patterns for state management that will overcome some of the downsides that we encountered till now:</p><ul><li>Kafka as a centralized store for distributed applications</li><li>Kafka used to handle state sharding</li></ul><p>The second part can be found here : <a href="https://medium.com/draftkings-engineering/apache-kafka-as-a-centralized-state-management-platform-part-2-980631412a5a">https://medium.com/draftkings-engineering/apache-kafka-as-a-centralized-state-management-platform-part-2-980631412a5a</a></p><p>Want to learn more about DraftKings’ global Engineering team and culture? Check out our <a href="https://careers.draftkings.com/life-at-draftkings/engineering/?utm_source=medium&amp;utm_medium=medium&amp;utm_campaign=medium_blog">Engineer Spotlights</a> and <a href="https://careers.draftkings.com/jobs/?utm_source=medium&amp;utm_medium=medium&amp;utm_campaign=medium_blog">current openings</a>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aa6d3fe4024b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/draftkings-engineering/apache-kafka-as-a-centralized-state-management-platform-part-1-aa6d3fe4024b">Apache Kafka as a centralized state management platform — Part 1</a> was originally published in <a href="https://medium.com/draftkings-engineering">DraftKings Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Resiliency in Feeds Integration]]></title>
            <link>https://medium.com/draftkings-engineering/resiliency-in-feeds-integration-4f31ff2bb04e?source=rss-b6cac4f54099------2</link>
            <guid isPermaLink="false">https://medium.com/p/4f31ff2bb04e</guid>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[system-resiliency]]></category>
            <category><![CDATA[dot-net-core]]></category>
            <dc:creator><![CDATA[Nicola Atorino]]></dc:creator>
            <pubDate>Fri, 06 Jan 2023 18:26:49 GMT</pubDate>
            <atom:updated>2023-07-26T22:02:42.396Z</atom:updated>
            <content:encoded><![CDATA[<p>The DraftKings Sportsbook product is a state-of-the-art software suite that offers a wide range of sport events in order for players to enjoy endless gaming possibilities. To be able to provide such an experience, different teams are responsible for generation or integration of different kinds of content. While DraftKings sport content is a composition between internal intelligence, content creation and external content consumption, the Feeds Team is dealing mainly with digestion and processing of external content into the core sports domains, which includes integration with 3rd parties.</p><h3>The Context</h3><p>Now, one of the most important characteristics of these integrations is stability. We need to quickly react to problems and then come back to a functioning state as soon as possible after the disruption has passed, regardless of whether or not DraftKings is the source of it. We also need to understand if the disruption has the potential of causing incidents, or if it’s possible to continue processing while this is happening with a graceful degradation of some functionalities. While some standards exist, every 3rd party provider has its own integration mechanism and its own structure. Some of them work mainly via HTTP calls, others use AMQP protocols, or SSH connections. There are a wide variety of cases and, generally, a new solution is required every time.</p><p>We can split the integrations into two types: request-response style (think about a web API) and producer-consumer style (think about an application consuming a queue, processing the data, and publishing results to another queue). This is an important characteristic of the integration, as it dictates how it should react in case of issues. A request/response integration may need to stop accepting new requests, while a consumer/producer style of the application may require stopping the consumption of new messages, or delaying the publishing. There are several varieties of cases that could require different approaches, but what they share in common is the necessity to quickly know when and if work can be resumed safely.</p><p>Because of this, any kind of health monitor system has to be:</p><ul><li><strong>Self-healing</strong>: even if alerted immediately, relying on manual intervention is simply too slow when live data is involved, especially if happening during the night. A problem system needs the capacity of automatically restoring its functionalities as soon as possible.</li><li><strong>Flexible</strong>: different providers have different necessities and different ways of confirming that they are working fine. In some cases, we need to get creative and find a way ourselves as the provider does not offer clear capabilities.</li><li><strong>Generalized</strong>: the expected result is always the same, so finding a common way of approaching the issue ensures implementing the feature into a new provider won’t require reinventing the wheel every time.</li><li><strong>Capable of real-time reporting</strong>:<strong> </strong>there is a huge advantage in providing real-time visibility over ongoing issues and degradation of services for each provider involved in potential incidents.</li></ul><h4><strong>Example : SSH-based provider</strong></h4><p>Let’s think about a fictional provider of LIVE sport content. This company provides:</p><ul><li><strong>offering information</strong>: which events they have available in their system, for example football matches, or motorbike races</li><li><strong>pricing information</strong>: what are the probabilities of something happening in the events they offer, for example a certain player to score, or a certain racer to win, etc.</li></ul><p>This provider offers the live pricing information via an SSH feed, to which only one connection at any time is allowed as per technical requirement on their side. Their offering information, instead, is provided via an HTTP API that they expose. The pricing information must be available all the time because the data is time-sensitive: when the games are live, odds change in a matter of seconds. The offering data, instead, changes only once every week, when the provider decides to prepare the new set of events that they plan to offer. On top of this, the DraftKings application integrating the provider is required to get all this data, update a SQL server DB when some conditions are met (for example, a new event is discovered for the first time), and, after some internal processing, publish it as a stream via Kafka, available for consumption further along in the pipeline .</p><p>This system has at least 5 external dependencies that may affect its resiliency:</p><ul><li>The SSH connection to the 3rd party provider. This is fundamental and should stay healthy all the time, otherwise we risk a potential incident</li><li>The HTTP endpoints of the 3rd party provider. This is less sensitive and our integration could survive some unavailability, because games are usually offered several days before they are needed</li><li>The DraftKings SQL Server Database. Based on the requirements, this may or may not be sensitive. For the sake of this example, let’s say it is accepted for this component to not be updated immediately, because offering discovery usually happens several days before the start of the game</li><li>The DraftKings Kafka cluster. Again, this is fundamental as it’s the main source of information for pricing that other components rely on. If this component is not available, or not reachable, our integration won’t work and we can risk a potential incident immediately</li><li>The DraftKings Vault secret storage. This is needed because DraftKings uses a dedicated solution for storing secrets (Vault by HashiCorp), and these secrets in our case are the credentials required to connect to DraftKings SQL Server</li></ul><p>So we can already split our dependencies into 2 groups: dependencies that when missing will bring the integration into an unhealthy state, and dependencies that when missing will bring the system into a degraded state.</p><h3>The Solution</h3><h4>Resiliency Architecture</h4><p>The vast majority of our integrations are written in .NET core and deployed in Linux-based containers, orchestrated by a Kubernetes cluster. On top of this, they are registered by a service discovery system based on Consul ( by HashiCorp). By taking advantage of the flexibility and power of the Kubernetes orchestrator, two different architectures could be implemented in order to increase our resiliency: an active-active approach, where the processing is split evenly between several instances of the same integration, and an active-passive approach (implemented with a leader election system), where one instance is actively processing the data and a second one is ready to take over in case of any trouble with the first. The one to use is dependent on the integration requirements, the expected load of the system, and generally a balance between complexity of the integration and resiliency capabilities. It is important to strike a balance between near-zero recovery time as opposed to a system with less strict requirements but simpler to develop and maintain, while still fitting into desired SLAs.</p><p>Regardless of the approach chosen, it is important to understand when an instance, active or passive , is healthy, where healthy means ‘capable of processing data and covering all expected functionalities.</p><h4>Example : architectural resiliency</h4><p>In our SSH-based provider we can already notice how, at least for the processing of the pricing, we won’t be able to have more than one instance active because of the SSH limitation. However, having a single instance deployed is problematic. A restart (due to crash, deployment, k8s cluster maintenance, k8s node compaction) could take minutes, and this kind of downtime is not acceptable if it happens during a live game, as it could generate a potential incident. The simplest option seems to be to use an active-passive approach. In case of restart, another instance already available and ready to take over will reduce our potential downtime from minutes to a few seconds, completely automatic without human intervention. A big improvement.</p><h3>Health Monitoring System</h3><p>An integration can be considered healthy when:</p><ul><li>The instances themselves are up and running</li><li>All the external dependencies of the instances are also up and running. The number, type, and level of importance of the dependencies varies with the integration</li></ul><h4>Health checks</h4><p>Both Consul and Kubernetes use a similar way of discovering integration health. They constantly ping specific HTTP endpoints that return health info about the application, and together they define the overall status of the application. There are 2 different kind of healthchecks we have to discuss: the liveness healthcheck and the readiness healtcheck.</p><p><em>Liveness healthcheck </em>is interrogated by a Kubernetes’ liveness probe and will trigger a restart of the container if unhealthy. It lets the system know if a container is deployed and if the instance running in it is operational. These checks should return basic health information for the service, together with the status of any dependency for which we know a restart is required, in case of troubles.</p><p><em>Readiness healthcheck </em>is interrogated by a Kubernetes’ readiness probe and Consul. Consul uses this health check for service discovery and leader election purposes. It lets the system know if the application is not only running, but is also ready to process information and accept traffic. An instance can be alive but not ready, such as if it has a long startup routine that requires the application to build up its own internal state before being able to properly process requests. These checks will be built around every registered dependency, whose faulty or unavailable status would make our application incapable of processing business requests (of any kind). This is where we should check all dependencies that our service can reconnect to without a restart, like Rabbit, Kafka, SQL, external HTTP services, and so on.</p><h4>Example : Liveness and Readiness dependencies</h4><p>Going back to our example integration, our 5 dependencies can be split in 2 groups:</p><p><strong>Liveness dependencies:</strong></p><ul><li>Vault. Given how this system is implemented in our infrastructure (a sidecar container), problems with this dependency will probably require a restart of the Kubernetes pod. Majority of Vault-related issues require reestablishment of trust between Vault and the container, and this means execution of startup logic is necessary.</li></ul><p><strong>Readiness dependencies:</strong></p><ul><li>SSH. There is no need to restart the container if the SSH channel experiences problems. The integration should solve this issue seamlessly, or wait for the 3rd party to recover.</li><li>HTTP webapi : this is a stateless kind of connection so each request is independent. As soon as the 3rd party accepts requests again, we are good to go.</li><li>SqlServer. Also in this case, if the problem is not in the credentials (for which we check Vault), there is no reason to restart the container</li><li>Kafka : the kafka broker and the client library are smart enough to automatically recover from several kind of issues without any intervention. Our application can simply check the status of the consumers and once the distruption is solved it will just need to start again the consumption of messages.</li></ul><h3>Stopping and Starting Business Logic-Based on Health Status</h3><p>Based on the importance of the dependency going haywire, an instance should be marked as degraded (working, but not at 100% functionality) or unhealthy, when it is often safer to stop any processing. This could prevent pushing forward wrong data, or flooding our logging system with errors. The best option, in this case, is to notify our alerting system that something is not working as expected, to clearly log the nature of the problem, and to put the instance in an unhealthy state, stopping any further data processing. As discussed before, there are 2 kinds of integrations that we are covering right now:</p><h4>HTTP-Based Request/Response</h4><p>These kinds of applications work by exposing some endpoints that the 3rd parties call to update DraftKings with their latest information. In this case, if the readiness monitor shows that the instance is unhealthy, the instance is automatically put away from the load balancer pool and won’t be reachable by HTTP traffic. This works out of the box thanks to a very clever load balancing system that uses real-time service discovery information from Consul to decide if an instance should be routed traffic or not. With this system, for example, if we have 3 active-active instances all accepting HTTP traffic and one of them suddenly reports unhealthy, the remaining instances will see an increase in traffic but the overall pipeline should be unaffected.</p><h4><strong>Producer/Consumer</strong></h4><p>Several of our integrations are not pushing data through HTTP endpoints, but are, instead, receiving information through other channels such as AMQP queues they are subscribed to, or Kafka topics. In these specific cases, we cannot take advantage of the dynamic HTTP load balancing capabilities of the infrastructure. Even if the instance is marked unhealthy in the service discovery mechanism, the instance itself won’t have any knowledge of that out of the box, and won’t automatically stop any subscription or any connection it did on startup. Because of this, the application may keep trying to process data while not having all the necessary dependencies available to do so, often with problematic results. A better, more proactive approach would be for that instance to react to its own health state changes, stop any processing, and allow other instances, if available, to pick up from where they left.</p><p>The library that the Feeds team implemented exposes specific events that can be used to react to health status changes of any dependency, understand the overall status of the system, and react accordingly. The biggest advantage of this kind of approach is being able to split the health monitor from the business domain of the application. A processing pipeline won’t necessarily need to check each dependency every time it tries to use it, or to implement complex resiliency mechanisms. Relying on the health monitor system will be enough to ensure that everything expected is available, greatly simplifying the implementation of required functionalities. This system will also allow the application to react to the dependencies going back online, and resume the processing automatically, without any manual intervention.</p><h3>Example : stop SSH processing</h3><p>Going back to our example integration, the application is an active-passive, consumer/producer application. This means that in order to improve the resiliency of the application we will be required to actively stop the SSH consumption and allow another healthy instance to be able to pick up the work.</p><p>For example, we could have a network partitioning and only one of our instances is able to reach the kafka cluster. In this case, it makes sense for the active instance to lose the leadership status, stop the consumption of the SSH channel, free up the only connection available, and allow another healthy instance to gain the leadership status and resume the processing of the data.</p><p>The feeds team has a separate library for leader election that integrates seamlessly with the healthmonitor system and takes advantage of Consul, to allow dynamic and automatic leader switching based solely on the health status information. Of course, if all instances are unhealthy, then in this cases consumption is impossible and an alert is sent to out monitoring channels for further management. More on this later in the article.</p><h3>Core &amp; Extensions</h3><p>The idea behind the whole implementation is for the core logic of the monitoring module to be the agnostic of any dependency, while instead accepting a generic contract that can be then fulfilled by dependency-specific implementation. These implementations are called ‘monitors’ . Without monitors, both the liveness and readiness logic will always return healthy, because there is no dependency that could fail.</p><p>Then, both checks can be easily extended by adding dedicated monitors based on what the application relies upon (for example, a Kafka monitor, that would check exclusively if the connectivity to the Kafka cluster is established at all times). The monitor will also allow configuration regarding the status that should be exposed in case of issues : for example, in some cases when losing Redis the application won’t be able to process data anymore, in other cases losing Redis won’t be a blocked and the system can continue with degraded functionalities. The integration may want to restart if it cannot connect to Kafka, may want to stop everything but stay alive and keep trying to reconnect, or may want to degrade gracefully and simply go into a degraded status until the problem is resolved. All of this will be configurable, without the need of touching the infrastructure configuration (Consul, K8s, load balancing, etc.). This is usually enough to control the behavior of consumer/producer style applications that we don’t want to execute on an instance that has issues with some of its dependencies.</p><p>Also, if the application is not on a request/response style, and does not need to expose the health checks via http, we won’t require any integration with .net core middleware-based http health check system. For this reason this extension will be optional, and will be exposed as a separate package.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yk9sdB_Vi2KN86JQSHf4kg.png" /><figcaption>the overall diagram of the resiliency system implementation</figcaption></figure><h3>Implementation</h3><p>The implementation is simple: a background service is configured to routinely collect the status of both liveness and readiness monitors, and keep in memory the aggregated status of the system. A monitor is a piece of logic dedicated to returning the status of a specific dependency. We will have a Kafka monitor, a Redis monitor, a Sql Server monitor and so on. The system will allow us to define a list of monitors, and configure them to decide if they should describe the liveness or readiness status, if they should mark the instance as degraded or unhealthy in case of troubles, all of this together with any other dependency-specific configuration. There will be two separate collections; one for readiness monitors, and one for liveness monitors. The overall status of a monitor collection will define the status of that specific health check. It is worth mentioning that the same monitor can be configured to be used as a liveness or readiness monitor based on the application use case.</p><h4>Overall status</h4><p>The logic is as follows:</p><ul><li>At least one unhealthy monitor — overall health check is unhealthy</li><li>Otherwise, at least one monitor degraded — overall health check is degraded</li><li>Otherwise, overall health check healthy</li></ul><p>This runs for both monitor collections and a separate result is stored for each of them. In addition, an event is raised every time the status of the readiness monitor changes, to allow the business logic to start or stop accordingly. In case a health check endpoint is requested in the .net host, an extension is attached to simply recover the latest aggregated status of the corresponding monitors.</p><h4>Timeout Policy</h4><p>Some of the monitors may require some time to be able to understand if a dependency is available or not, and to be able to avoid status flickering in case of a brief interruption of the connection. For this reason, and also to prevent the system from getting stuck in case any of the monitors hang for any reason (including bugs in the monitor implementation) there is a timeout policy in place in the overall monitor status collecting system. This timeout period is configurable at application level and, in case of triggering, will prevent the entire system from hanging out waiting for a response from one of the monitors that will never come, and instead will show the overall status as unhealthy, allowing the application and the overall infrastructure to react accordingly.</p><h4>Extensibility of the Solution</h4><p>The monitors are exposed as extension packages so the core does not have unnecessary dependencies. New monitors can be added if needed, and custom monitors can be implemented for specific applications that require an ad-hoc solution. The integration with the .net core health check system is exposed as a separate package for the same reason.</p><h4>Example : SSH monitor</h4><p>Going back to our example, it is very possible that the monitor used for checking the status of the SSH connection is very application-specific. Because of this, it would make more sense to implement it as a custom monitor directly in the application code instead of creating a new extension. This will allow us to reduce the time-to-market and to avoid overengineering the solution, while still keeping this logic separated from the main flow. In the future, in case of centralization needs, that implementation can be eventually extrapolated from the context in order to accommodate more generic requirements.</p><h3>Reacting to Health Status Changes</h3><h4>Active/Active : Splitting the Work and Dynamic Rebalancing of Traffic</h4><p>When the requirements allow it, an active/active approach is preferable as it would also help in other important aspects like scalability. However, there is always the need of implementing how the work can be repartitioned between the healthy instances in case one of them is not capable of handling traffic anymore, and how to return traffic properly to that instance once the disruption has passed.</p><p>Usually for request/response applications this is handled automatically by the load balancing system. Traffic is routed only to the healthy instances, and as long as we make sure that every instance is capable of processing every request, this works out of the box. An unhealthy instance will be removed from the pool, and then put back seamlessly once its deemed ready again.</p><p>For consumer/producer based applications in DraftKings, the preferred way of ensuring this is to take advantage of the Kafka rebalancing mechanism. All applications are consuming the same Kafka topic and the Kafka system itself makes sure to repartition the traffic only to the active consumers. For this reason, is very important to take advantage of the health monitor events to stop any consumer when the application is unhealthy, and start it back when the application is healthy again. This will notify the Kafka broker that there is a change in the consumer’s group membership status, and the broker will react accordingly, ensuring that traffic is rerouted properly to the remaining instances. This has the huge advantage of not needing the application instances to be aware of the status of any other instance apart from themselves.</p><p>In case of other integrations, the solution is not so straightforward. For RabbitMq, for example. it may require some explicit reconfiguration of binding and routing between the remaining instances, together with the possibility for the application to request the overall status of each instance to Consul in order to better orchestrate the consumption. This is undoubtedly more complicated to handle and more error prone, but it is doable, or we could fall back to an active/passive system or a sharded system (more manual maintenance but more straightforward architecture) . As said before, is a matter of balancing between resiliency and complexity.</p><h4>Active/Passive : Integration with the leader election system &amp; additional challenges</h4><p>The Feeds Team uses Consul also for Leader Election when implementing an active-passive approach. This combines perfectly with the health monitoring system, as consul uses the same health check, on its side, to allow an instance to maintain its leadership status. If the readiness health check of the application returns an unhealthy status, the instance is immediately demoted as a leader and any other healthy instance will take its place. This will trigger an event in the application, and this event can be used to start or stop the processing of the data that require leadership status for consumption.</p><p>While this system works very well out of the box, there are indeed some challenges that arise in this case and that need to be taken care of :</p><ul><li>How to handle monitors that should check a dependency that should be connected only if an instance is currently a leader</li><li>How to avoid constant switching of leadership in case of troubles with a fundamental dependency</li></ul><p>These are all cases that are currently handled with application-specific code when the need arises. A more general solution is expected to be scoped and discussed in the future. The monitoring system is pretty much alive and constantly evolving.</p><p><strong>Http Based Active/Passive system</strong></p><p>On a side note, an interesting requirement that was necessary in some of our past integrations was the necessity to combine HTTP-based request/response system together with active/passive architecture. In other words, we wanted only our active instance to be reachable via HTTP (to an internal load balancer — our system won’t allow internet connection directly, there is a gateway solution for this) . This is not as straightforward as it seems, because our load balancer by default exposes ALL healthy instances, regardless of them being active or passive, and we did not want to modify the existing infrastructure to accommodate for this. <br>After some experiments with degraded statuses for passive instances, or by dynamically configuring the weight of the load balancing routing based on the metadata of the application (both unsuccessful for various reasons), the solution was found by taking advantage of Consul and the way its DNS system can be configured.<br>Without going into too much detail, when registering applications into the Consul service discovery system, it is possible to optionally add ‘tags’ to the instance registration. We use this functionality to mark which instance is currently the leader in order to track it down in our monitoring system, using a tag with the key ‘<em>Leader.’</em> The tag is added and removed by the leader election library based on the actual acquisition or demotion of leadership.<br>Consul has a DNS templating system that allows it to take these tags into consideration for traffic routing. When a service is called, for example, <em>MyService</em>, the service will be reachable in our network by calling <em>MyService.Services.Consul</em>. However, it is also possible to use the aforementioned tags to better filter the instances to route the traffic. So, when calling <em>Leader.MyService.Services.Consul</em> the traffic will be routed ONLY to the instances that are registered with that specific tag.<br>Given that the tag is dynamically added or removed as previously explained, this allows any client trying to connect to<em> Leader.MyService.Services.Consul</em> to hit the leader directly, and to reach the new leader just few seconds after the switch.</p><h3>Visibility</h3><p>The status of each component is visible in various ways:</p><ul><li><em>Consul Dashboard </em>— Consul provides a very clear dashboard giving us the status of every healthcheck in realtime, including the response that the application returns upon request</li><li><em>Grafana Metric</em>s — Grafana is the main monitoring tool used in the Sportsbook product, and Consul also produces health metrics that can be used for alerting</li><li><em>Kubernetes Dashboards</em></li><li><em>Kibana </em>— The Sportsbook system uses the Elastic/Logstash/Kibana stack for logging purposes, and the monitoring system takes advantages of it by inserting clear and detailed logs about any kind of issues encountered for each monitor. It is very useful for troubleshooting purposes of both the application and the monitoring system itself</li><li><em>Kafka </em>— A dedicated Kafka Topic containing the status of each provider integration. This is a separate component that can be used to allow our Sportsbook to dynamically react on health issues, for example by switching the provider used to offer a certain game for further calculation, requiring as little as possible to handle such cases manually.</li></ul><h3>Usage Example</h3><p>To use the system, all that is needed in the startup.cs class of the application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/633/1*oI1c7N9rF77s4GOr0ryfhA.png" /><figcaption>A configuration example with several monitors.</figcaption></figure><p>Once this is done, it will be necessary to add a line available in the extension package to integrate with .net core health check. The returned status of the health checks system takes automatically in consideration the status of all the monitors registered, for readiness and liveness.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/651/1*WvXdpwqCKPwz4vZ_LKr6Ng.png" /><figcaption>this will add default health check routes /health-readiness and /health-liveness</figcaption></figure><p>Finally, to be able to start/stop business services based on the readiness of the application, simply register to the event that the HealthMonitorService exposes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/734/1*oLeD7grjVYp3tNgd_SGHDw.png" /><figcaption>this can be easily combined with Background or Hosted services.</figcaption></figure><h3>Recap of capabilities and advantages</h3><p>Thanks to the monitor plugin system, the implementation of monitoring is easy and quick, and brings immediate advantages to a new project in terms of resiliency. Developers are quickly capable of writing custom monitors, and configuration is simple and easy.</p><p>The seamless integration with the leader election package of feeds makes the creation of a self-healing, leader-election system based on Consul straightforward, as several cases are handled out of the box.</p><p>Already existing metrics and dashboards that have been refined with past experiences allow us not only to react quickly in case of troubles, but also to rule out false positives due to metrics infrastructure issues. Moreover, a quick call to any of the endpoints or a query in the Kibana logging system will return clear data about which monitor is firing and the result of the overall monitor aggregation.</p><p>The fact that the monitors are pluggable and reusable also means that the metrics and alerting logic that can be attached to them can be easily reused in different applications.</p><p>As a result, this allows us to have a self-healing system that will stay down only the minimum amount of time for the dependencies to recover, and provides automatic resolution of problems that before would have required manual intervention from developers and/or operations. In most cases, IT and business do not even notice that a (short-lived) problem has occurred. Only the alerting and auditing system keeps track of this.</p><p>A business service (intended as an entity capable of processing business logic) can utilize the health-monitoring system in various ways:</p><ul><li>It can subscribe to the health event triggered by it, and react accordingly to shutdown a consumer, fire an alert , trigger another event, etc.</li><li>It could trigger a health check explicitly as part of a catch statement and control an error caused by the health status of the application as soon as possible.</li></ul><p>The overall infrastructure instead can use this system to allow:</p><ul><li>Automatic restarts of containers UNTIL the dependency for which the restart is required does not get back online</li><li>Automatic split of load if only some of the instances are unhealthy (for example, connectivity disruption in some nodes), not only in terms of HTTP traffic but also in terms of Kafka rebalancing</li><li>Automatic leader switch if a leader gets unhealthy, and a complete stop of the system if every instance is unhealthy</li></ul><h4><strong>Example : results in our SSH provider integration</strong></h4><p>We achieved a very flexible resiliency system that will allow us to perfectly configure the behavior we would like to observe in our application. Our SSH monitor can be customized to allow the application to keep trying the connection for 30 seconds before giving up; The HTTP monitor could mark the instance degraded (allowing us to register a warning) but not do anything for several hours before marking the instance as unhealthy; and the integration with the leader election system will ensure a smooth transition to a healthy instance and continuation of processing as soon as problems with 3rd parties or DraftKings infrastructure are resolved.<br>All the monitors can then be transformed in extension packages and reused, as the Kafka, SqlServer, Vault, and HTTP monitors have pretty standard requirements, and a package will be very useful in other cases in the future, reducing the time needed to implement our architectural requirements in our next integrations.</p><h3>Conclusion</h3><p>This library, together with the integration with the leader election system and the overall infrastructure at DraftKings, is the result of 2 years of constant improvement and discussions between lots of people in various teams. We’re proud to say that this system reduced the amount of incidents and manual interventions drastically, significantly increasing the confidence in the overall Sportsbook solution. The self-healing capabilities of the system reduced the amount of times people had to be paged due to infrastructure problems, improving the quality of life of developers and the quality and consistency of DraftKings’ offering over time. The considerable investment of time spent in designing and implementing the solution has been fully repaid by allowing people to focus more on product and less on solving the same technical requirements every time, and reduced the time to develop a solid integration by 2 to 3 times, making our roadmaps more flexible and more capable of adjusting to new challenges and requirements.</p><p>Want to learn more about DraftKings’ global Engineering team and culture? Check out our <a href="https://careers.draftkings.com/draftkings-life-blog/engineering/?utm_source=Medium&amp;utm_medium=Blog&amp;utm_campaign=DK+Blog&amp;utm_content=Medium+DK+Life+Engineering">Engineer Spotlights</a> and <a href="https://careers.draftkings.com/jobs/?utm_source=Medium&amp;utm_medium=Blog&amp;utm_campaign=Job+Openings&amp;utm_content=Medium+Open+Jobs">current openings</a>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4f31ff2bb04e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/draftkings-engineering/resiliency-in-feeds-integration-4f31ff2bb04e">Resiliency in Feeds Integration</a> was originally published in <a href="https://medium.com/draftkings-engineering">DraftKings Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>