{"@attributes":{"version":"2.0"},"channel":{"title":"Indu Alagarsamy","description":"Indu Alagarsamy's personal website for blog and events","link":"https:\/\/indu.dev\/","pubDate":"Sun, 20 Feb 2022 03:23:05 +0000","lastBuildDate":"Sun, 20 Feb 2022 03:23:05 +0000","generator":"Jekyll v3.9.0","item":[{"title":"The Captain of the Night Watch","description":"<p>This article was originally published in <a href=\"https:\/\/leanpub.com\/ddd_first_15_years\">Domain-Driven Design: The first 15 years<\/a> ebook.<\/p>\n\n<p><em>This article is based on a conversation that ensued during a midnight stroll in the streets of Amsterdam with Eric Evans, Paul Rayner, and Mathias Verraes.<\/em><\/p>\n\n<p>There I was, standing in front of a masterpiece, thanking my lucky stars of the incredible opportunity that I had just been given to be there, to be present in that moment. I was in front of Rembrandt\u2019s Night Watch, standing in complete awe. The captain was striking and regal. The light flowed into the room, as if the heavens were trying to illustrate his authority.  He was giving orders to the people around him. There was a sense of life and belonging, a canvas that was filled with so much emotion all captured so beautifully. I was in the midst of it all, facing the captain and for a brief moment, it almost felt as if he was walking straight toward me.<\/p>\n\n<p>Ever since I first saw the windmills of Zaanse Schans in a travel book, I was fascinated and wanted to visit Amsterdam someday. So I was beyond thrilled when Mathias invited me to speak at DDD Europe 2018, and the venue was Amsterdam! The universe had granted my wish. Not wanting to waste a single minute, I started my exploration of the city with the Rijksmuseum.  When I arrived at the museum, I realized that I had only about an hour, so I asked the museum attendant what\u2019s the one thing I shouldn\u2019t miss at the museum. Non-judgmentally she said, \u201cRembrandt\u2019s Night Watch.\u201d And that\u2019s how I first met the captain on a complete coincidence.<\/p>\n\n<p>Fast-forward to the conference. Despite my jet lag, my talk at DDD Europe went fabulously well, and at the conference closing, I was invited to go to dinner and hang out with the DDD greats: Eric Evans, Paul Rayner, and Mathias Verraes. I felt incredibly lucky. At dinner, we discussed Bollywood movies, and I was pleasantly surprised listening to Eric talk about \u201cLagaan\u201d and explain the storyline to Paul and Mathias.<\/p>\n\n<p>As we were making our way back to our hotel we found ourselves in front of the Rembrandt statue at the city square. Rembrandt was standing on a pedestal and right below him, it was as though his painting had come alive at the stroke of midnight. All the characters that Rembrandt had meticulously detailed out in his Night Watch were transformed into bronze statues and brought to life in 3D. There were 22 statues including one for the dog, all standing in the same pose created by Rembrandt, frozen in time for the world to see. And there was the captain again. It felt like deja vu standing face to face with him, this time in 3D.<\/p>\n\n<h2 id=\"what-does-this-have-to-do-with-bounded-contexts\">What does this have to do with Bounded Contexts?<\/h2>\n\n<p>We took a selfie in front of the statues. But then Eric suggested that it\u2019s not every day you get to see what\u2019s behind the Night Watch, something you don\u2019t actually get to see in the actual painting and that we should be taking pictures from the other side. This brought up the question of different perspectives. Because the statues were 3D, you had a different view, a perspective from behind the figures as well. As we were taking pictures,  being a nerd, I had a serious question. I always have a tendency to try and relate software with actual real life things and that helps me understand the bigger picture. So the question that was burning in me this time, at the midnight hour was: would the front and back of the statues make different bounded contexts since it was essentially a different perspective of the same thing?  Do different perspectives make different bounded contexts?  It was as if the captain was trying to show me something important, but I had to try hard to grasp it.  Luckily for me, I was with the right company, so I asked Eric.  Eric with his calm and logical way of explaining things answered me without a second thought that the painting and the sculpture would be the two different bounded contexts and not the front and the back of the captain.<\/p>\n\n<h2 id=\"what-makes-the-painting-and-the-sculpture-a-different-context\">What makes the painting and the sculpture a different context?<\/h2>\n\n<p>I let that sink in for a moment. So the statue and the painting were the different contexts. Then like a puzzle piece falling into place, it started to make sense to me.  The biggest reason is because the rules around these contexts were completely different. The constraints of making art on a canvas and sculpting a bronze statue are entirely different. While the captain might appear differently from the front and the back, the constraints on the statue were the same, regardless of which angle you looked at him.<\/p>\n\n<p>I remembered the evening at the museum where I stood in front of the Night Watch. Light was streaming down on the captain as if to highlight his authority. But at the square, the captain was just one among the 22 individual sculptures. Unless you know about Rembrandt\u2019s Night Watch, you couldn\u2019t tell who was the man with all the authority. At the square there was nothing special about the captain, and definitely no special lighting. The constraints on the light were different in both the painting context and the sculpture context.<\/p>\n\n<p><img src=\"\/images\/posts\/2018-09-18-captain\/comparison-1.jpg\" alt=\"Comparison of the Captain in the painting vs sculpture\" \/><\/p>\n\n<p>When Rembrandt was painting, he didn\u2019t have to worry about how these characters were going to look from behind. 2D was perfectly sufficient. However, when the Russian artists created the sculptures they had to deal with a whole new set of constraints that pertained to creating statues out of bronze in 3D.<\/p>\n\n<p>In Rembrandt\u2019s art, the level of detail for each character was different. In the painting, the details on the captain were stunning from the wrinkles on his boots to the stitching on his vest and then some of the other characters were vague, for example the dog. The sculptures however were all equally well defined. There was no difference in the amount of detail in the captain\u2019s statue vs. the dog\u2019s statue.<\/p>\n\n<p><img src=\"\/images\/posts\/2018-09-18-captain\/comparison-2.jpg\" alt=\"Comparison of the dog in the painting vs sculpture\" \/><\/p>\n\n<p>Also, in the painting there is a character hidden in the group, that\u2019s believed to be Rembrandt himself. Whereas at the square, Rembrandt was in plain sight towering over all of his creation from his place on the pedestal. So on the surface, while the art hanging at Rijksmuseum and the sculpture at the city square both represent the Night Watch, they are bound by different constraints, have different goals, and therefore different focus and detail. That makes them different bounded contexts.<\/p>\n\n<h2 id=\"how-does-this-help-with-software-design\">How does this help with software design?<\/h2>\n\n<p>In software design, we might have to model the concept of a \u201cProduct.\u201d  However what the Product is to the \u201cSales\u201d context is different from that of an \u201cInventory\u201d context and that of a \u201cShipping\u201d context. In the Sales context, a product brings in revenue to the company. In the Inventory context, it\u2019s a thing that you have (or don\u2019t have) in some quantity. In the Shipping context, it\u2019s a thing that has some weight associated with it, which gets sent from, say, Amsterdam to California. On the surface, just like the Night Watch, it\u2019s the same. However, depending on the context, the rules are different.<\/p>\n\n<p>We have been taught early to look for nouns to help determine the objects. , We\u2019ve been so well trained to find the nouns, it\u2019s hard to think differently. In that mindset, a product is a noun; therefore it gets its own model. Things like name, description, price, how much of it you have in stock, what it would take to ship it, etc., tend to get associated with this product object model. OO always stressed behavior and data hiding and data encapsulation. But it\u2019s too easy to turn off that behavior bit part of it and just model based on pure data.  But here\u2019s the thing: would you require transactional integrity when trying to update the description of the product, compared to where you were trying to ship it? Are there any business rules to say, \u201cAll products that start with X in the name cannot be shipped to California?\u201d. If you don\u2019t have any such rules, then having the product\u2019s name and the shipping rules in the same transactional boundary doesn\u2019t make much sense.<\/p>\n\n<p>Here is where Eric\u2019s Domain-Driven Design forces you to think of individual models, as opposed to the \u201cone universal model to rule them all\u201d.  Placing more emphasis on what processes happen in the business, and focusing more on the pain points, and identifying the constraints, helps to model the context more accurately, rather than just trying to model the data in a entity driven fashion. Properties like Description and Price can be separated from the context if we apply the rule that each context must be isolated, internally consistent, and unambiguous. And most importantly that the context can have the same representation of a concept, just that different rules govern it. Just like Rembrandt\u2019s Night Watch on the canvas and the sculptures in the city square.<\/p>\n\n<p>As all nights do, this one came to an end too. I felt like I had come a full circle. From that first moment when I was in awe of the Captain at Rijksmuseum to seeing him again at the square, both Rembrandt and Eric in their own ways, showed me the nuances of the bounded context. While I had to part my ways with the captain, I walked away with a new learning and appreciation for Bounded Contexts.<\/p>\n\n<p><img src=\"\/images\/posts\/2018-09-18-captain\/group-selfie.jpg\" alt=\"Group Selfie\" \/><\/p>\n","pubDate":"Tue, 18 Sep 2018 00:00:00 +0000","link":"https:\/\/indu.dev\/ddd\/2018\/09\/18\/captain-of-the-nightwatch.html","guid":"https:\/\/indu.dev\/ddd\/2018\/09\/18\/captain-of-the-nightwatch.html","category":["Bounded","Context,","DDD","DDD"]},{"title":"Break that big ball of mud","description":"<p><em>This article was originally published on the <a href=\"https:\/\/blog.ndcconferences.com\/break-that-big-ball-of-mud\/\">NDC 2016 Blog<\/a>.<\/em><\/p>\n\n<p>Have you ever had to deal with a function that had hundreds and hundreds of lines? Code that had duplication all over the place? Chances are you were dealing with legacy code that was written years ago. If you\u2019re a Star Wars fan like I am, it\u2019s like dealing with the Force. As Yoda would say, <strong>\u201cFear is the path to the dark side. Fear leads to anger. Anger leads to hate. Hate leads to suffering.\u201d<\/strong><\/p>\n\n<p>In my 15+ years of coding, every single time I\u2019ve dealt with legacy code, fear, anger, hate, and suffering were pretty common.<\/p>\n\n<p><strong>Fear<\/strong>: I fear that monster two-thousand-line function because I know what lies beneath in that monster function. Absolutely nothing good!<\/p>\n\n<p><strong>Anger<\/strong>: I get angry when I see code repeated all over the place. On one occasion, I came across 50 modules that had the same ten lines of code. That code was trying to look up a registry key to find some detail and then writing back to HKLM. Remember the time when Vista OS introduced new OS security features? Applications with standard user access could not write to the HKLM registry keys. To be Vista compliant, the same ten lines of code needed a change in not one but 50 modules!<\/p>\n\n<p><strong>Hate<\/strong>: Of course, the next natural emotion is hate, leading to a lot of WTF moments looking at the code. What in the world was that developer thinking!? When you start duplicating the code for the second time why didn\u2019t the alarm bells go off, let alone the 50th time!<\/p>\n\n<p><strong>Suffering<\/strong>: All this naturally leads to suffering, just like the wise Yoda predicted. Because, at the end of the day, why the existing codebase has its quirks doesn\u2019t matter. It just does, and I\u2019m the one that has to deal with it.<\/p>\n\n<p>Unfortunately, I am not the only one in our industry who goes through these same emotions. Many of us experience them on a daily basis. You\u2019re probably in that same boat.<\/p>\n\n<p>You think you could probably do better. The codebase is so bad that it needs a rewrite. You look at the smart developer team around you and think, \u201cWe\u2019ve got this.\u201d Technology is much better than it was all those years ago when that legacy project began. You now have newer frameworks in your toolbox. What could possibly go wrong?<\/p>\n\n<h2 id=\"the-all-new-death-star\">The \u201cAll New\u201d Death Star?<\/h2>\n\n<p>The problem is that it requires time to wrap your head around the many nuances and nooks and crannies in that legacy code. While you might be convinced that these are the exact reasons that warrant the rewrite, chances are you\u2019ll miss a few details that might be important to your business. These oversights might end up as costly mistakes later.<\/p>\n\n<p>You may not be able to get away from your responsibility of fixing existing bugs. You might also have to add new and important features to the existing codebase to satisfy customer needs. What if you still have to support the existing system? As you\u2019re rewriting the system, how are you going to deal with these new feature requests for customers?<\/p>\n\n<p>If you\u2019ve scanned the existing code and compiled a list of features, you probably know it\u2019s going to take you a long time to get the rewrite done. Months? Years? A lot can happen in that time frame. What was relevant when you first started may no longer be relevant when you finish.<\/p>\n\n<p>How do you plan to sell the rewrite to business stakeholders? A rewrite based purely on technical concerns (like upgrading .NET Framework versions) won\u2019t sound like a convincing reason to them. If the multi-year rewrite plan does get approved by the business, what\u2019s to say you won\u2019t be making the same mistakes as your predecessors but with the technology of today? What if you accidentally end up building a new Death Star?<\/p>\n\n<h2 id=\"a-new-hope\">A New Hope<\/h2>\n\n<p>As part of supporting existing customers, it\u2019s likely you add new features to your system. Working on a greenfield project is every developer\u2019s dream. It\u2019s a place filled with unit tests, automated integration tests, and code written using the \u201cmost latest\u201d framework in town. Adding new features to existing legacy code and supporting existing customers, on the other hand, is tricky. To do it right, without breaking existing features, you\u2019ll have to try and find your inner Jedi.<\/p>\n\n<p>\u201cUse the Force, Luke.\u201d<\/p>\n\n<p>\u201cThank you, Obi-Wan. If only it were that simple!\u201d<\/p>\n\n<p>The young Luke Skywalker\u2019s job was simple. He fired those missiles and made the Death Star explode. While, you, on the other hand, now have to navigate a minefield. One line of code in the wrong place can break existing functionality. And it can upset QA, product owners, and other developers, as it might lead to slipping deadlines. Even worse is if this bug isn\u2019t caught in the development, QA, and staging environments and only showed its nastiness in production.<\/p>\n\n<p>While this paints a pretty dark picture, every problem has a solution.<\/p>\n\n<h2 id=\"event-driven-architecture-to-the-rescue\">Event-Driven Architecture to the Rescue<\/h2>\n\n<p>Event-driven architecture is a software design style that uses messaging techniques to convey events to other services. It promotes asynchrony. Events are nothing but simple data transfer objects (DTO) to convey something significant that happened within your business system. They can signify a change, such as a threshold change, to indicate that something just completed, that there was a failure, etc. These events can then be used to trigger other downstream business processes.<\/p>\n\n<p>Events typically contain the relevant identifier for the related entity, the date and time of occurrence, and other important data about the event itself. For example, the CustomerBecamePreferred event would contain relevant details, such as the CustomerId, CustomerPreferredFrom, CustomerPreferredUntil \u2014 i.e., the date and times that are relevant to this event and other important information.<\/p>\n\n<p>When the condition in the code is met, an event is published. The interested parties of this event then take the appropriate action upon receiving it. These interested parties could be another service, which might publish another event and so on. In this model, the software system follows the natural business process.<\/p>\n\n<p>The beauty of this model is that the publisher of the event just publishes the event. It has no knowledge of what the subscriber intends to do with it. Event-driven architecture leads to loosely coupled systems.<\/p>\n\n<h2 id=\"back-to-the-legacy-conundrum-how-can-event-driven-architecture-help\">Back to the legacy conundrum. How can event-driven architecture help?<\/h2>\n\n<p>You can now use messaging patterns like Publish-Subscribe to evolve your system. The book Enterprise Integration Patterns is a fantastic read that covers over a hundred messaging patterns you can use to solve everyday problems using asynchrony.<\/p>\n\n<h3 id=\"step-1-add-visibility-to-your-monolith\">Step 1: Add Visibility to Your Monolith<\/h3>\n\n<p>Instrumenting your monolith with events can help for a variety of reasons. First and foremost, it adds visibility inside your monolith.<\/p>\n\n<p>You\u2019ll first need to analyze your monolith code to find the lines that complete important actions. Now you can publish those actions as events. Repeat this process until you\u2019ve captured all the important actions as events your monolith is performing. Adding the code to publish an event inside your monolith is less intrusive than attempting to write a brand new feature inside it. And doing this is simple, especially if you\u2019re using an available library like NServiceBus or MassTransit.<\/p>\n\n<p>This strategy came in handy once when my team had to discover why a process was taking so long. After we had instrumented the legacy code with events, we had a subscriber module that received all these events. Using these events, we knew how long each of these critical business processes took to complete. We were able to identify the part that took too long. It turned out that an RPC call to a legacy service, whose response value was stored in the 72nd column in the database table, wasn\u2019t even necessary. After we had removed the offending line of code, the process was 30 times faster. Would we have found this without instrumenting? Eventually, after a few gray hairs and a whole lot of caffeine, yes. However, instrumenting with events provided visibility into a process that was opaque from the dawn of its creation, which turned out to be quite valuable in gathering other insights.<\/p>\n\n<p><img src=\"\/images\/posts\/2016-05-25-big-ball-of-mud\/InstrumentingWithEvents-1.jpg\" alt=\"Instrumenting with events\" \/><\/p>\n\n<h3 id=\"step-2-add-your-new-feature-on-the-outside\">Step 2: Add Your New Feature on the Outside.<\/h3>\n\n<p>Create your feature as a new service that subscribes to the event published by the monolith. When this service receives the event, take the relevant action that needs to occur. This service could also end up publishing an event for processing other downstream business processes.<\/p>\n\n<h2 id=\"the-return-of-the-natural-order\">The Return of the Natural Order<\/h2>\n\n<p>The good news is that you\u2019ve now completely decoupled your new service from the existing monolith. Even better, you can be assured that this new feature is not to going to break other parts of your monolith. You\u2019ve managed to isolate it.<\/p>\n\n<p>Because the feature is on the outside, it doesn\u2019t fall victim to the old constraints of your monolith. Your service could be written using the latest C# language version making use of the Elvis operator, etc. You can deploy this service without having to stop the monolith service, and now you have all the freedom in the world to write unit tests and integration tests. That land with rainbow unicorns might still be around the corner after all!<\/p>\n\n<p>Because you\u2019re on the outside of the monolith, your database technology constraints also disappear. You\u2019re now free to select the database technology of your choice to build this feature.<\/p>\n\n<p>You may not always need a relational database. What you need might be better accomplished with a graph database or a NoSQL database driven by the requirements of your feature.<\/p>\n\n<h2 id=\"strangler-pattern\">Strangler Pattern<\/h2>\n\n<p>You can use events to build new features on the outside, but how can you make this monolith obsolete? Again, the answer is with events. You could use different events whose only goal is to start slowly funneling the relevant data from your monolith into your new parts of the system, also written on the outside. You can deploy this new module to production. Since the goal of this module is to gather the needed data from your monolith slowly, running it side by side with your monolith shouldn\u2019t be a problem. Once you\u2019ve shoveled enough data from the monolith database to different storages, you can activate your new feature and remove those redundant parts of the code. Granted, this is a little more intrusive, but you still control the risks.<\/p>\n\n<p>Martin Fowler talks about a pattern called the Strangler Pattern, where slowly but steadily the monolith starts to lose its relevance and eventually becomes dead.<\/p>\n\n<p>When you\u2019ve managed to suck enough of the data from the legacy system using these events and funnel them through new smaller services that can have separate databases living on the outside, you\u2019re on target. You can kill your monolith, as does the strangler vine referred to in Martin\u2019s article. With enough time, the monolith might become completely obsolete. That\u2019s how you destroy the Death Star. That\u2019s how you bring balance to the Force.<\/p>\n\n<h2 id=\"so-whats-the-catch\">So what\u2019s the catch?<\/h2>\n\n<p>Since this potentially involves a lot of little services doing their thing based on the single responsibility principle, you could end up with a lot of services. These services will be communicating with other services using messages. It becomes extremely important to audit these messages to have a better handle on what\u2019s going on during debugging. Invest some time in finding the appropriate tools to help you trace these messages. Visualize the flow of messages to get a better understanding of your system from the messaging vantage point to see what works best for you.<\/p>\n\n<h2 id=\"in-summary\">In Summary\u2026<\/h2>\n\n<p>Use event-driven architecture style to your advantage when dealing with legacy systems to add visibility to your monolith. Use messaging patterns like publish\/subscribe to build new features outside of your monolith. Make sure to evolve your monolith into newer, smaller services, using events from the monolith, to make the monolith lose its relevance.<\/p>\n\n<p>And finally, stay on target. Destroy your Death Star.<\/p>\n\n<h2 id=\"related-reads\">Related Reads:<\/h2>\n\n<p><a href=\"https:\/\/www.industriallogic.com\/blog\/rewrites-hazardous\/\">Hazards And Safeguards for Software Rewrites<\/a><\/p>\n\n<p><a href=\"https:\/\/www.amazon.com\/Enterprise-Integration-Patterns-Designing-Addison-Wesley-ebook\/dp\/B007MQLL4E\/ref=dp_kinw_strp_1\">Enterprise Integration Patterns<\/a><\/p>\n\n<p><a href=\"https:\/\/www.martinfowler.com\/bliki\/StranglerApplication.html\">Strangler Pattern<\/a><\/p>\n","pubDate":"Wed, 25 May 2016 00:00:00 +0000","link":"https:\/\/indu.dev\/event-driven%20architecture\/2016\/05\/25\/break-that-big-ball-of-mud.html","guid":"https:\/\/indu.dev\/event-driven%20architecture\/2016\/05\/25\/break-that-big-ball-of-mud.html","category":["Event-driven","architecture,","Messaging","Event-driven architecture"]},{"title":"Don't get zapped! Protect your software","description":"<p><em>This article was originally published on the <a href=\"https:\/\/particular.net\/blog\/protect-your-software-with-the-circuit-breaker-design-pattern\">Particular.net Blog<\/a>.<\/em><\/p>\n\n<p>Life as a software developer is definitely lived in the fast lane. After weeks and hours of cranking out the code to get the features developed, and after the builds and tests are green and QA stamps its seal of approval, the code is deployed to Production. And then the most dreaded thing happens, the deployed software fails in production in a bad sort of way. In a Murphy\u2019s law sort of way. As the saying goes, <strong>\u201cAnything that can go wrong, will go wrong\u201d<\/strong>. But, just what if the code we write took this sort of thing into consideration?<\/p>\n\n<p>So, how do we take a bad thing and turn it around into something good?<\/p>\n\n<h2 id=\"electronics-to-the-rescue\">Electronics to the rescue<\/h2>\n\n<p>I still remember the day when my brother and I had to change the fuse in our house due to a surge, granted I didn\u2019t know the gravity of the situation at the time, he\u2019s the one with the electrical savvy.  The fuse was completely burnt. But it saved our TV. In electrical engineering, fuses and circuit breakers were invented for exactly this sort of thing. An overload of power can cause serious damage, from ruining electrical equipment to even setting the house on fire! A <a href=\"http:\/\/en.wikipedia.org\/wiki\/Fuse_(electrical)\">fuse<\/a> contains a small filament of wire that will melt during an electrical overload, similar to a light bulb burning out, stopping the dangerous flow of current and keeping other electrical equipment and the house safe.<\/p>\n\n<p>Fuses evolved into <a href=\"http:\/\/en.wikipedia.org\/wiki\/Circuit_breaker\">circuit breakers<\/a>, which commonly use an electromagnet to break the circuit instead of burning it up, allowing a circuit breaker to be reset and used over and over. However, the basic premise is the same. It detects the over usage, then fails fast, without destroying everything else.<\/p>\n\n<p>Thinking back about it, that\u2019s a pretty powerful concept. By actually killing the component (the fuse was literally dead), you can save serious damage. Our TV was alive thanks to the dead fuse after that surge episode. And rightfully, why can\u2019t the same be done in software? Something bad happens and you have this component in your software that will help you fail fast. Mimic that real life behavior and we have the Circuit Breaker design pattern.<\/p>\n\n<p>In dealing with distributed scenarios, some failures are transient, where quick successive retries will fix the problem. But there may be some scenarios where connectivity to a critical dependency is lost and may not be restored for a while. For example, an application may lose its connection to a persistent store hosted on the cloud. In these scenarios, by shutting down your service, you can prevent further damage to the rest of your system by avoiding bad processing of data, or even worse, data loss or cascading failures.<\/p>\n\n<p>By failing fast, it also becomes easier for Ops resources to monitor and respond. As far as they are concerned, services attempting in vain to re-establish connectivity may still appear healthy, hence not triggering alarms when in fact it should\u2019ve. Now if you cause the service to fail completely when appropriate, the warning lights go off and Ops is now aware of the problem and can respond right away.<\/p>\n\n<h2 id=\"the-circuit-breaker-design-pattern\">The Circuit Breaker Design Pattern<\/h2>\n\n<p>It\u2019s easy to create reusable infrastructure to enable the circuit breaker design pattern within your own systems. This is how it works:<\/p>\n\n<ol>\n  <li>\n    <p>Define a reusable <code class=\"language-plaintext highlighter-rouge\">CircuitBreaker<\/code> class with <code class=\"language-plaintext highlighter-rouge\">Trip<\/code> and <code class=\"language-plaintext highlighter-rouge\">Reset<\/code> methods, and provide it an action to call when the circuit breaker is tripped.<\/p>\n  <\/li>\n  <li>\n    <p>Use the <code class=\"language-plaintext highlighter-rouge\">CircuitBreaker<\/code> to monitor the dependency upon which your system depends. For every single failure, trip the circuit breaker, which sets it in an armed state. This is like the beginning of an electrical surge.<\/p>\n  <\/li>\n  <li>\n    <p>If a subsequent attempt succeeds within a specified time window (the current has subsided) then reset the breaker, and all is well.<\/p>\n  <\/li>\n  <li>\n    <p>If the circuit breaker is not reset within the specified time, and exceptions continue to occur (the current continues to rise to unsafe levels) then the breaker will invoke the action you\u2019ve provided. You can choose to fail fast (terminate the process) when the circuit breaker is tripped, or whatever other action you choose.<\/p>\n  <\/li>\n<\/ol>\n\n<h3 id=\"sample-usage\">Sample Usage<\/h3>\n\n<p>In this example, <code class=\"language-plaintext highlighter-rouge\">ExternalServiceAdapter<\/code> is a class that helps connects to some external dependency. There could be a web program that makes requests executing the <code class=\"language-plaintext highlighter-rouge\">DoStuff<\/code> operation constantly. While executing, if the <code class=\"language-plaintext highlighter-rouge\">GetConnection<\/code> method fails, it will trip the circuit breaker when an exception occurs. It resets the circuit breaker when the connection is re-established. But if the connection exceptions continue to occur, the circuit breaker will be tripped and the specified Trip action will be executed, which in this case will fail fast.<\/p>\n\n<div class=\"language-c# highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code><span class=\"k\">public<\/span> <span class=\"k\">class<\/span> <span class=\"nc\">ExternalServiceAdapter<\/span>\n<span class=\"p\">{<\/span>\n    <span class=\"k\">private<\/span> <span class=\"n\">CircuitBreaker<\/span> <span class=\"n\">circuitBreaker<\/span><span class=\"p\">;<\/span>\n\n    <span class=\"k\">public<\/span> <span class=\"nf\">ExternalServiceAdapter<\/span><span class=\"p\">()<\/span>\n    <span class=\"p\">{<\/span>\n        <span class=\"n\">circuitBreaker<\/span> <span class=\"p\">=<\/span> <span class=\"k\">new<\/span> <span class=\"nf\">CircuitBreaker<\/span><span class=\"p\">(<\/span><span class=\"s\">\"CheckConnection\"<\/span><span class=\"p\">,<\/span> <span class=\"cm\">\/*name of your circuit breaker *\/<\/span>\n            <span class=\"n\">exception<\/span> <span class=\"p\">=&gt;<\/span> <span class=\"cm\">\/* The action to take when the circuit breaker is tripped *\/<\/span>\n            <span class=\"p\">{<\/span>\n                <span class=\"n\">Console<\/span><span class=\"p\">.<\/span><span class=\"nf\">WriteLine<\/span><span class=\"p\">(<\/span><span class=\"s\">\"Circuit breaker tripped! Fail fast!\"<\/span><span class=\"p\">);<\/span>\n                <span class=\"c1\">\/\/ Terminate the process, skipping any pending try\/finally blocks or finalizers<\/span>\n                <span class=\"n\">Environment<\/span><span class=\"p\">.<\/span><span class=\"nf\">FailFast<\/span><span class=\"p\">(<\/span><span class=\"n\">exception<\/span><span class=\"p\">.<\/span><span class=\"n\">Message<\/span><span class=\"p\">);<\/span>\n            <span class=\"p\">},<\/span>\n        <span class=\"m\">3<\/span><span class=\"p\">,<\/span> <span class=\"cm\">\/* Max threshold before tripping the circuit breaker *\/<\/span>\n        <span class=\"n\">TimeSpan<\/span><span class=\"p\">.<\/span><span class=\"nf\">FromSeconds<\/span><span class=\"p\">(<\/span><span class=\"m\">2<\/span><span class=\"p\">));<\/span> <span class=\"cm\">\/* Time to wait between each try before attempting to trip the circuit breaker *\/<\/span>\n    <span class=\"p\">}<\/span>\n\n    <span class=\"k\">public<\/span> <span class=\"k\">void<\/span> <span class=\"nf\">DoStuff<\/span><span class=\"p\">()<\/span>\n    <span class=\"p\">{<\/span>\n        <span class=\"kt\">var<\/span> <span class=\"n\">externalService<\/span> <span class=\"p\">=<\/span> <span class=\"nf\">GetConnection<\/span><span class=\"p\">();<\/span>\n        <span class=\"n\">externalService<\/span><span class=\"p\">.<\/span><span class=\"nf\">DoStuff<\/span><span class=\"p\">();<\/span>\n    <span class=\"p\">}<\/span>\n\n    <span class=\"n\">ConnectionDependency<\/span> <span class=\"nf\">GetConnection<\/span><span class=\"p\">()<\/span>\n    <span class=\"p\">{<\/span>\n        <span class=\"k\">try<\/span>\n        <span class=\"p\">{<\/span>\n            <span class=\"kt\">var<\/span> <span class=\"n\">newConnection<\/span> <span class=\"p\">=<\/span> <span class=\"k\">new<\/span> <span class=\"nf\">ConnectionDependency<\/span><span class=\"p\">();<\/span>\n            <span class=\"n\">circuitBreaker<\/span><span class=\"p\">.<\/span><span class=\"nf\">Reset<\/span><span class=\"p\">();<\/span>\n            <span class=\"k\">return<\/span> <span class=\"n\">newConnection<\/span><span class=\"p\">;<\/span>\n        <span class=\"p\">}<\/span>\n        <span class=\"k\">catch<\/span> <span class=\"p\">(<\/span><span class=\"n\">Exception<\/span> <span class=\"n\">exception<\/span><span class=\"p\">)<\/span>\n        <span class=\"p\">{<\/span>\n            <span class=\"n\">circuitBreaker<\/span><span class=\"p\">.<\/span><span class=\"nf\">Trip<\/span><span class=\"p\">(<\/span><span class=\"n\">exception<\/span><span class=\"p\">);<\/span>\n            <span class=\"k\">throw<\/span><span class=\"p\">;<\/span>\n        <span class=\"p\">}<\/span>\n    <span class=\"p\">}<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div><\/div>\n\n<h3 id=\"simple-implementation-of-the-circuit-breaker-pattern\">Simple Implementation of the Circuit Breaker pattern.<\/h3>\n\n<div class=\"language-c# highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code><span class=\"k\">using<\/span> <span class=\"nn\">System<\/span><span class=\"p\">;<\/span>\n<span class=\"k\">using<\/span> <span class=\"nn\">System.Threading<\/span><span class=\"p\">;<\/span>\n\n<span class=\"k\">public<\/span> <span class=\"k\">class<\/span> <span class=\"nc\">CircuitBreaker<\/span> \n<span class=\"p\">{<\/span>\n    <span class=\"k\">public<\/span> <span class=\"nf\">CircuitBreaker<\/span><span class=\"p\">(<\/span><span class=\"kt\">string<\/span> <span class=\"n\">name<\/span><span class=\"p\">,<\/span> <span class=\"cm\">\/*name of the operation *\/<\/span>\n        <span class=\"n\">Action<\/span><span class=\"p\">&lt;<\/span><span class=\"n\">Exception<\/span><span class=\"p\">&gt;<\/span> <span class=\"n\">tripAction<\/span><span class=\"p\">,<\/span> <span class=\"cm\">\/* action to invoke when the circuit breaker is tripped *\/<\/span>\n        <span class=\"kt\">int<\/span> <span class=\"n\">maxTimesToRetry<\/span><span class=\"p\">,<\/span> <span class=\"cm\">\/* number of times to retry before tripping the circuit breaker *\/<\/span>\n        <span class=\"n\">TimeSpan<\/span> <span class=\"n\">delayBetweenRetries<\/span> <span class=\"cm\">\/* time to wait between each retry*\/<\/span><span class=\"p\">)<\/span> \n    <span class=\"p\">{<\/span>\n        <span class=\"k\">this<\/span><span class=\"p\">.<\/span><span class=\"n\">name<\/span> <span class=\"p\">=<\/span> <span class=\"n\">name<\/span><span class=\"p\">;<\/span>\n        <span class=\"k\">this<\/span><span class=\"p\">.<\/span><span class=\"n\">tripAction<\/span> <span class=\"p\">=<\/span> <span class=\"n\">tripAction<\/span><span class=\"p\">;<\/span>\n        <span class=\"k\">this<\/span><span class=\"p\">.<\/span><span class=\"n\">maxTimesToRetry<\/span> <span class=\"p\">=<\/span> <span class=\"n\">maxTimesToRetry<\/span><span class=\"p\">;<\/span>\n        <span class=\"k\">this<\/span><span class=\"p\">.<\/span><span class=\"n\">delayBetweenRetries<\/span> <span class=\"p\">=<\/span> <span class=\"n\">delayBetweenRetries<\/span><span class=\"p\">;<\/span>\n        \n        <span class=\"c1\">\/\/ Don't start the timer, just as yet. Start it when the user trips the circuit breaker. <\/span>\n        <span class=\"n\">timer<\/span> <span class=\"p\">=<\/span> <span class=\"k\">new<\/span> <span class=\"nf\">Timer<\/span><span class=\"p\">(<\/span><span class=\"n\">CircuitBreakerTripped<\/span><span class=\"p\">,<\/span> <span class=\"k\">null<\/span><span class=\"p\">,<\/span> <span class=\"n\">Timeout<\/span><span class=\"p\">.<\/span><span class=\"n\">Infinite<\/span><span class=\"p\">,<\/span> <span class=\"p\">(<\/span><span class=\"kt\">int<\/span><span class=\"p\">)<\/span><span class=\"n\">delayBetweenRetries<\/span><span class=\"p\">.<\/span><span class=\"n\">TotalMilliseconds<\/span><span class=\"p\">);<\/span>\n    <span class=\"p\">}<\/span>\n\n    <span class=\"k\">public<\/span> <span class=\"k\">void<\/span> <span class=\"nf\">Reset<\/span><span class=\"p\">()<\/span>\n    <span class=\"p\">{<\/span>\n        <span class=\"kt\">var<\/span> <span class=\"n\">oldValue<\/span> <span class=\"p\">=<\/span> <span class=\"n\">Interlocked<\/span><span class=\"p\">.<\/span><span class=\"nf\">Exchange<\/span><span class=\"p\">(<\/span><span class=\"k\">ref<\/span> <span class=\"n\">failureCount<\/span><span class=\"p\">,<\/span> <span class=\"m\">0<\/span><span class=\"p\">);<\/span>\n        <span class=\"n\">timer<\/span><span class=\"p\">.<\/span><span class=\"nf\">Change<\/span><span class=\"p\">(<\/span><span class=\"n\">Timeout<\/span><span class=\"p\">.<\/span><span class=\"n\">Infinite<\/span><span class=\"p\">,<\/span> <span class=\"n\">Timeout<\/span><span class=\"p\">.<\/span><span class=\"n\">Infinite<\/span><span class=\"p\">);<\/span>\n        <span class=\"n\">Console<\/span><span class=\"p\">.<\/span><span class=\"nf\">WriteLine<\/span><span class=\"p\">(<\/span><span class=\"s\">\"The circuit breaker for {0} is now disarmed\"<\/span><span class=\"p\">,<\/span> <span class=\"n\">name<\/span><span class=\"p\">);<\/span>\n\n    <span class=\"p\">}<\/span>\n\n    <span class=\"k\">public<\/span> <span class=\"k\">void<\/span> <span class=\"nf\">Trip<\/span><span class=\"p\">(<\/span><span class=\"n\">Exception<\/span> <span class=\"n\">ex<\/span><span class=\"p\">)<\/span>\n    <span class=\"p\">{<\/span>\n        <span class=\"n\">lastException<\/span> <span class=\"p\">=<\/span> <span class=\"n\">ex<\/span><span class=\"p\">;<\/span>\n        <span class=\"kt\">var<\/span> <span class=\"n\">newValue<\/span> <span class=\"p\">=<\/span> <span class=\"n\">Interlocked<\/span><span class=\"p\">.<\/span><span class=\"nf\">Increment<\/span><span class=\"p\">(<\/span><span class=\"k\">ref<\/span> <span class=\"n\">failureCount<\/span><span class=\"p\">);<\/span>\n\n        <span class=\"k\">if<\/span> <span class=\"p\">(<\/span><span class=\"n\">newValue<\/span> <span class=\"p\">==<\/span> <span class=\"m\">1<\/span><span class=\"p\">)<\/span>\n        <span class=\"p\">{<\/span>\n            <span class=\"c1\">\/\/ Start the retry timer. <\/span>\n            <span class=\"n\">timer<\/span><span class=\"p\">.<\/span><span class=\"nf\">Change<\/span><span class=\"p\">(<\/span><span class=\"n\">delayBetweenRetries<\/span><span class=\"p\">,<\/span> <span class=\"n\">TimeSpan<\/span><span class=\"p\">.<\/span><span class=\"nf\">FromMilliseconds<\/span><span class=\"p\">(-<\/span><span class=\"m\">1<\/span><span class=\"p\">));<\/span>\n            \n            <span class=\"c1\">\/\/ Log that the circuit breaker is triggered.<\/span>\n            <span class=\"n\">Console<\/span><span class=\"p\">.<\/span><span class=\"nf\">WriteLine<\/span><span class=\"p\">(<\/span><span class=\"s\">\"The circuit breaker for {0} is now in the armed state\"<\/span><span class=\"p\">,<\/span> <span class=\"n\">name<\/span><span class=\"p\">);<\/span>\n        <span class=\"p\">}<\/span>\n    <span class=\"p\">}<\/span>\n\n\t<span class=\"k\">void<\/span> <span class=\"nf\">CircuitBreakerTripped<\/span><span class=\"p\">(<\/span><span class=\"kt\">object<\/span> <span class=\"n\">state<\/span><span class=\"p\">)<\/span>\n    <span class=\"p\">{<\/span>\n        <span class=\"n\">Console<\/span><span class=\"p\">.<\/span><span class=\"nf\">WriteLine<\/span><span class=\"p\">(<\/span><span class=\"s\">\"Check to see if we need to trip the circuit breaker. Retry:{0}\"<\/span><span class=\"p\">,<\/span> <span class=\"n\">failureCount<\/span><span class=\"p\">);<\/span>\n        <span class=\"k\">if<\/span> <span class=\"p\">(<\/span><span class=\"n\">Interlocked<\/span><span class=\"p\">.<\/span><span class=\"nf\">Increment<\/span><span class=\"p\">(<\/span><span class=\"k\">ref<\/span> <span class=\"n\">failureCount<\/span><span class=\"p\">)<\/span> <span class=\"p\">&gt;<\/span> <span class=\"n\">maxTimesToRetry<\/span><span class=\"p\">)<\/span>\n        <span class=\"p\">{<\/span>\n            <span class=\"n\">Console<\/span><span class=\"p\">.<\/span><span class=\"nf\">WriteLine<\/span><span class=\"p\">(<\/span><span class=\"s\">\"The circuit breaker for {0} is now tripped. Calling specified action\"<\/span><span class=\"p\">,<\/span> <span class=\"n\">name<\/span><span class=\"p\">);<\/span>\n            <span class=\"nf\">tripAction<\/span><span class=\"p\">(<\/span><span class=\"n\">lastException<\/span><span class=\"p\">);<\/span>\n            <span class=\"k\">return<\/span><span class=\"p\">;<\/span>\n        <span class=\"p\">}<\/span>\n        <span class=\"n\">timer<\/span><span class=\"p\">.<\/span><span class=\"nf\">Change<\/span><span class=\"p\">(<\/span><span class=\"n\">delayBetweenRetries<\/span><span class=\"p\">,<\/span> <span class=\"n\">TimeSpan<\/span><span class=\"p\">.<\/span><span class=\"nf\">FromMilliseconds<\/span><span class=\"p\">(-<\/span><span class=\"m\">1<\/span><span class=\"p\">));<\/span>        \n    <span class=\"p\">}<\/span>\n\n    <span class=\"k\">readonly<\/span> <span class=\"kt\">string<\/span> <span class=\"n\">name<\/span><span class=\"p\">;<\/span>\n    <span class=\"k\">readonly<\/span> <span class=\"kt\">int<\/span> <span class=\"n\">maxTimesToRetry<\/span><span class=\"p\">;<\/span>\n    <span class=\"kt\">long<\/span> <span class=\"n\">failureCount<\/span><span class=\"p\">;<\/span>\n    <span class=\"k\">readonly<\/span> <span class=\"n\">Action<\/span><span class=\"p\">&lt;<\/span><span class=\"n\">Exception<\/span><span class=\"p\">&gt;<\/span> <span class=\"n\">tripAction<\/span><span class=\"p\">;<\/span>\n    <span class=\"n\">Exception<\/span> <span class=\"n\">lastException<\/span><span class=\"p\">;<\/span>\n    <span class=\"k\">readonly<\/span> <span class=\"n\">TimeSpan<\/span> <span class=\"n\">delayBetweenRetries<\/span><span class=\"p\">;<\/span>\n    <span class=\"k\">readonly<\/span> <span class=\"n\">Timer<\/span> <span class=\"n\">timer<\/span><span class=\"p\">;<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div><\/div>\n\n<h3 id=\"unit-tests-for-the-circuitbreaker\">Unit Tests for the CircuitBreaker<\/h3>\n\n<div class=\"language-c# highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code><span class=\"p\">[<\/span><span class=\"n\">TestFixture<\/span><span class=\"p\">]<\/span>\n<span class=\"k\">public<\/span> <span class=\"k\">class<\/span> <span class=\"nc\">CircuitBreakerTests<\/span>\n<span class=\"p\">{<\/span>\n    <span class=\"p\">[<\/span><span class=\"n\">Test<\/span><span class=\"p\">]<\/span>\n    <span class=\"k\">public<\/span> <span class=\"k\">void<\/span> <span class=\"nf\">When_the_circuit_breaker_is_tripped_the_trip_action_is_called_after_reaching_max_threshold<\/span><span class=\"p\">()<\/span>\n    <span class=\"p\">{<\/span>\n        <span class=\"kt\">bool<\/span> <span class=\"n\">circuitBreakerTripActionCalled<\/span> <span class=\"p\">=<\/span> <span class=\"k\">false<\/span><span class=\"p\">;<\/span>\n        <span class=\"kt\">var<\/span> <span class=\"n\">connectionException<\/span> <span class=\"p\">=<\/span> <span class=\"k\">new<\/span> <span class=\"nf\">Exception<\/span><span class=\"p\">(<\/span><span class=\"s\">\"Something bad happened.\"<\/span><span class=\"p\">);<\/span>\n\n        <span class=\"kt\">var<\/span>  <span class=\"n\">circuitBreaker<\/span> <span class=\"p\">=<\/span> <span class=\"k\">new<\/span> <span class=\"nf\">CircuitBreaker<\/span><span class=\"p\">(<\/span><span class=\"s\">\"CheckServiceConnection\"<\/span><span class=\"p\">,<\/span> <span class=\"n\">exception<\/span> <span class=\"p\">=&gt;<\/span>\n        <span class=\"p\">{<\/span>\n            <span class=\"n\">Console<\/span><span class=\"p\">.<\/span><span class=\"nf\">WriteLine<\/span><span class=\"p\">(<\/span><span class=\"s\">\"Circuit breaker tripped - fail fast\"<\/span><span class=\"p\">);<\/span>\n            <span class=\"n\">circuitBreakerTripActionCalled<\/span> <span class=\"p\">=<\/span> <span class=\"k\">true<\/span><span class=\"p\">;<\/span>\n            <span class=\"c1\">\/\/ You would normally fail fast here in the action to faciliate the process shutdown by calling:<\/span>\n            <span class=\"c1\">\/\/ Environment.FailFast(connectionException.Message);<\/span>\n        <span class=\"p\">},<\/span> <span class=\"m\">3<\/span><span class=\"p\">,<\/span> <span class=\"n\">TimeSpan<\/span><span class=\"p\">.<\/span><span class=\"nf\">FromSeconds<\/span><span class=\"p\">(<\/span><span class=\"m\">1<\/span><span class=\"p\">));<\/span>\n\n        <span class=\"n\">circuitBreaker<\/span><span class=\"p\">.<\/span><span class=\"nf\">Trip<\/span><span class=\"p\">(<\/span><span class=\"n\">connectionException<\/span><span class=\"p\">);<\/span>\n        <span class=\"n\">System<\/span><span class=\"p\">.<\/span><span class=\"n\">Threading<\/span><span class=\"p\">.<\/span><span class=\"n\">Thread<\/span><span class=\"p\">.<\/span><span class=\"nf\">Sleep<\/span><span class=\"p\">(<\/span><span class=\"m\">5000<\/span><span class=\"p\">);<\/span> \n        <span class=\"n\">Assert<\/span><span class=\"p\">.<\/span><span class=\"nf\">IsTrue<\/span><span class=\"p\">(<\/span><span class=\"n\">circuitBreakerTripActionCalled<\/span><span class=\"p\">);<\/span> \n    <span class=\"p\">}<\/span>\n\n    <span class=\"p\">[<\/span><span class=\"n\">Test<\/span><span class=\"p\">]<\/span>\n    <span class=\"k\">public<\/span> <span class=\"k\">void<\/span> <span class=\"nf\">When_the_circuit_breaker_is_reset_the_trip_action_is_not_called<\/span><span class=\"p\">()<\/span>\n    <span class=\"p\">{<\/span>\n        <span class=\"kt\">bool<\/span> <span class=\"n\">circuitBreakerTripActionCalled<\/span> <span class=\"p\">=<\/span> <span class=\"k\">false<\/span><span class=\"p\">;<\/span>\n        <span class=\"kt\">var<\/span> <span class=\"n\">connectionException<\/span> <span class=\"p\">=<\/span> <span class=\"k\">new<\/span> <span class=\"nf\">Exception<\/span><span class=\"p\">(<\/span><span class=\"s\">\"Something bad happened.\"<\/span><span class=\"p\">);<\/span>\n\n        <span class=\"kt\">var<\/span> <span class=\"n\">circuitBreaker<\/span> <span class=\"p\">=<\/span> <span class=\"k\">new<\/span> <span class=\"nf\">CircuitBreaker<\/span><span class=\"p\">(<\/span><span class=\"s\">\"CheckServiceConnection\"<\/span><span class=\"p\">,<\/span> <span class=\"n\">exception<\/span> <span class=\"p\">=&gt;<\/span>\n        <span class=\"p\">{<\/span>\n            <span class=\"n\">Console<\/span><span class=\"p\">.<\/span><span class=\"nf\">WriteLine<\/span><span class=\"p\">(<\/span><span class=\"s\">\"Circuit breaker tripped - fail fast\"<\/span><span class=\"p\">);<\/span>\n            <span class=\"n\">circuitBreakerTripActionCalled<\/span> <span class=\"p\">=<\/span> <span class=\"k\">true<\/span><span class=\"p\">;<\/span>\n            <span class=\"c1\">\/\/ You would normally fail fast here in the action to faciliate the process shutdown by calling:<\/span>\n            <span class=\"c1\">\/\/ Environment.FailFast(connectionException.Message);<\/span>\n        <span class=\"p\">},<\/span> <span class=\"m\">3<\/span><span class=\"p\">,<\/span> <span class=\"n\">TimeSpan<\/span><span class=\"p\">.<\/span><span class=\"nf\">FromSeconds<\/span><span class=\"p\">(<\/span><span class=\"m\">2<\/span><span class=\"p\">));<\/span>\n\n        <span class=\"n\">circuitBreaker<\/span><span class=\"p\">.<\/span><span class=\"nf\">Trip<\/span><span class=\"p\">(<\/span><span class=\"n\">connectionException<\/span><span class=\"p\">);<\/span>\n        <span class=\"n\">System<\/span><span class=\"p\">.<\/span><span class=\"n\">Threading<\/span><span class=\"p\">.<\/span><span class=\"n\">Thread<\/span><span class=\"p\">.<\/span><span class=\"nf\">Sleep<\/span><span class=\"p\">(<\/span><span class=\"m\">1000<\/span><span class=\"p\">);<\/span> \n        <span class=\"n\">circuitBreaker<\/span><span class=\"p\">.<\/span><span class=\"nf\">Reset<\/span><span class=\"p\">();<\/span>\n        <span class=\"n\">Assert<\/span><span class=\"p\">.<\/span><span class=\"nf\">False<\/span><span class=\"p\">(<\/span><span class=\"n\">circuitBreakerTripActionCalled<\/span><span class=\"p\">);<\/span>\n    <span class=\"p\">}<\/span>\n<span class=\"p\">}<\/span>\n<\/code><\/pre><\/div><\/div>\n\n<p>The code example above uses Console.WriteLine. Replace it with your favorite logger.<\/p>\n\n<h2 id=\"closing-thoughts\">Closing Thoughts<\/h2>\n\n<p>Circuit breakers are an essential part of the modern world, and arguably one of the most important safety devices ever invented. There\u2019s always a good reason behind a blown fuse or a tripped circuit breaker.<\/p>\n\n<p>Monitor your critical resources, fail fast when they don\u2019t respond. Facilitate your Ops team to take corrective actions.<\/p>\n\n<p>If you\u2019re further interested in these types of patterns, Michael.T.Nygard\u2019s <a href=\"http:\/\/www.amazon.com\/Release-It-Production-Ready-Pragmatic-Programmers\/dp\/0978739213\">Release It<\/a> is a fantastic read.<\/p>\n\n<p>Be safe. Don\u2019t get zapped.<\/p>\n","pubDate":"Mon, 18 May 2015 00:00:00 +0000","link":"https:\/\/indu.dev\/design%20patterns\/2015\/05\/18\/circuit-breaker-pattern.html","guid":"https:\/\/indu.dev\/design%20patterns\/2015\/05\/18\/circuit-breaker-pattern.html","category":["Design","Patterns","Design Patterns"]},{"title":"Why can't my machines talk nicely!? - Troubleshooting MSMQ and DTC","description":"<p>You are already in the land of messaging, and have built your endpoints that use MSMQ as the transport of choice. Now comes the fun part, deployment! You deploy your endpoints to your servers and give it a try. The client endpoint is happy to send messages to the server  endpoint and crickets on your server, or you get lovely transaction errors! And yes the machines are not playing nice with each other!<\/p>\n\n<p>Here are some troubleshooting tips:<\/p>\n\n<h2 id=\"can-your-machines-ping-each-other\">Can your machines ping each other?<\/h2>\n<p>Issue a ping from either machine to make sure that the machines can talk nice. Check by both IP address and name to make sure that name resolution works as expected.<\/p>\n\n<h2 id=\"is-your-machine-name-too-long\">Is your machine name too long?<\/h2>\n<p>For MSMQ to be able to send messages properly, <a href=\"http:\/\/geekswithblogs.net\/Plumbersmate\/archive\/2012\/02\/03\/make-sure-computer-names-are-15-characters-or-less-fro.aspx\">the machine names must be 15 characters or less<\/a>.<\/p>\n\n<h2 id=\"do-you-have-windows-firewall-turned-on\">Do you have Windows firewall turned on?<\/h2>\n<p>If your firewall is turned on, ensure that Message Queueing and Distribution Transaction Coordinator are added to the list of Programs that are allowed in the firewall.<\/p>\n\n<h2 id=\"are-the-ports-configured-correctly\">Are the ports configured correctly?<\/h2>\n<p>To verify: open ComponentServices. Expand Computers &amp; right click on MyComputer \u2192 Properties. Click on Default Protocols tab. Click on Connection Oriented TCP\/IP and then Properties and verify if the 5000-6000 port range is open. If not add the port range.<\/p>\n\n<p><img src=\"\/images\/posts\/2013-06-13-msmq-dtc\/ports.png\" alt=\"Open ports\" \/><\/p>\n\n<h2 id=\"is-dtc-configured-properly\">Is DTC configured properly?<\/h2>\n<p>To verify: In Component Services, expand My Computer and expand Distribution Transaction Coordinator. Check the properties on Local DTC to see if its configured like below:<\/p>\n\n<p><img src=\"\/images\/posts\/2013-06-13-msmq-dtc\/localDtcProperties.png\" alt=\"DTC Configuration\" \/><\/p>\n\n<h2 id=\"have-you-cloned-your-vms\">Have you cloned your VMs?<\/h2>\n<p>VMs are great. But if you have copied your VMs off of some image, then you need to know that there are some registry keys that cannot be the same for MSMQ to work properly.  For more details <a href=\"http:\/\/www.wadewegner.com\/2007\/08\/warning-the-cid-values-for-both-test-machines-are-the-same\/\">read this post<\/a>.<\/p>\n\n<p>Re-install DTC by following these steps:\nGo to an administrative command prompt and type: msdtc -uninstall\nGo to HKEY_CLASSES_ROOT\/CID and delete any keys if they are present\nReboot the VM\nGoto an administrative command prompt and type: \n                msdtc -install\n                net start msdtc\nIf you had previously enabled Distribution Transaction Coordinator in firewall settings, you\u2019ll need to add it again to the allowed programs list. \nGenerate a new QMId by following these steps:\nMSMQ uses a unique Id for every machine. In order to generate a new identifier, follow these steps:\nStop MSMQ Service\nGoto HKLM\\Software\\Microsoft\\MSMQ\\Parameters\\MachineCache and delete the REG_BINARY QMId\nGoto HKLM\\Software\\Microsoft\\MSMQ\\Parameters, add a DWORD called SysPrep and set it to 1\nRestart MSMQ<\/p>\n\n<h2 id=\"what-does-dtcping-tell-you\">What does DTCPing tell you?<\/h2>\n<p>DTCPing is a great tool that can help troubleshoot MSDTC woes between servers. <a href=\"https:\/\/www.microsoft.com\/en-us\/download\/details.aspx?id=2868\">Download DTCPing<\/a> and run DTCPing on both the server and the client and start the test.<\/p>\n\n<p>If you receive a Access is Denied error on DTCPing:  make sure you add the following registry entries and try again.\nAdd a key called RPC under HKEY_LOCAL_MACHINE\\ SOFTWARE\\Policies\\ Microsoft\\Windows NT\nAdd a DWORD called RestrictRemoteClients under RPC and set the value to 0 \nIf you received a duplicate CID warning, follow the steps outlined above for cloning the VMs. Essentially re-install DTC and generate a new QMId.<\/p>\n\n<p>For more information on the read: <a href=\"https:\/\/blogs.msdn.microsoft.com\/distributedservices\/2008\/11\/12\/troubleshooting-msdtc-issues-with-the-dtcping-tool\/\">Troubleshooting MSDTC issues with the DTCPing tool<\/a>.<\/p>\n\n<h2 id=\"using-sqlserver-and-still-having-problems\">Using SQLServer and still having problems?<\/h2>\n<p>If running DTCPing on both machines produces the right results and you are still having trouble with transactions on the SQL Server, then try the DTCTester tool. The DTCTester establishes a connection to the SQL Server and creates a temporary table and enlists the connection in a transaction and does an insert on the temporary table and commits the transaction. It selects to read the inserted value and finally closes the connection.<\/p>\n\n<p>For more details: <a href=\"https:\/\/www.microsoft.com\/en-us\/download\/details.aspx?id=30746\">Download DTCTester<\/a>.<\/p>\n\n<p>Hope these steps help in resolving your MSMQ, DTC, SQLServer woes!<\/p>\n\n","pubDate":"Thu, 13 Jun 2013 00:00:00 +0000","link":"https:\/\/indu.dev\/messaging\/2013\/06\/13\/troubleshooting-msmq-dtc.html","guid":"https:\/\/indu.dev\/messaging\/2013\/06\/13\/troubleshooting-msmq-dtc.html","category":["MSMQ,","DTC","Messaging"]},{"title":"Be explicit - Commands and Events","description":"<p>In order for the systems we build to be reliable and scalable,  it usually involves queueing and messaging.  Having removed temporal coupling out of the equation, (Blocking synchronous RPC has its place, but just not everywhere) messaging is an important part of the puzzle.<\/p>\n\n<ul>\n  <li>How we classify these messages become important<\/li>\n  <li>How we communicate between \u201cthings\u201d via these messages become important (using the right messaging pattern, ie. request-response, publish-subscribe, and the other 150 messaging patterns described in Gregor A Hophe and Bobby Woolf\u2019s Enterprise Integration Patterns book)<\/li>\n  <li>And not but least, naming these messages more important.<\/li>\n<\/ul>\n\n<h2 id=\"types-of-messages\">Types of Messages:<\/h2>\n<p>If we can classify messages, then we could classify them into Commands &amp; Events.<\/p>\n\n<h3 id=\"there-are-those-that-fail\">There are those that fail:<\/h3>\n<p>Commands are messages that can be sent to one specific logical endpoint to fulfill a certain request.  The endpoint that handles this message has the ultimate authority to reject or fulfill this request. Therefore it makes sense to name these messages in the active tense, for Example, PlaceOrder<\/p>\n\n<h3 id=\"e--mc2\">E = mc2:<\/h3>\n<p>And then there are those messages that convey a certain something happened that is of significant importance to the business. And are published as a statement of fact. These messages are classified as events. Since these messages convey a certain something happened, it is named in the passive past tense, i.e. OrderAccepted.  Since these have a significant importance, there are often multiple parties interested in when this happens. And since multiple parties are acting on this, as soon as it is broadcasted, they cannot be revoked. When you publish the OrderBilled, Shipping is going to ship the items to the customer. There is no oops, no, Order did not get billed without bad consequences.<\/p>\n\n<h2 id=\"tiny-business-of-naming\">Tiny business of naming<\/h2>\n<p>When naming these messages, i.e these specific commands and events, let\u2019s for one brief moment, throw away all technical details out of the window and focus entirely on the business. Does business understand CreatePdfDocument? Or IPdfDocumentCreated? If the whole purpose of writing software is so that it adds business value, and the software to \u201calign\u201d with the business,  then the first step is to use the domain language, language understood by the business rather than use the language we techy geeks love. My seven year old has the right idea, geeks are cool people that solve problems and he kindly gave me a huge compliment. However domain experts in the business know the business and its needs. Techy people try to understand these requirements and come up with their own language and design to convey the same. Ummm, just why is it that we need an extra translation layer? Why not call a spade a spade? Why not describe our system in the language of the domain. Why is OrderPlaced, getting morphed to some type of IPdfDocumentSent? The blue book (aka Eric Evans\u2019 Domain Driven Design) talks about the importance of the Ubiquitous language.<\/p>\n\n<p>The patterns of messaging and messages that are classified correctly and named right can easily fit into the business of software development and IT alignment!<\/p>\n\n<h2 id=\"example\">Example<\/h2>\n<p>Let\u2019s say that Orders can be placed via web, mail or phone.\nPreferred customers get a certain discount\nCustomers are made preferred, if their sales volume exceeds a certain limit.<\/p>\n\n<p>An extremely over simplified solution :\nOrder system\u2019s endpoint receives the PlaceOrder command (website exposed to customer, internal intranet site that customer service reps use will send the PlaceOrder command) and once it succeeds based on some criteria, publishes the event, \u201cOrderAccepted\u201d<\/p>\n\n<p>Let\u2019s say the CRM service, listens to the OrderAccepted events. Knows which customer placed what order, and based on the order amount, can publish the CustomerStatusUpgraded event.<\/p>\n\n<p>The Order service also listens to CustomerStatusUpgraded and CustomerStatusDowngraded events and based on that sets the discount appropriately.<\/p>\n\n<p>In this model, the order service does not send commands to the CRM to GetCustomerStatus and waits for a response to compute the discount before it can publish the OrderAccepted event. A simple twist of how  pub\/sub is used here by making the order service listen to the status changed event,   removed the need for request\/response and made these two parts of the system autonomous. If or when the event is published, the ordering service will upgrade its discount percent. When orders are placed, it will always use what it has to compute the discount.<\/p>\n\n<p>And a bigger benefit, when business says, \u201cWhen a customer\u2019s status is upgraded, they get a complimentary fee waived one year Hertz Gold membership\u201d with all that jazz of 3rd party integration with Hertz, all is needed is to add a an endpoint that subscribes to the event and to fulfill business\u2019 request. And the biggest benefit,  these new subscribers can be added without having to modify existing working system. And can be upgraded without having to impact other pieces of the puzzle as well.<\/p>\n","pubDate":"Thu, 14 Feb 2013 00:00:00 +0000","link":"https:\/\/indu.dev\/ddd,%20messaging\/2013\/02\/14\/be-explicit-commands-events.html","guid":"https:\/\/indu.dev\/ddd,%20messaging\/2013\/02\/14\/be-explicit-commands-events.html","category":["DDD,","Event-Driven","Architecture","DDD, Messaging"]},{"title":"Agile Iceland 2012 - Screw it, Let's do it.","description":"<p>I totally stole Richard Branson\u2019s line for the captivating title. While Richard Branson was talking about something entirely different on his tweet, it just fit so right on with my zen experience yesterday at the Open Space forum at the Agile Island 2012 conference at Reykjavik that I shamelessly stole it.<\/p>\n\n<p>A day packed with goodness.  Jurgen Appelo\u2019s keynote started the day making you think about enhancing the quality of work life and how getting away from a more traditional style of management into something that allows experimentation, and a more collaborative style can effectively affect the ordinary unhappy Melly\u2019s who hate their job but do it anyway because they have to, into happy and productive Melly\u2019s. Udi Dahan\u2019s talk on balancing architecture and agile practices was keeping it real as always and how being \u201cAgile\u201d and architecture are both important and they help alleviate completely different risks, both important to address. While being agile, helps to focus on mitigating the risk of, \u201care we developing the right thing?\u201d architecture focuses on building the software right with emphasis to reliability.  Also, it\u2019s not a good thing if you can\u2019t scale your system and you end up having to rewrite it! And other interesting talks like Culture Hacking by Petur Orri Saemundsen and Daoi Ingolfsson of Sprettur, and a whole lot more.<\/p>\n\n<h2 id=\"eye-openers\">Eye Openers<\/h2>\n<p>70 % of the projects fail.\nYou need to balance good architecture and agile practices. You need both, it\u2019s not one or the other as each of them are fundamentally managing a different risk.\nManagement is often the biggest hindrance to the adoption of being agile (aka collaborative) style of software development.\nJurgen\u2019s statement that Management being the top 4 reasons for biggest hindrance to Agile \/ collaborative style of development adoption in an organization, brought up this burning question in my head:  \u201cSo then, how do we convince them!?\u201d  If Management is the culprit then how can Developer(s) help change it? Another question that was brought up along the same lines was how does Culture Hacking come into play into the culture of the organization? The discussion was great, and what I learned even more inspiring.<\/p>\n\n<h2 id=\"two-stories--vastly-different--same-results---better-practices-better-ways\">Two stories.  Vastly different.  Same results - Better practices, better ways<\/h2>\n\n<h3 id=\"story-1\">Story 1:<\/h3>\n<p>A senior member in the team was able to get buy in from the management to try the new Agile \/ Collaborative methodology in just one project as an experiment and let the team to implement the process that the team thought best.  After management consented, they team experimented. The team was now no longer just theorizing, but actually experimented this, and was able to show effective results. Needless to say, it was adopted and it was the thing.<\/p>\n\n<h3 id=\"story-2\">Story 2:<\/h3>\n<p>The development and the testing team had great collaboration already. One of the developer(s) had brought up lean thinking and lean methodology as discussion to the group. The entire team really loved the idea. To the point where they started a book club and read about Lean Development. The thing is, \u201cManagement\u201d was invited to their book club meetings but they were a no show. But the group continued with their book club and put practices into place. The D-Day came, and the team informed the management that they are going to work pronto this way, because it works and if they have any questions, they should read the book on lean development first.  Screw it, Let\u2019s do it \u2013 In this case, a simple and yet an effective culture hack was born turning the organization more effective.<\/p>\n\n<h2 id=\"to-improve-is-to-change-to-be-perfect-is-to-change-often\">\u201cTo improve is to change, to be perfect is to change often\u201d<\/h2>\n<p>Regardless of which story you draw your inspiration from, the hope is that, it is possible. Experimentation is a good thing.\nWhen management realizes that having a whole lot of unhappy Mellys\u2019, who just show up for their jobs to pay their mortgages is terrible and the more employees are involved, then good things happen!<\/p>\n\n<h2 id=\"my-takeaways\">My Takeaways:<\/h2>\n<p>The biggest takeaway of the open space discussion was Culture is bigger than management.\nManagement\u2019s job is to help identify the vision and help facilitate the organization reach the goals and empower its people to achieve this effectively.\nThe more open, management is to experiments and collaboration, awesome things are waiting around the horizon!\nNow onto the equally exciting travel part of the vacation!<\/p>\n","pubDate":"Thu, 29 Nov 2012 00:00:00 +0000","link":"https:\/\/indu.dev\/agile\/2012\/11\/29\/agile-iceland-2012.html","guid":"https:\/\/indu.dev\/agile\/2012\/11\/29\/agile-iceland-2012.html","category":["Agile","Agile"]},{"title":"Temporal Coupling - Why does it matter?","description":"<p>Writing good software is a thing of beauty and a thing of beauty is a joy forever.\nWhat constitutes good software? Code that looks good? Three lines of code as opposed to lines and lines of code?<\/p>\n\n<p>There was a time, I was blissfully unaware of a fundamental coupling in code called, \u201cTemporal Coupling\u201d. In my mind, being Service Oriented was JBOWS. Just a bunch of WCF\/Web services, that call each other to fulfill something. These services were grouped into Capability Services, Activity Services, and Entity Services. In my mind,  Services equaled WCF. And yes, though WCF offers a whole bunch of bindings. I had stuck to using Tcp. I was doing full fledged synchronous blocking request response without being aware of consequences.<\/p>\n\n<p>I was designing a thing of beauty. The software was going to be being oriented into these blocks of services!  Calling these services was simple too! As MSDN samples show, it was just  three simple steps:<\/p>\n\n<div class=\"language-c# highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code><span class=\"c1\">\/\/Step 1: Create an instance of the WCF proxy.<\/span>\n<span class=\"n\">CalculatorClient<\/span> <span class=\"n\">client<\/span> <span class=\"p\">=<\/span> <span class=\"k\">new<\/span> <span class=\"nf\">CalculatorClient<\/span><span class=\"p\">();<\/span>\n<span class=\"c1\">\/\/ Step 2: Call the service operations. Call the Add service operation.<\/span>\n<span class=\"kt\">double<\/span> <span class=\"n\">value1<\/span> <span class=\"p\">=<\/span> <span class=\"m\">100.00D<\/span><span class=\"p\">;<\/span>\n<span class=\"kt\">double<\/span> <span class=\"n\">value2<\/span> <span class=\"p\">=<\/span> <span class=\"m\">15.99D<\/span><span class=\"p\">;<\/span>\n<span class=\"kt\">double<\/span> <span class=\"n\">result<\/span> <span class=\"p\">=<\/span> <span class=\"n\">client<\/span><span class=\"p\">.<\/span><span class=\"nf\">Add<\/span><span class=\"p\">(<\/span><span class=\"n\">value1<\/span><span class=\"p\">,<\/span> <span class=\"n\">value2<\/span><span class=\"p\">);<\/span>\n<span class=\"c1\">\/\/Step 3: Closing the client gracefully closes the connection and cleans up resources.<\/span>\n<span class=\"n\">client<\/span><span class=\"p\">.<\/span><span class=\"nf\">Close<\/span><span class=\"p\">();<\/span>\n<\/code><\/pre><\/div><\/div>\n\n<p>The first problem I ran into was timeout exceptions, and the problems didn\u2019t end there. Needless to say, it was far from beautiful and the devil is always in the details. Those three lines of code that looked beautiful hid a whole lot of things that I needed to make explicit in my design.<\/p>\n\n<h2 id=\"what-if\">What If?<\/h2>\n\n<p>What if the service was not up?\nWhat if the client called the method and the service operation is executing and the operation timed out on the client side, but the operation completed on the server side?\nWhat if this was a web service in a land far far away?\nDo I need to retry the failed operation? \nCan I safely retry the operation?<\/p>\n\n<p>My questions led to the first answers, led to the fact that these so called services were temporally coupled. What does that mean? Well, it means that one service cannot complete its function if the other service is not around to perform what it\u2019s asked to do. So, if Service A calls Service B, and Service B is down, well good luck to the million dollar order that is trying to be placed into the system. No Bueno!<\/p>\n\n<p>So, this whole idea of the activity service calling a capability service calling another service tumbled quickly into the abyss. More thought went into, how can these services be on their own without being dependent on each other to fulfill these capabilities and a design pattern that has been around forever emerged into sight. Event Driven Architecture and the Publish-Subscribe pattern.<\/p>\n\n<h2 id=\"enter-a-different-way-of-thinking\">Enter a different way of thinking<\/h2>\n<p>Well the real world works on events. A low battery event on your computer makes you react and plug in the power source when the event occurs. You react to events and perform certain actions when they occur. And yet why is that we write code on a command-control basis? Our programs mostly tend to, call method, perform action, retrieve more information, do this do that as if nothing else can go around these actions.<\/p>\n\n<p>What if we turned that around and made software react to events? An order placed event. The billing system can react to it and charge the customer and publish CustomerCharged event. The shipping system can then react to this event and ship the item. There is no service calling service, instead a loosely coupled model where services can be truly autonomous emerges.<\/p>\n\n<p>Software \u201ctalking\u201d to software via messages to convey a certain something happened. These messages being durable, i.e. in case of something bad happens, they can be still around, so when the process is restarted, the service is aware of \u201cI still need to process this message\u201d. Messaging makes things explicit of all the things, as a software person I need to consider and account for, exactly what those three steps of code was masking.<\/p>\n\n<h2 id=\"how-can-i-build-this-awesome-pubsub-as-the-backbone-for-the-software-i-write\">How can I build this awesome pub\/sub as the backbone for the software I write?<\/h2>\n<p>Juval Lowy\u2019s WCF book has a whole appendix worth 33 pages that describes, how you can build your own pub\/sub system using WCF. All I can say is,  May the force be with you. To start anything is easy, but to build it and build it right takes time. And the pressure is on you to make sure that this works well, and you\u2019ve taken care of every teeny tiny detail, since this will be a fundamental piece of the system. The last thing you want is events gone AWOL and the CEO watching you while you are trying to frantically debug your system! Talk about pressure!<\/p>\n\n<h2 id=\"there-is-a-much-easier-way\">There is a much easier way!<\/h2>\n<p>When I was on this quest to find a framework that can help me build software in a loosely coupled, event driven manner, my path crossed  with NServiceBus.<\/p>\n\n<p>NServiceBus is a light weight framework has been around for a long while and offers a robust and a relatively simple way of using pub\/sub in your software. You can have pub\/sub in 5 minutes, no kidding.  I\u2019ve haven\u2019t looked back since and I don\u2019t miss WCF much! My experience with NServiceBus has been fantastic. I could now focus on my business problem and not worry about the intricacy of how the underlying messages get transported and the infrastructure aspect. IJW (It just works!) and yes, Atlantis does exist!<\/p>\n\n<p>When you leave behind  RPC request response blocking calls and start thinking in terms of event driven programming and how messaging and good architecture makes your software more reliable and autonomous, I say, you\u2019ve arrived in the land of beautiful software and yes, Keats was right. A thing of beauty is a joy forever.<\/p>\n\n","pubDate":"Wed, 12 Jan 2011 00:00:00 +0000","link":"https:\/\/indu.dev\/event-driven%20architecture\/2011\/01\/12\/temporal-coupling.html","guid":"https:\/\/indu.dev\/event-driven%20architecture\/2011\/01\/12\/temporal-coupling.html","category":["Temporal","Coupling,","Event-driven","Architecture","Event-driven Architecture"]}]}}