<?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 Sagynysh Baitursinov on Medium]]></title>
        <description><![CDATA[Stories by Sagynysh Baitursinov on Medium]]></description>
        <link>https://medium.com/@saga-saga?source=rss-1b801fb4f76e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*R8BvXNiu7Z31mQupyt_0pA.png</url>
            <title>Stories by Sagynysh Baitursinov on Medium</title>
            <link>https://medium.com/@saga-saga?source=rss-1b801fb4f76e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 21:23:46 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@saga-saga/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[Ensuring Data Consistency between Event-Driven Microservices]]></title>
            <link>https://saga-saga.medium.com/ensuring-data-consistency-between-event-driven-microservices-1df01da06fad?source=rss-1b801fb4f76e------2</link>
            <guid isPermaLink="false">https://medium.com/p/1df01da06fad</guid>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[data-consistency]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[event-driven-architecture]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[Sagynysh Baitursinov]]></dc:creator>
            <pubDate>Sun, 28 Aug 2022 14:48:18 GMT</pubDate>
            <atom:updated>2025-03-12T23:44:29.439Z</atom:updated>
            <content:encoded><![CDATA[<p>Asynchronous Event Driven Architecture is a popular design choice when building a system consisting of distributed services. This design helps to achieve the choreography<strong> </strong>of (micro)services, making them loosely coupled, removing a need to centrally coordinate business processes, while avoiding single point of failure and bottlenecks for the whole system. Besides, it makes services easier to test and shapes their boundaries and responsibilities clearly. If it sounded convincing enough to adopt Event-Driven Architecture for your next project, you might be thinking about what kind of messaging tool to use for propagating events between your (micro)services. Regardless of your choice, be it Apache Kafka, AWS SQS or ActiveMQ, a broker cannot guarantee you that messages will never get lost when technical failures happen and are not handled properly by the application services. Undelivered or falsely delivered events would lead to inconsistent state of the system, which might disrupt business processes and be hard to detect. To avoid such outcomes it should be the responsibility of a developer to design their system to work with message brokers in a way that is resilient to failures. This article will explain how fault tolerance can be achieved using two design patterns: <strong>Transactional Outbox</strong> and <strong>Idempotent Consumers</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Y_XepjByQgC3zTI8" /><figcaption>Photo by Ann H from Pexels</figcaption></figure><p>In a happy scenario Event messages have to notify interested services about a domain state change, which occurred in another part of the system. Often that domain state is stored in a Database and when Database change happens, a corresponding Event is propagated via Message Broker into subscribed services. This way services stay eventually consistent between each other regarding the mutating domain state. However, technical failures do happen. They can happen on the side of a message broker, or on the consumer/producer services side. They might occur due to an unexpected software error, forced restarts, faulty deployment configurations, electricity shutdown at your data center, etc. Obviously you cannot choose at which exact moment failures may take place, to provide time for your processes to finish gracefully or revert what they might have already started. But what you can do is to design your services in such a way that after interruptions, processes re-start again and no events will get lost unprocessed; as a result domain state is not left half way incomplete. Being able to recover from failures is the key to reaching data consistency across the system. This article will demonstrate how this can be achieved on an example of a simple asynchronous event based communication between two services.</p><h3>Example application: Online Newsletter</h3><p>We have a task to implement a simple software, which consists of two microservices: <strong>Subscriptions-service </strong>and <strong>Newsletter-service</strong>. <strong>Subscriptions-service</strong> faces a front-end application, takes care of users subscriptions. <strong>Newsletter-service</strong> gets notified about new subscribers via events so that it can send them newsletters on a regular basis. Both microservices need their own databases to perform their responsibilities: <strong>Subscriptions-service </strong>needs a database since it stores data about <strong>subscribers </strong>already present, so it can prevent users from subscribing multiple times, etc. On the other hand, <strong>Newsletter-service </strong>is interested in storing all active subscriptions as <strong>newsletter-targets</strong> so that it can email newsletter issues to them. Note that these two do not share a single database, because we want our microservices to be truly decoupled and independent from each other. They may even utilize different Database management systems.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/571/1*0eTYohEaMsQAnJjJZPm11Q.png" /></figure><p>As you may see from the diagram above two microservices are communicating via a message broker. <strong>Newsletter-service</strong> listens to events produced from <strong>Subscriptions-service</strong> of type<strong> subscriber.created</strong>, which contain information about the subscriptions created via synchronous REST calls. Let’s see what would be the expected happy path for the successful domain state change propagation from service one to service two.</p><h3>Happy path for a user subscribing to the newsletter</h3><ol><li><strong><em>Front-end</em></strong><em> application sends an HTTP request to sign up for the newsletter</em></li><li><strong><em>Subscriptions-service </em></strong><em>creates and commits the new </em><strong><em>subscriber</em></strong><em> to its database</em></li><li><strong><em>Subscriptions-service </em></strong><em>synchronously notifies the </em><strong><em>message broker</em></strong><em> about a </em><strong><em>subscriber.created</em></strong><em> event, and the event is propagated to consumers’ queues</em></li><li><strong><em>Front-end</em></strong><em> application receives HTTP response with status 201 (created) from </em><strong><em>Subscriptions-service</em></strong></li><li><strong><em>Newsletter-service</em></strong><em> consumes the </em><strong><em>‘subscriber.created’</em></strong><em> event</em></li><li><strong><em>Newsletter-service</em></strong><em> creates and commits the new </em><strong><em>newsletter-target</em></strong><em> to its database</em></li><li><strong><em>Newsletter-service</em></strong><em> acknowledges the </em><strong><em>broker</em></strong><em> that </em><strong><em>subscriber.created</em></strong><em> event got successfully processed, so it can be removed from the message queue</em></li></ol><p>That was a happy scenario when the subscriber’s data got saved in both microservices’ databases, consistent with one another. However, as stated before you should never design your services with only a happy scenario in mind. Such Optimism Driven Development will lead you to situations when the system has no way to recover when unexpected failures occur.</p><p>Some failures will cause only minor inconveniences: for example if <em>Step1</em> or <em>Step2 </em>fail, then a user or the front-end application can retry the subscription request and the second attempt might succeed. Even if the second request doesn’t succeed, the user may be asked to come back and try again later. In the end, the domain state doesn’t stay corrupt. Let’s have a look at more inconvenient system states.</p><h3>When the system ends up in inconsistent state</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*12qt2CxnbetGSLaT" /><figcaption>Photo by Pixabay from Pexels</figcaption></figure><h4><strong>Lost event:</strong></h4><ul><li>If <em>Step2 </em>(database state change) succeeds and <em>Step3 </em>(event publishing) fails or isn’t even attempted due to application shut-down, subscriber data will be written in <strong>Subscriptions-service </strong>database, even though an event about this state change will not get published. Besides, as <em>Step4 </em>(response to front application) is not reached, the front-end<strong> </strong>might display an initial error, but after a retry of the <em>Step1 </em>(Rest call) user is to be informed that the initial subscription attempt has succeeded, and subscription is saved. Unfortunately, the user shouldn’t get too excited, as the second microservice, <strong>Newsletter-service, </strong>has no idea about the <strong>newsletter-target </strong>that had to be created, but was not due to lack of <strong>subscriber.created </strong><em>(Step3)</em> event produced. Consequently, the user will never get the next issue of the newsletter, even though <strong>Subscriptions-service </strong>assures them that their subscription has succeeded.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/581/1*xu190VHTZQ0f0zrriarUtA.png" /><figcaption>Lost event inconsistent state</figcaption></figure><h4>False event:</h4><ul><li>Trying to mitigate the <strong>“Lost event”</strong> inconsistency scenario, some developers might think to redesign the process in such a way that a <strong>subscription.created </strong>event is published first, and only after a successful publishing, <strong>subscriber </strong>entity creation is committed into the database. But if the database commit does not succeed<strong> </strong>when<strong> subscription.created </strong>has already been published, we will find the system in an inconsistent state. <strong>Newsletter-service </strong>is informed about the new<strong> newsletter-target</strong>, even though <strong>Subscription-service</strong> has no new subscriber saved. The consequence would be that users will receive newsletter emails even though they might think that the subscription attempt has failed.</li></ul><figure><img alt="False event, resulting inconsistent state" src="https://cdn-images-1.medium.com/max/589/1*o8JQfdrtcGDMvXiW3M3S8w.png" /><figcaption>False event inconsistent state</figcaption></figure><h4>A single event processed multiple times:</h4><ul><li><em>Step6 </em>(database state change) succeeds and <em>Step7 </em>(event acknowledgment) fails: <strong>Newsletter-service</strong> fails to acknowledge the broker that it has processed the event message successfully. For these situations, Message Brokers often have message re-delivery mechanisms. So when event acknowledgement is not executed,<strong> subscriber.created</strong> message can be re-delivered, and consumed by <strong>Newsletter-service</strong> multiple times. If not designed to handle this scenario, <strong>Newsletter-service </strong>creates two (or more) <strong>newsletter-target</strong> entries for the same <strong>subscriber</strong>, which could bring us to a situation when one user is receiving the same newsletter more than once.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/571/1*_XWbk1BPrS9cHIct8xwkag.png" /><figcaption>Mishandled duplicate event consumption</figcaption></figure><h3>How to ensure that data stays consistent across services?</h3><p>The failure types “<strong>Lost</strong> <strong>or</strong> <strong>False</strong> <strong>events</strong>” described above may occur if a service does not persist the mutated state of an entity in Database and does not produce an event informing about the state mutation <em>atomically</em>. <em>Atomic</em> here means guaranteed indivisibility: if one action succeeds, the second has to succeed as well. If the second action fails, the first one must be reverted back. When applied to our example, two actions that must be done in an <em>atomic</em> manner are 1) having<strong> </strong>a <strong>subscriber</strong> entity committed to Database and 2) having a<strong> subscriber.created </strong>event published into Message Broker. Fortunately for us, database management systems provide possibilities to perform operations within <em>atomic</em> transactions. <em>ACID</em> transactions in relational (SQL) databases may span several local operations concerning multiple entries across different tables, guaranteeing their <em>atomicity</em>. NoSQL databases on the other hand ensure <em>atomicity</em> of one document’s or one row’s insertion or modification.</p><h4>But how to <em>ensure atomicity</em> of operations writing into two separate systems: Database and Message Broker?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/381/1*gxunvHXz5D8ycegfhIbXsA.png" /></figure><p>There are such Database management systems and Message Brokers that support distributed transactions (XA — eXtended Architecture) across multiple services with a help of a technique called two-phase commits (2PC). However, they significantly affect the performance of the system, limit developers&#39; choice of tools, and on top of that, may lead developers into the Optimism Driven Development. <strong>Therefore, I cannot recommend distributed transactions spanning multiple services. </strong>Another solution to the problem might be required…</p><h4>Transactional outbox</h4><p>The solution is to start recording and publishing events using a design pattern called <strong>Transactional outbox</strong>. In this pattern, events are written to the same database where the domain state change is recorded in a scope of a single local transaction. Since the<em> atomicity</em> of these two operations is guaranteed by the DBMS, we can be sure that <strong>subscriber.created</strong> event will be known in the system only if the actual <strong>subscriber </strong>is persisted. If one fails, the second one is also reverted. In the relational databases a separate “events” table might be needed for storing <strong>subscriber.created </strong>or other events. In NoSQL databases, events are to be written into the same document that receives a domain state change in the scope of a single write operation.</p><p>In order to publish the events written into the database to their actual destination, which is a Message Broker, a technical <strong>publisher</strong> process must be implemented into the publisher service. It must regularly query not yet published events and publish them, marking them as<em> SENT</em> afterwards.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/753/1*S-MKiS200CAn-Tg-7atBug.png" /><figcaption>Transactional outbox</figcaption></figure><p>Note that it’s still possible to have a service failure to occur when the <strong>outbox event publisher </strong>process finished with publishing the <strong>subscriber.created </strong>event, but failed to mark the entry in the outbox table as <em>SENT</em>. Unfortunately,<em> Atomicity</em> between these two actions cannot be easily guaranteed. The worst that can happen in such a case is the event being published a second (or more) times after the outbox publisher fails and starts again. And it is something we need to learn to live with. <strong>Transactional outbox</strong> design pattern helps us with avoiding issues “<strong>Lost/False</strong> <strong>events</strong>” described above by providing <em>atomicity</em> of event recording and entity change. As the next step we need to take care of the third issue, which is: <strong>A single event processed multiple times</strong>. Because now it can happen due to several different reasons:</p><ol><li>Transactional outbox publishing the same message into Message Broker multiple times due to technical failures.</li><li>Message broker delivers the same message to Consumer service multiple times. <strong>Important note: </strong>usually Message Brokers do not guarantee <em>“only once delivery”,</em> while guaranteeing <em>“at least once delivery”</em> of a message. If you think about how the just-described <strong>transactional outbox</strong> pattern works, it could be relatable to why <em>“only once delivery”</em> is not a usual guarantee of Message Brokers.</li><li>Consumer service fails to acknowledge the Message Broker that the message got processed successfully, so the broker re-delivers the message to the consumer a second or more times.</li></ol><p>As there are multiple sources of “event multiplication” occurring, the issue must be taken care of. And we can do so on the consumer services’ side. There’s another design pattern that will help us to solve the issue.</p><h4>Idempotent consumer</h4><p>For those who hear the term first time here’s the description of Idempotent Consumer from Chris Richardson (<a href="https://microservices.io/patterns/communication-style/idempotent-consumer.html">microservices.io</a>):</p><blockquote>the outcome of processing the same message repeatedly must be the same as processing the message once</blockquote><p>If we apply this to our scenario, <strong>Newsletter-service</strong> should be designed in such a way that even if it consumes the same <strong>subscriber.created </strong>event twice or more times, the result should be the same as if it consumed it once.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/231/1*GBS5cspa8Fh8n4TWs7n0qQ.png" /><figcaption>Only one newsletter target is created even though subscriber.created got consumed multiple times</figcaption></figure><p>There are a few ways how to make the Consumer service idempotent:</p><ol><li>Create and use an events inbox table, which will store incoming events’ IDs as primary key, so the event cannot reach consumer service more than once.</li><li>Store IDs of incoming events together with the related business entities. F.e. newsletter-target entity will be aware of its creating event’s id. Make the event id unique using database mechanisms.</li><li>Build your consumer to be naturally idempotent within the domain logic itself. For example in the case of handling the <strong>subscriber.created </strong>event, it’s possible to impose uniqueness of newsletter-target’s <strong>email</strong>. Ignore duplicate events bringing the existing <strong>email</strong> as a new newsletter-target.</li></ol><h3>Conclusion</h3><p>In this article, we discussed two techniques called <strong>Transactional Outbox</strong> and <strong>Idempotent Consumer</strong>, which can help you build distributed microservices communicating asynchronously without data loss or false data propagation. A great thing about these techniques is that they can be utilized together with different database management systems and message brokers. When properly implemented they do not negatively affect the performance of the system, leaving the system to be scalable and loosely coupled. At the same time you can know how your system ensures eventual data consistency within itself. I hope the article was helpful to you. Keep in mind to think about what can go wrong in the system while designing and implementing it. Do not be driven solely by optimism, and stay prepared!</p><p><strong>Further readings:</strong></p><p>Chris Richardson: <a href="https://microservices.io/patterns/data/transactional-outbox.html">https://microservices.io/patterns/data/transactional-outbox.html</a></p><p>Chris Richardson: <a href="https://microservices.io/patterns/communication-style/idempotent-consumer.html">https://microservices.io/patterns/communication-style/idempotent-consumer.html</a></p><p>Dave Syer: <a href="https://www.infoworld.com/article/2077963/distributed-transactions-in-spring--with-and-without-xa.html">https://www.infoworld.com/article/2077963/distributed-transactions-in-spring--with-and-without-xa.html</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1df01da06fad" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Open/Closed principle on the example of Togglz java library + Spring Boot Application]]></title>
            <link>https://saga-saga.medium.com/open-closed-principle-on-the-example-of-togglz-java-library-spring-boot-application-bd774b9c1f55?source=rss-1b801fb4f76e------2</link>
            <guid isPermaLink="false">https://medium.com/p/bd774b9c1f55</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[feature-toggles]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Sagynysh Baitursinov]]></dc:creator>
            <pubDate>Tue, 02 Mar 2021 22:25:10 GMT</pubDate>
            <atom:updated>2021-03-07T00:35:32.476Z</atom:updated>
            <content:encoded><![CDATA[<h3>Open/Closed principle on the example of Togglz Java library + Spring Boot</h3><h3>1. Introduction. Push your commits directly to prod? Why not, Togllz for the rescue!</h3><p>Once in my developer consultant career I worked in a team that follows extreme programming methodology. The team has built a CI/CD pipeline utilizing the benefits of trunk-based development on a single Git branch. Their fast code delivery practices rely on teammates’ common understanding that a developer should be able to push their code to the main branch without much hesitation, being confident that a code piece would not appear in production servers before it’s been quality checked. An automated test suite in CI/CD pipeline, which sufficiently covers systems’ behavior, assures that new changes to the code-base will not bring bugs. Nevertheless, not every commit pushed to the code repository is intended to go live as soon as possible. There are situations when a feature needs manual approval, manual QA-ing, or when it is expected to start running in production servers only at some specific time. In such cases <strong>feature toggles</strong> were found handy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/491/1*agceez2W5mT5XHAtol5hxg.png" /></figure><p>I started using a java library called Togglz last year and so far happy with what it offers. It’s a relatively simple java library, which implements various ways of toggling features in your code. I found the library easy to integrate into a Spring-managed project. Besides, Togglz comes with an extension, ready-to-use web GUI. But what I value in this library more than everything it offers is its openness for customization. A developer using Togglz can tune its functionality using instruments shipped together with the framework or bringing in their own self-written pieces of code. For example Feature toggles’ states (<em>on/off</em>) can be loaded from Spring property files, JDBC data source, DynamoDB table, etc. I am leaving <em>“etc.”</em> here as the implementations of Togglz’ <em>StateRepository </em>interface that I’ve touched and found useful for my projects are the previously mentioned ones. However, the library offers a variety of its own implementations for <em>StateRepository</em>, an interface that you can implement yourself if you wish and as you wish. The same applies to other interfaces of Togglz: you can substitute default functionalities of the library with your own without much hustle. I believe this came true because object oriented design rules lying behind the famous acronym SOLID was well followed:</p><ul><li><strong>Single-responsibility.</strong> Interfaces inside of Togglz mechanism are assumed to trigger simple tasks.</li><li><strong>Open/Closed principle. </strong>The core functionality of the library doesn’t need to be changed in order for it to be customized. We will stop on this one in particular.</li><li><strong>Liskov substitution principle. </strong>Classes ensuring the whole feature toggling business can be easily substituted with their subtypes.</li><li><strong>Interface segregation. </strong>Many simple task performing small interfaces are provided to collectively maintain the whole feature toggling business.</li><li><strong>Dependency inversion.</strong> The core functionality of the library does not depend on the specifics of interface implementations meaning various implementations can be injected into the framework.</li></ul><h3>2. Building a simple spring boot application.</h3><p>To demonstrate the features provided by the library and possibilities to extend them, I created a simple spring boot application that just says <em>hello</em> via rest API.</p><p>A rest controller that calls a <em>HelloService</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7wqqO4vgVUpIwdjSw0Shww.png" /><figcaption>My friendly controller</figcaption></figure><p>And the service, which is quite basic, simple enough, just returns its <em>hello</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TNXL0uMS22o-51M4-PLNSA.png" /><figcaption>A really basic service</figcaption></figure><p>After an ordinary spring boot deployment our application starts handling HTTP requests:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lUI3BqI8RDEKCa4xxpM21Q.png" /><figcaption>One simple curl</figcaption></figure><p>As part of our next task let’s imagine we want to make the <em>HelloService</em> to speak some other language, for example, Kazakh (“<em>Hello world</em>” in Kazakh would be “<em>Sálem Álem</em>”). Additionally, the task has a requirement saying that the application maintenance team wants to be able to switch the language at their will without needing to redeploy the application. It sounds like a good reason to try out <strong>Togglz</strong> library.</p><h3>3. Integrating Togglz library into the application. Basic app feature.</h3><p>Few configurations are needed to bring Togglz into the project and enable its GUI to toggle and monitor application features. In the following demo project features are represented in the code as java enumeration values. The framework is to persists the features’ state in a relational database.</p><p>First things first. The maven dependencies to bring Togglz and the Togglz UI into our project:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YYLMg_C8jYvzkztkX9kZ6Q.png" /><figcaption>Togglz maven dependencies in pom.xml</figcaption></figure><p>Next we want to setup a property-file sourced by spring. The following lines are there to enable the Togglz console. Its GUI console has its own security mechanisms, which I ignored for this post’s scope. Besides the Togglz security, it’s also possible to use spring security module to configure access to the Togglz web console.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gluNgqis9y0PF86wXfscJQ.png" /><figcaption>Togglz’ properties</figcaption></figure><p>A Spring Java configuration defining beans needed for the library to function. The most important bean here is <em>featureManager</em> of type <em>org.togglz.core.manager.FeatureManager</em>, which is dependent on other two beans.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MaBV16Ee9mAFVQe096Sraw.png" /><figcaption>A spring config class defining featureManager bean</figcaption></figure><p>The <em>org.togglz.core.spi.FeatureProvider </em>instance is initialized as <em>org.togglz.core.manager.EnumBasedFeatureProvider</em> and uses the following enum as representations of feature names:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hRzUf8fgh7uqqKR1MdzUnA.png" /><figcaption>A lonely enum value representing a single togglz feature</figcaption></figure><p>So far we have only one lonely feature to toggle on and off. Note that the enum has to extends <em>org.togglz.core.Feature</em> class.</p><p>To store states of feature toggles I chose <em>org.togglz.core.repository.jdbc.JDBCStateRepository</em> implementation coming from Togglz package, which i<em>s </em>expecting and depending on <em>javax.sql.DataSource </em>configured for an underlying SQL database. Besides, many different implementation classes of <em>org.togglz.core.repository.StateRepository</em> interface are shipped in the jars we’ve already imported to the project:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-2E4fY04TbkCE7ecNW2wNw.png" /><figcaption>StateRepository implementations</figcaption></figure><p>I’ve used extensions of the library that make it possible for Togglz to store the feature states in NoSQL databases as well (e.g. AWS DynamoDB). However, this time we use a relational database as an example.<br>Querying the data from the DB:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4pkr-7dI1sXemHZjBmnGfA.png" /><figcaption>A simple SQL query to see what’s in the automatically created table</figcaption></figure><p>I place the feature toggle in the service class. Note, as usage of the <em>featureManager</em> becomes part of the application’s functionality, it’s important to test both states of the feature: when it’s toggled on and off.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BPo1DOXZPMcl7hBW4mP1Rg.png" /><figcaption>Our basic service is getting bit more complicated</figcaption></figure><p>Let’s see how the toggle can be turned on. It’s done pretty easily actually. One mouse click sends an HTTP request, which is automatically handled and persisted by Togglz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dNTzRhGd60xOYQ1HSmVBoA.png" /><figcaption>It’s red</figcaption></figure><p>…aaand it’s on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HxgyR1SJnein2ismhoPtHA.png" /><figcaption>Green</figcaption></figure><p>DB’s state should change as well as the color of the button on UI. Since the data is saved in the database application restarts will not make it forget that feature is enabled.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tapxmokaPHRfgvscukvyNw.png" /></figure><p>The changes can be noticed in the app’s behavior:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rlh1L7GzetDdu3ccNcqieg.png" /><figcaption>curl is giving another result as the feature is on</figcaption></figure><h3>4. Feature activation strategies. Time based toggling.</h3><p>Now, let’s imagine that as their next request, people maintaining the app ask you to toggle the feature on and off automatically, based on time. To support this kind of feature toggling activities Togglz has got its built-in activation strategies, accessible directly from the web UI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SzWWXKNL1P36c0pbVcLTcg.png" /><figcaption>Built-in activation strategies on Togglz web GUI</figcaption></figure><p>I chose the ‘<em>Release date</em>’ activation strategy and entered the release date I wanted in the text-boxes appeared below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ggRfL7Kh7gMH0K9xFSa-JA.png" /><figcaption>Activation strategy parameters shown on Toggz web GUI</figcaption></figure><p>The params are reflected in the feature state repository. You could notice the columns called “<em>strategy_id</em>” and “<em>strategy_params</em>”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z-RyCU8C6mbUaGBGSOy_jA.png" /><figcaption>Application strategy parameters stored in a relational DB</figcaption></figure><p>What I appreciated about the activation strategy mechanisms in Togglz is the fact that the params for different strategies have a generic form of storage. How is it even useful for a developer? For answering this question let’s imagine another situation. Time passes and now our lovely maintenance team wants the feature to be enabled automatically every day, but only during certain day hours. And again, it’s expected to be possible to change the activation time without needing to redeploy the server or touch the codebase. We’re lucky that we already have Togglz in place. Thanks to the unified format of inputting parameters in the UI, and the generic way of how they’re stored in <em>StateRepository</em>, and the way they’re handled by the framework, developers can use this entire mechanism for building their own custom activation strategies. So let’s experience some openness for extension principle, which means extending the library’s features without even touching its source code.</p><h3><strong>5. Extending the library. Building a custom feature activation strategy.</strong></h3><p>Our custom activation strategy should extend an interface called <em>org.togglz.core.spi.ActivationStrategy</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mcic9_bNLhlra15FwI9cgw.png" /><figcaption>Custom <em>ActivationStrategy</em> java class</figcaption></figure><p>Note that we’re obliged to implement methods of the <em>ActivationStrategy </em>parent class. Those methods are needed by the framework to display strategy’s parameters on the GUI, and . Obviously, we also are expected to handle these parameters in <em>isActive</em>() function, which is declared as a method returning a boolean value. Some parameter validation is recommended in the method, but I don’t want to over-complicate the example code.</p><p>Activation strategies are wired into an <em>activationStrategyProvider </em>bean, which is itself a dependency of the <em>featureManager</em> bean:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*clvHcp88EGHBKr5Kht7oyw.png" /><figcaption>Slightly modified DefaultActivationStrategyProvider being injected into the FeatureManager bean</figcaption></figure><p>The results of this exercise can be immediately seen on the web GUI. We set the parameters to the desired values so that app can practice speaking Kazakh 2 minutes a day from 19:25 to 19:27 Zulu time:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mZkcMdClhDcP8iQHS-DRjw.png" /><figcaption>Custom activation strategy on web GUI</figcaption></figure><p>And consequentially the parameters are reflected on the underlying database’s state:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SgIqaTrr2-CtHF6oAUcDCg.png" /></figure><p>Results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LQq0fyHa3MdPPDn1ZmSXIw.png" /><figcaption>Few more curls. Feature activation strategy works as desired</figcaption></figure><h3>6. Conclusion</h3><p>So that’s it. Following simple steps, we managed to configure and customize Togglz library. While doing so we have not touched the insides of the library, because it is <strong>closed </strong>for a modification. However, it was possible to add additional functionality to it as it was <strong>open</strong> for extending it. What I’d like to highlight here is that if you design your application/library in a way that dependencies are externally injected into your classes, and if you provide possibilities for the dependencies to be easily substituted by their different implementations (Liskov substitution principle), and if the library stays open for someone extending it, then, as a result, your code will become one pleasant code piece to use and tune. In my opinion, Togglz is a good example of a simple lightweight library, whose authors followed the <strong>SOLID</strong> principles when designing their APIs. I would defintely recommend it to friends.</p><p>Best regards,</p><p>Saga</p><h3><strong>7. Useful links</strong></h3><ul><li>Togglz web site: <a href="https://www.togglz.org/">https://www.togglz.org/</a></li><li>Togglz source code: <a href="https://github.com/togglz/togglz">https://github.com/togglz/togglz</a></li><li>Demo application source code: <a href="https://github.com/SagynyshBaitursinov/togglz-demo">https://github.com/SagynyshBaitursinov/togglz-demo</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bd774b9c1f55" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>