<?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 Gopalkrushna Pattanaik on Medium]]></title>
        <description><![CDATA[Stories by Gopalkrushna Pattanaik on Medium]]></description>
        <link>https://medium.com/@gopalkrushnapattanaik?source=rss-de8c416b338------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Z8oRuCOHEbgQaf53QgSvqw@2x.jpeg</url>
            <title>Stories by Gopalkrushna Pattanaik on Medium</title>
            <link>https://medium.com/@gopalkrushnapattanaik?source=rss-de8c416b338------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 20:46:58 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@gopalkrushnapattanaik/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[From Spaghetti to Symphony: Architecting for Heterogeneous Workloads]]></title>
            <link>https://medium.com/@gopalkrushnapattanaik/from-spaghetti-to-symphony-architecting-for-heterogeneous-workloads-a2ec0f90abe2?source=rss-de8c416b338------2</link>
            <guid isPermaLink="false">https://medium.com/p/a2ec0f90abe2</guid>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[design-systems]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[scaling]]></category>
            <dc:creator><![CDATA[Gopalkrushna Pattanaik]]></dc:creator>
            <pubDate>Sun, 03 May 2026 05:46:23 GMT</pubDate>
            <atom:updated>2026-05-03T05:46:23.735Z</atom:updated>
            <content:encoded><![CDATA[<p>Most successful services eventually hit the “Integration Ceiling.” You started with a clean API, but over time, 20 different integrations were bolted on. Now, a new business requirement demands 6 more.</p><p>The problem isn’t just the quantity; it’s the heterogeneity. You are managing a chaotic mix:</p><ul><li><em>The Sprint:</em> High-frequency, low-latency read-heavy feeds.</li><li><em>The Marathon:</em> Write-heavy event loggers with high throughput.</li><li><em>The Zombie: </em>Legacy 3rd-party integrations with 5-second latencies and 10% error rates.</li></ul><p>Adding 6 more integrations to this pile is no longer a technical debt — it’s a business risk. Here is how to decompose the chaos into a scalable, high-performance ecosystem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kJHnP0b75ZS2SnLLbTao3w.png" /></figure><p><strong>The Decision Drivers: When and Where to Split?</strong></p><p>Decomposition is a surgical process. You don’t split for the sake of microservices; you split based on these four “Gravity Factors”:</p><p><strong><em>1. Domain Context (The Logical Split)</em></strong></p><p>Group by business capability, not technical utility.</p><ul><li>Example: A “Tax Calculator” and a “Promo Code Engine” might both be “calculations,” but they change for different reasons (legal vs. marketing). Keep them in separate Bounded Contexts.</li></ul><p><strong><em>2. Consistency Requirements</em></strong></p><ul><li><em>Strict Consistency (ACID):</em> If Integration A and B must update a shared ledger and <em>cannot</em> be out of sync for even a millisecond, they have “Data Gravity” and should stay together.</li><li><em>Eventual Consistency (BASE):</em> If a “User Profile” change can take 2 seconds to reflect in the “Analytics Integration,” decouple them using an event-driven approach.</li></ul><p><strong><em>3. Workload &amp; Traffic Patterns</em></strong></p><ul><li><em>Read vs. Write Heavy:</em> If Integration X is 99% reads (Catalog) and Integration Y is 99% writes (Logging), they shouldn’t compete for the same database thread pool.</li><li><em>Burstiness: </em>If one integration spikes 100x during Black Friday but the others don’t, isolate it so its autoscaling doesn’t drag the others along.</li></ul><p><strong><em>4. Failure Volatility</em></strong></p><ul><li>Example: If your “Shipping Tracker” relies on a flaky legacy API, isolate it. Use a Circuit Breaker so that when the Shipping API hangs, it doesn’t “starve” the threads for your “Checkout” integration.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LL2fnye5A8z2njVPax5HfQ.png" /></figure><p><strong>The Architecture: Strategic Decomposition</strong></p><p>To handle the 6 new integrations while fixing the existing 20, follow this blueprint:</p><p><strong><em>1. The Strangler Fig Pattern</em></strong></p><p>Stop adding to the monolith. Build the 6 new integrations as standalone services. Use an API Gateway (like Kong or Istio) to route traffic. To the client, it’s one API; internally, it’s a distributed system.</p><p><strong><em>2. CQRS for Read-Heavy Feeds</em></strong></p><p>For your read-heavy integrations, separate the Read Model from the Write Model. Scale your “Query Service” horizontally across multiple regions with a heavy Redis/Memcached layer, keeping the “Command Service” lean.</p><p><strong><em>3. Load Leveling for Write-Heavy Feeds</em></strong></p><p>Use Asynchronous Messaging (Kafka/RabbitMQ). Let the integration accept the write, return a 202 Accepted, and push the work to a queue. This protects your database from being &quot;hammered&quot; during traffic surges.</p><p><strong>Seamless Migration: The “Zero-Downtime” Strategy</strong></p><p>The biggest fear is breaking existing contracts. Here is how to migrate without the business ever noticing:</p><p><strong><em>1. The Anti-Corruption Layer (ACL)</em></strong></p><p>When building a new service that needs data from the old monolith, don’t use the monolith’s messy database schema. Build an ACL — a translation layer that maps the “legacy” data into your “new” clean domain models. This prevents the “rot” from spreading.</p><p><strong><em>2. Contract-First Migration (The “Facade” Pattern)</em></strong></p><p>To ensure zero changes to integration contracts:</p><ul><li>Keep the original API endpoints on the API Gateway.</li><li>Map the incoming legacy request format to the new service’s internal format at the Gateway or a “Shim” layer.</li><li>The external partner never knows the backend moved from a Ruby monolith to a Go microservice.</li></ul><p><strong><em>3. Shadow Mirroring (Dark Launching)</em></strong></p><p>Before switching traffic to a new service:</p><ul><li>Mirror the traffic: Send a copy of the production request to both the monolith and the new service.</li><li>Compare the results: Ensure the new service’s output matches the monolith’s.</li><li>Cutover: Once you have 99.9% parity, flip the switch at the API Gateway level.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KIWOh7R4YMn4aN6EU1th0Q.png" /></figure><p><strong>Conclusion</strong></p><p>Scaling from 20 to 26+ integrations isn’t about writing more code; it’s about reducing entanglement. By analyzing traffic patterns, isolating failure domains, and using an API Gateway to protect your contracts, you turn a brittle monolith into a resilient, event-driven platform.</p><p>Ready to start your decomposition?</p><ul><li>Which of your current 20 integrations is the “noisy neighbor” causing the most outages?</li><li>Do your 6 new requirements need real-time or eventual consistency?</li><li>Would you like a sample sequence diagram for the Shadow Mirroring phase?</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a2ec0f90abe2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Distributed Recovery: Why Idempotency is Your Best Friend.]]></title>
            <link>https://medium.com/@gopalkrushnapattanaik/distributed-recovery-why-idempotency-is-your-best-friend-6bb6fe565d48?source=rss-de8c416b338------2</link>
            <guid isPermaLink="false">https://medium.com/p/6bb6fe565d48</guid>
            <category><![CDATA[apache-kafka]]></category>
            <category><![CDATA[reliability-engineering]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Gopalkrushna Pattanaik]]></dc:creator>
            <pubDate>Fri, 13 Feb 2026 18:27:34 GMT</pubDate>
            <atom:updated>2026-02-14T02:34:02.977Z</atom:updated>
            <content:encoded><![CDATA[<p>In my previous post, we discussed how to solve the <strong>Dual-Write Problem</strong> using patterns like the Transactional Outbox. But there is a “hidden boss” that emerges during system recovery or network partitions: <strong>Out-of-Order Execution.</strong></p><p>If you are recovering from a crash and replaying 10,000 events, how do you ensure that an old “Update Address” event doesn’t overwrite a newer one? How do you ensure your system doesn’t process the same payment twice?</p><h3>1. The Sequencing Problem: The “Late Arriver”</h3><p>When a system recovers, Kafka or your outbox relayer might retry sending messages. In a distributed network, there is no guarantee that Message A will arrive before Message B unless you enforce it.</p><p><strong>The Solution: Partition Keys &amp; Sequence IDs</strong></p><ul><li><strong>Partition Keys:</strong> In Kafka, you must use a consistent key (e.g., user_id). This ensures all events for that user land in the same partition, where Kafka guarantees strict chronological order.</li><li><strong>Sequence IDs:</strong> Every event should carry a monotonically increasing version number or a high-precision “Event Timestamp” generated at the source of truth.</li></ul><h3>2. The Idempotency Guard: Making Retries Safe</h3><p>In a recovery scenario, “At-Least-Once” delivery is the standard. This means your consumers <em>will</em> see the same message more than once. Idempotency is the ability of a system to process the same message multiple times without changing the result beyond the initial application.</p><h4>Recovery Pattern A: The “Natural Idempotency” (Upserts)</h4><p>If your operation is a simple state overwrite (e.g., SET status = &#39;SHIPPED&#39;), it is naturally idempotent. Multiple applications of the same state result in the same final state.</p><ul><li><strong>Pitfall:</strong> This fails if the sequence is wrong. If ‘CANCELLED’ arrives before ‘SHIPPED’ due to a retry delay, you might end up with a ‘SHIPPED’ order that should have been dead.</li></ul><h4>Recovery Pattern B: The “State-Check” Pattern (Conditional Writes)</h4><p>The consumer checks the current version before applying the update.</p><blockquote><em>UPDATE orders SET status = &#39;SHIPPED&#39;, version = 5 WHERE order_id = 123 AND version &lt; 5;</em></blockquote><ul><li><strong>Pitfall:</strong> Requires the consumer to have a stateful database and adds a “read-before-write” overhead.</li></ul><h3>3. Critical Pitfalls of Common Patterns</h3><p>While the patterns above are robust, they come with trade-offs that can bite you in production:</p><p><strong>Pattern Common Pitfall The “Fix” Outbox Relayer</strong></p><p><strong>Duplicate Publishing:</strong> The relayer crashes after sending to Kafka but before marking the DB entry as “sent.”Ensure the downstream consumer is idempotent.</p><p><strong>Time-based Sequencing Clock Skew:</strong> Two different app instances might have clocks that are off by milliseconds, causing events to be sequenced incorrectly.Use a Database-generated sequence or a Logical Clock (Lamport Timestamps).</p><p><strong>Listen-to-Yourself Circular Loops:</strong> A consumer might accidentally trigger a new event that leads back to itself.Use “Trace IDs” or “Origin Headers” to filter out self-generated events.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VuEkpbqoZLyua0SJ1E1ObQ.png" /><figcaption>Common Patterns</figcaption></figure><h3>4. The Vector Clock (Causal Ordering)</h3><p>For high-availability systems where multiple nodes accept writes, we use <strong>Vector Clocks</strong>. Each node maintains a counter. An event’s “time” is a vector (e.g., [NodeA:3, NodeB:1]).</p><ul><li><strong>How it helps:</strong> It allows the consumer to detect <strong>Causality</strong>. If an incoming message’s vector is “smaller” than the local state, it’s an old event. If the vectors are incomparable, you’ve found a <strong>Conflict</strong> that needs manual resolution.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fxNAUexPfviH2pL5t46lEQ.png" /></figure><h3>5 . Designing for “Safe” Failure</h3><p>The goal of recovery isn’t to prevent duplicates — it’s to make duplicates <strong>boring</strong>.</p><p>When designing your recovery logic, follow the <strong>Rule of Three</strong>:</p><ol><li><strong>Tag it:</strong> Every message gets a unique event_id and a version_number.</li><li><strong>Route it:</strong> Use consistent partitioning to keep the sequence in one lane.</li><li><strong>Check it:</strong> The consumer must always ask: <em>“Have I seen this ID before?”</em> or <em>“Is this version newer than what I have?”</em></li></ol><h3>Final Thought</h3><p>Consistency in distributed systems isn’t a gift; it’s a discipline. You cannot prevent failure, but you can make recovery <strong>deterministic</strong>. By using Partition Keys for ordering and Vector Clocks for causality, you ensure that no matter how many times a system crashes, it always wakes up in the right state.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6bb6fe565d48" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Solving the Dual-Write Problem: Ensuring Atomic Updates Across Distributed Systems]]></title>
            <link>https://medium.com/@gopalkrushnapattanaik/solving-the-dual-write-problem-ensuring-atomic-updates-across-distributed-systems-2732ccdc77c9?source=rss-de8c416b338------2</link>
            <guid isPermaLink="false">https://medium.com/p/2732ccdc77c9</guid>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <dc:creator><![CDATA[Gopalkrushna Pattanaik]]></dc:creator>
            <pubDate>Sat, 07 Feb 2026 06:42:43 GMT</pubDate>
            <atom:updated>2026-02-07T06:42:43.740Z</atom:updated>
            <content:encoded><![CDATA[<h3>The Peril of Inconsistent States in Modern Architectures</h3><p>In the world of distributed systems, we often find ourselves in situations where a single logical operation requires updates to multiple independent systems. Whether it’s updating a database and publishing a message to Apache Kafka, sending an email after a user action, or invalidating a cache after data changes, the need for atomicity across these operations is paramount.</p><p>Yet, a common and insidious challenge lurks: the <strong>dual-write problem</strong>. It’s that moment when you perform two critical updates, and one succeeds while the other mysteriously fails. The result? An inconsistent system state that can lead to data discrepancies, lost events, and ultimately, a breakdown of trust in your application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FbL3g6lU0iP7AT9_ADLAlQ.png" /><figcaption>DUAL WRITE</figcaption></figure><h3>What Exactly is the Dual-Write Problem?</h3><p>The dual-write problem manifests when two or more systems must be updated as part of a single, indivisible operation, but due to a failure in one of the updates, the overall operation doesn’t complete successfully across all systems.</p><p>Consider the classic scenario:</p><ul><li>A user places an order, and your application successfully updates the order status in the <strong>database</strong>.</li><li>Simultaneously, the application attempts to publish an event to <strong>Kafka</strong> to notify other services about the new order.</li><li><strong>Crucially, the Kafka event publish fails</strong> due to a network issue, a broker outage, or an application crash.</li></ul><p>The outcome? Your database shows a new order, but no event was published. Downstream services relying on Kafka events will never know about this order, leading to processing delays, missing inventory updates, or frustrated customers. This isn’t just a Kafka problem; it applies to any scenario where you write to multiple distinct systems:</p><ul><li>Database + Kafka</li><li>Database + Email Service</li><li>Database + Cache</li><li>Database + Another Database (e.g., a reporting DB)</li></ul><h3>Common Anti-Patterns and Why They Fall Short</h3><p>Developers often attempt to solve the dual-write problem with seemingly intuitive, but ultimately flawed, approaches. Let’s look at why these common anti-patterns fail:</p><h4>1. Reordering Writes (Kafka First vs. DB First)</h4><p>One might think, “If the second write fails, let’s just swap the order!”</p><ul><li><strong>Kafka first, then Database:</strong> If the database update fails, you’ve published an event for an action that never fully materialised. Now you have a “ghost” event.</li><li><strong>Database first, then Kafka:</strong> This is the scenario described above — a successful database write with a failed Kafka publish, leading to lost events.</li></ul><p>In both cases, if the second write fails, your system is left in an inconsistent state.</p><h4>2. Database Transactions</h4><p>“Why not just use a database transaction?” This is a natural thought, especially for those familiar with ACID properties. However, a crucial limitation of traditional database transactions is that they do not span external systems like Kafka, email services, or other databases.</p><p>You can successfully rollback a database transaction if a subsequent Kafka publish fails, but this won’t undo the Kafka event if it <em>was</em> successfully published before the database commit. It provides a false sense of safety because transactions are confined to the boundaries of a single transactional resource.</p><h4>3. Simple Retries</h4><p>Retrying the failed operation (e.g., retrying the Kafka publish) seems like a pragmatic solution. And it is, to an extent! However, simple in-memory retries are unreliable if your application crashes mid-retry.</p><p>If you attempt “durable retries” (e.g., storing the failed event in a separate table to retry later), you’ve just created <em>another</em> dual-write problem — writing to your main system <em>and</em> the retry table. While helpful as a part of a larger strategy, simple retries alone are an incomplete solution.</p><h3>Proven Solutions That Actually Work</h3><p>Since you can’t truly make dual writes atomic across inherently separate systems, the goal is to design for safe and recoverable failures. The winning strategy involves separating the writes, designating one as the source of truth, and ensuring robust retries for the rest.</p><p>Here are three industry-proven patterns:</p><h4>1. The Transactional Outbox Pattern (Most Common)</h4><p>This is arguably the most widely adopted and robust solution for the dual-write problem, especially with Kafka.</p><p><strong>How it works:</strong></p><ol><li>When a business operation occurs, your application doesn’t directly publish to Kafka.</li><li>Instead, it writes both the business data update (e.g., UPDATE orders SET status=&#39;shipped&#39;) and the corresponding event message (e.g., ORDER_SHIPPED_EVENT) into the <strong>same database transaction</strong>.</li><li>The event message is stored in a dedicated “outbox” table within your database.</li><li>A separate, independent process (often called an “outbox relayer” or using Change Data Capture — CDC) constantly monitors this outbox table.</li><li>When a new event appears in the outbox, this process reads it, publishes it to Kafka, and then marks it as published (or deletes it) in the outbox table.</li><li>The outbox relayer has its own robust retry mechanism, ensuring that the event is eventually published to Kafka, even if Kafka is temporarily unavailable.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0riG717jmZ7znzlyv81pyw.png" /></figure><p><strong>Benefits:</strong></p><ul><li><strong>Strong Consistency:</strong> Guarantees that either both the business data and the event are saved in the DB, or neither are.</li><li><strong>Kafka-Friendly:</strong> Decouples the core business logic from Kafka publishing concerns.</li><li><strong>Industry-Proven:</strong> A well-established pattern used by many companies.</li></ul><h4>2. Event Sourcing</h4><p>Event Sourcing is a more fundamental architectural pattern that inherently solves the dual-write problem by changing how state is stored.</p><p><strong>How it works:</strong></p><ol><li>Instead of storing the current state of an entity, you persist a sequence of immutable events that represent every change to that entity as the source of truth.</li><li>The current state of an entity is <em>rebuilt</em> by replaying all its historical events.</li><li>These events, once persisted, are then published to Kafka (or another message broker) for other services to consume. Since the event itself is the primary record, there’s no “dual-write” between business data and an event; the event <em>is</em> the business data.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_8D2CNWZ9wTTsuiELSOjng.png" /></figure><p><strong>Benefits:</strong></p><ul><li><strong>No Dual-Write:</strong> The problem simply doesn’t exist in this model.</li><li><strong>Audit-ability &amp; History:</strong> Provides a complete, immutable audit trail of all changes.</li><li><strong>Powerful for Complex Domains:</strong> Excellent for financial systems, gaming, or any domain where understanding history is critical.</li></ul><p><strong>Considerations:</strong></p><ul><li><strong>Higher Complexity:</strong> Requires a significant paradigm shift and can be more complex to implement and manage.</li></ul><h4>3. Listen-to-Yourself Pattern (Eventual Consistency)</h4><p>This pattern flips the traditional order, relying on eventual consistency.</p><p><strong>How it works:</strong></p><ol><li>When a user action occurs, your application directly publishes an event to Kafka.</li><li>The application then immediately commits, without updating its own database synchronously.</li><li>The same application (or another service) acts as a consumer of its <em>own</em> Kafka topic.</li><li>Upon consuming the event, it then updates its internal database.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kJWCmO4cvnnD-Lm9vj4aqA.png" /></figure><p><strong>Benefits:</strong></p><ul><li><strong>Extremely Fast:</strong> The initial write is very quick, as it’s just a Kafka publish.</li><li><strong>No Dual-Write:</strong> Only one write is considered “primary” at the initial step.</li></ul><p><strong>Considerations:</strong></p><ul><li><strong>Eventual Consistency Required:</strong> Your application must be designed to tolerate a brief period where the event is published but its internal database state hasn’t yet caught up. This can impact user experience if immediate consistency is expected.</li><li><strong>Idempotency:</strong> The database updates must be idempotent, as events might be consumed multiple times.</li></ul><h3>Key Takeaway: Design for Safe and Recoverable Failures</h3><p>The fundamental truth is that you cannot make dual writes <em>atomically consistent</em> across genuinely separate systems in a distributed environment. Failures will happen. The winning strategy is to anticipate these failures and design your system so that:</p><ol><li><strong>Writes are separated:</strong> Don’t try to bundle inherently disparate operations into one synchronous block.</li><li><strong>One system is the source of truth:</strong> Identify which system holds the primary, authoritative record (e.g., your database in the Outbox pattern, or the event store in Event Sourcing).</li><li><strong>Retries are robust and durable:</strong> Ensure that any subsequent updates to other systems are guaranteed to eventually succeed, often through persistent queues or dedicated retry mechanisms.</li></ol><h3>Final Thought</h3><p>If your system:</p><ul><li>Writes to Kafka</li><li>Sends emails</li><li>Updates caches</li><li>Interacts with multiple microservices</li></ul><p>…then congratulations, you already have a distributed system! And with it, the dual-write problem is a very real threat to data integrity and system reliability.</p><p>Don’t wait for a production incident to discover its impact. Proactively design for the dual-write problem from the outset, adopting one of these proven patterns to build resilient, consistent, and scalable applications. Your future self (and your users) will thank you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2732ccdc77c9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating Fault Tolerant Services Using Resilience4j]]></title>
            <link>https://medium.com/@gopalkrushnapattanaik/creating-fault-tolerant-services-using-resilience4j-888d72a4fc0e?source=rss-de8c416b338------2</link>
            <guid isPermaLink="false">https://medium.com/p/888d72a4fc0e</guid>
            <category><![CDATA[resilience4j]]></category>
            <category><![CDATA[monitoring]]></category>
            <category><![CDATA[rate-limiter]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[circuit-breaker]]></category>
            <dc:creator><![CDATA[Gopalkrushna Pattanaik]]></dc:creator>
            <pubDate>Tue, 24 Dec 2019 10:49:57 GMT</pubDate>
            <atom:updated>2019-12-24T17:02:26.550Z</atom:updated>
            <content:encoded><![CDATA[<p>In a distributed system, whenever a service makes a synchronous request to another service, there is an ever-present risk of partial failure. Because the client and the service are separate processes, a service may not be able to respond in a timely way to a client’s request. The service could be down because of a failure or for maintenance. Or the service might be overloaded and responding extremely slowly to requests. Because the client is blocked waiting for a response, the danger is that the failure could cascade to the client’s clients and so on and cause an outage.</p><p>There are several design patterns that are available to achieve fault tolerance against these partial failures. It is beautifully described by Netflix Tech blog <a href="https://medium.com/netflix-techblog/fault-tolerance-in-a-high-volume-distributed-system-91ab4faae74a"><em>here</em></a> .</p><p>In Summary Whenever a service invokes other services synchronously it should protect itself from using combination of below mechanisms</p><ul><li><strong><em>Network timeouts (</em></strong><em>Never block indefinitely and always use timeouts)</em></li><li><strong><em>Retry </em></strong><em>(Retry after specified period of time to avoid the transaction to fail due to transient failures such as network glitch</em><strong><em>)</em></strong></li><li><strong><em>BulkHead </em></strong>(Limiting the number of outstanding requests from a client to a service)</li><li><strong><em>Circuit breaker (</em></strong><em>Track the number of successful and failed requests, and if the error rate exceeds some threshold, trip the circuit breaker so that further attempts fail immediately</em><strong><em>)</em></strong></li><li><strong><em>Rate Limit (</em></strong><em>As a Service limiting the processing of number of requests from each client in a given period.</em><strong><em>)</em></strong></li></ul><p>Few of these above mechanisms were provided by Netflix library <strong>Hystrix </strong>which is used vastly till date.</p><p><strong>Introduction to Resilience4j</strong></p><p>After Netflix in Nov 2018 announced that Hystrix will be under maintenance mode and no further new development will be done, in Dec 2018 Spring Cloud Hystrix project is deprecated.So new applications should not use this project. Instead Resilience4j is a new option for Spring developers to implement the circuit breaker pattern.</p><p>Resilience4j is also more lightweight compared to Hystrix as it has the Vavr library as its only dependency. Netflix Hystrix, by contrast, has a dependency on Archaius which has several other external library dependencies such as Guava and Apache Commons.</p><p>Resilience4j comes with features like <strong>Rate Limiter, Retry and Bulkhead along with Circuit Breaker pattern</strong>. Works well with spring boot and using micrometer libraries, it can emit metrics for monitoring.</p><p>There is no replacement introduced by Spring for Hystrix Dashboard so users need to use prometheus or NewRelic for monitoring.</p><p>A sample poc application using spring boot and Resilience4J with monitoring enabled using Prometheus and Grafana can be found <a href="https://github.com/gopalkrushnapattanaik/Resilience4j-POC"><em>here</em></a>.</p><p>Below are the few of the screen grabs from Grafana circuit breaker dashboard</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aZU7SM9XFIqly8e7ytymAw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZmpB_YGGhnrpUHW1jFlD1Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QhmExm6kVD2Of3WYraUwKA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YbnYy4AzPppTk8_qkOSZCA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LrLMmCtsjcCwzNgDDsfwUw.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=888d72a4fc0e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Monitoring spring boot services using micrometer , prometheus, Grafana]]></title>
            <link>https://medium.com/@gopalkrushnapattanaik/monitoring-spring-boot-services-using-micrometer-prometheus-grafana-30106774372d?source=rss-de8c416b338------2</link>
            <guid isPermaLink="false">https://medium.com/p/30106774372d</guid>
            <category><![CDATA[monitoring]]></category>
            <category><![CDATA[observability]]></category>
            <category><![CDATA[prometheus]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[metrics-and-analytics]]></category>
            <dc:creator><![CDATA[Gopalkrushna Pattanaik]]></dc:creator>
            <pubDate>Tue, 17 Dec 2019 10:20:21 GMT</pubDate>
            <atom:updated>2019-12-17T10:20:21.981Z</atom:updated>
            <content:encoded><![CDATA[<h3>Monitoring spring boot services using micrometer , prometheus, Grafana</h3><p>Observability is a key factor of modern application, traditionally majority of java applications depends on the robust logging. But visualising have been done from logs using some popular enterprise tools like Splunk, App-dynamics.</p><p>Now in market from past few years we have many open source tools like ElasticSearch,LogStash &amp; Kibana [ELK] which provides very convenient way of depicting and visualising the observability of softwares.</p><p>With the release of SpringBoot2 , It has been very easy to monitor the health and other metrics of the application using Micrometer, Prometheus, Grafana.</p><ul><li><strong>Spring Boot Actuator </strong>: Exposes the application metrics as REST endpoints</li><li><strong>Micrometer</strong>: As Actuator endpoints are not vendor neutral, so to overcome of this we can use Micrometer which exposes Actuator metrics to external monitoring systems such as Prometheus, AWS Cloudwatch, and many more , in a specific format that vendors can understand. We can consider Micrometer as a facade for metrics for various vendor types.</li><li><strong>Prometheus</strong>: Time series DB to Store our metric data , it scrapes the endpoints and will store the metrics.</li><li><strong>Grafana</strong>: Visualises our data in graphs , backed by Prometheus as Datasource.</li></ul><p>In this Project We have added the below dependencies , which will expose the actuator endpoints using micrometer which Prometheus understands.</p><pre>compile(&#39;org.springframework.boot:spring-boot-starter-web&#39;)<br>compile group: &#39;org.springframework.boot&#39;, name: &#39;spring-boot starter-actuator&#39;, version: &#39;2.1.6.RELEASE&#39;<br>compile(&#39;io.micrometer:micrometer-registry-prometheus&#39;)</pre><p>After running the spring boot application with above dependencies, @ default port , spring-boot-actuator will automatically expose the system metrics @ <a href="http://localhost:8080/actuator/">http://localhost:8080/actuator/</a></p><p><em>{<br> “_links”: {<br> “self”: {<br> “href”: “</em><a href="http://localhost:8080/actuator"><em>http://localhost:8080/actuator</em></a><em>&quot;,<br> “templated”: false<br> },<br> “auditevents”: {<br> “href”: “</em><a href="http://localhost:8080/actuator/auditevents"><em>http://localhost:8080/actuator/auditevents</em></a><em>&quot;,<br> “templated”: false<br> },<br> “beans”: {<br> “href”: “</em><a href="http://localhost:8080/actuator/beans"><em>http://localhost:8080/actuator/beans</em></a><em>&quot;,<br> “templated”: false<br> },<br> “caches-cache”: {<br> “href”: “</em><a href="http://localhost:8080/actuator/caches/%7Bcache"><em>http://localhost:8080/actuator/caches/{cache</em></a><em>}&quot;,<br> “templated”: true<br> },<br> “caches”: {<br> “href”: “</em><a href="http://localhost:8080/actuator/caches"><em>http://localhost:8080/actuator/caches</em></a><em>&quot;,<br> “templated”: false<br> },<br> “health”: {<br> “href”: “</em><a href="http://localhost:8080/actuator/health"><em>http://localhost:8080/actuator/health</em></a><em>&quot;,<br> “templated”: false<br> },<br> “health-component”: {<br> “href”: “</em><a href="http://localhost:8080/actuator/health/%7Bcomponent"><em>http://localhost:8080/actuator/health/{component</em></a><em>}&quot;,<br> “templated”: true<br> },<br> “health-component-instance”: {<br> “href”: “</em><a href="http://localhost:8080/actuator/health/%7Bcomponent%7D/%7Binstance"><em>http://localhost:8080/actuator/health/{component}/{instance</em></a><em>}&quot;,<br> “templated”: true<br> },<br> “conditions”: {<br> “href”: “</em><a href="http://localhost:8080/actuator/conditions"><em>http://localhost:8080/actuator/conditions</em></a><em>&quot;,<br> “templated”: false<br> },<br> “configprops”: {<br> “href”: “</em><a href="http://localhost:8080/actuator/configprops"><em>http://localhost:8080/actuator/configprops</em></a><em>&quot;,<br> “templated”: false<br> },<br> “env”: {<br> “href”: “</em><a href="http://localhost:8080/actuator/env"><em>http://localhost:8080/actuator/env</em></a><em>&quot;,<br> “templated”: false<br> },<br> “env-toMatch”: {<br> “href”: “</em><a href="http://localhost:8080/actuator/env/%7BtoMatch"><em>http://localhost:8080/actuator/env/{toMatch</em></a><em>}&quot;,<br> “templated”: true<br> },<br> “info”: {<br> “href”: “</em><a href="http://localhost:8080/actuator/info"><em>http://localhost:8080/actuator/info</em></a><em>&quot;,<br> “templated”: false<br> },<br> “loggers-name”: {<br> “href”: “</em><a href="http://localhost:8080/actuator/loggers/%7Bname"><em>http://localhost:8080/actuator/loggers/{name</em></a><em>}&quot;,<br> “templated”: true<br> },<br> “loggers”: {<br> “href”: “</em><a href="http://localhost:8080/actuator/loggers"><em>http://localhost:8080/actuator/loggers</em></a><em>&quot;,<br> “templated”: false<br> },<br> “heapdump”: {<br> “href”: “</em><a href="http://localhost:8080/actuator/heapdump"><em>http://localhost:8080/actuator/heapdump</em></a><em>&quot;,<br> “templated”: false<br> },<br> “threaddump”: {<br> “href”: “</em><a href="http://localhost:8080/actuator/threaddump"><em>http://localhost:8080/actuator/threaddump</em></a><em>&quot;,<br> “templated”: false<br> },<br></em><strong><em> “prometheus”: {<br> “href”: “</em></strong><a href="http://localhost:8080/actuator/prometheus"><strong><em>http://localhost:8080/actuator/prometheus</em></strong></a><strong><em>&quot;,<br> “templated”: false<br> },</em></strong><em><br> “metrics-requiredMetricName”: {<br> “href”: “</em><a href="http://localhost:8080/actuator/metrics/%7BrequiredMetricName"><em>http://localhost:8080/actuator/metrics/{requiredMetricName</em></a><em>}&quot;,<br> “templated”: true<br> },<br> “metrics”: {<br> “href”: “</em><a href="http://localhost:8080/actuator/metrics"><em>http://localhost:8080/actuator/metrics</em></a><em>&quot;,<br> “templated”: false<br> },<br> “scheduledtasks”: {<br> “href”: “</em><a href="http://localhost:8080/actuator/scheduledtasks"><em>http://localhost:8080/actuator/scheduledtasks</em></a><em>&quot;,<br> “templated”: false<br> },<br> “httptrace”: {<br> “href”: “</em><a href="http://localhost:8080/actuator/httptrace"><em>http://localhost:8080/actuator/httptrace</em></a><em>&quot;,<br> “templated”: false<br> },<br> “mappings”: {<br> “href”: “</em><a href="http://localhost:8080/actuator/mappings"><em>http://localhost:8080/actuator/mappings</em></a><em>&quot;,<br> “templated”: false<br> }<br> }<br>}</em></p><p>Here in the above response we can see that <strong><em>prometheus </em></strong><em>has its own endpoint exposed which it can use to get the metrics @</em><a href="http://localhost:8080/actuator/prometheus"><strong><em>http://localhost:8080/actuator/prometheus</em></strong></a><em>.</em></p><p>Now we will Install and Configure Prometheus &amp; Grafana to integrate with our application.</p><p><strong>Prometheus</strong></p><p>Prometheus is a time-series database that stores our metric data by pulling it (using a built-in data scraper) periodically over HTTP. The intervals between pulls can be configured. we have to provide the URL to pull from. It also has a simple user interface where we can visualise/query on all of the collected metrics.</p><p><strong>Install and Configure Prometheus</strong></p><p>We can use docker compose image to run prometheus , here we are using Homebrew to install</p><pre>brew update<br>brew install prometheus<br>vi prometheus.yml</pre><p>Create the Prometheus config file [prometheus.yml], where we have to provide mention the target URL from where prometheus server will scrape the metrics and form the graphs to visualise them.</p><pre>global:<br>  scrape_interval: 10s<br><br>scrape_configs:<br>  - job_name: &#39;spring_micrometer&#39;<br>    metrics_path: &#39;/actuator/prometheus&#39;<br>    scrape_interval: 5s<br>    static_configs:<br>      - targets: [&#39;localhost:8080&#39;]</pre><p>We have provided the details to Prometheus server, now we can start the server using this config file , so that the metrics can be scrapped.</p><pre>prometheus --config.file=prometheus.yml</pre><p>prometheus will start @ default port 9090 <a href="http://localhost:9090/">http://localhost:9090/</a></p><p>We can see the prometheus server is up .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XkNBFZ2986LMgtotgs-o-Q.png" /><figcaption>Home page</figcaption></figure><p>lets check what target endpoint it is scrapping by navigating @<a href="http://localhost:9090/targets">http://localhost:9090/targets</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FxESfRWmcRJdKIq5FAdZ6w.png" /><figcaption>Target</figcaption></figure><p>We can see the job defined before in the config file spring_micrometer is shown along with the endpoint configured.</p><p>Now lets quickly check few of the system metrics using the graphs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mY1BYksge5lKxiFznZTdVw.png" /><figcaption>System CPU usage</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-B2SfR5GzgyhmtDT8nX4Ag.png" /><figcaption>JVM Memory Usage</figcaption></figure><h3>Grafana</h3><p>While Prometheus does provide some crude visualisation, Grafana offers a rich UI where you can build up custom graphs quickly and create a dashboard out of many graphs in no time.</p><p>There are many built in dashboards readily available @ <a href="https://grafana.com/grafana/dashboards">https://grafana.com/grafana/dashboards</a> which we can use directly.</p><p>Grafana dashboards are backed by any given data source (<a href="https://grafana.com/docs/grafana/latest/features/datasources/#supported-data-sources/">https://grafana.com/docs/grafana/latest/features/datasources/#supported-data-sources/</a>) from where it pulls details , few of the examples are</p><ul><li>AWS CloudWatch</li><li>Azure Monitor</li><li>Elasticsearch</li><li>Google Stack driver</li><li>Graphite</li><li>InfluxDB</li><li>Loki</li><li>Microsoft SQL Server (MSSQL)</li><li>Mixed</li><li>MySQL</li><li>OpenTSDB</li><li>PostgreSQL</li><li>Prometheus</li><li>Testdata</li></ul><p>We will be using Prometheus as our datasource for our grafana setup.</p><p><strong>Install and Configure Grafana</strong></p><p>I am using Homebrew again to install grafana for this proj , Docker compose is recommended for general usage.</p><pre> brew update<br> brew install grafana<br> brew tap homebrew/services<br> brew services start grafana</pre><p>Grafana will start at its default address @http://localhost:3000/<br>and default username/password :- admin/admin</p><p>First step is to add a data source to start with any dashboard, we will add a data source for Prometheus</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TUuJrDUUKIs-7Jmt0NhryQ.png" /><figcaption>Add DataSource</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s83LWZQpibejITtdflyHpg.png" /><figcaption>Add the Endpoint to Prometheus</figcaption></figure><p>Now we can create a dashboard to monitor the application, we will use a very popular JVM dashboard available @ <a href="https://grafana.com/grafana/dashboards/4701">https://grafana.com/grafana/dashboards/4701</a></p><p>Once added we can monitor our system metrics as given below with rich UI experience.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jdVD8HzNC2YxE0QxGOnyNw.png" /></figure><p>Prometheus &amp; Grafana has different types of logging metrics available like</p><p><strong>Counter</strong> to check number at cumulative level that only ever goes up . It is useful for data like number of sessions, number of events consumed ,number of Requests served , Error occurred and so on.</p><p><strong>Gauge </strong>is a number that can go up or down with time based on some factors. it is useful for data like JVM Memory Usage , Sessions in your website.</p><p><strong>Histogram &amp; Summary </strong>are sample observations, typically request durations or response sizes. They track the number of observations <em>and</em> the sum of the observed values, allowing you to calculate the <em>average</em> of the observed values.</p><p>Thats all as of now. Thank you &amp; Happy learning :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=30106774372d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Improving Fault-Tolerance of System in Micro-services Environment.]]></title>
            <link>https://medium.com/@gopalkrushnapattanaik/improving-fault-tolerance-of-system-in-micro-services-environment-452b9a326d58?source=rss-de8c416b338------2</link>
            <guid isPermaLink="false">https://medium.com/p/452b9a326d58</guid>
            <category><![CDATA[retry]]></category>
            <category><![CDATA[circuit-breaker]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[resiliency]]></category>
            <dc:creator><![CDATA[Gopalkrushna Pattanaik]]></dc:creator>
            <pubDate>Sun, 05 May 2019 18:53:34 GMT</pubDate>
            <atom:updated>2019-09-30T06:23:52.840Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to Make Microservices more Resilient &amp; Fault Tolerant</h3><p>In a typical micro-services environment , the services bounded based on their domain context and interact with each other commonly using lightweight protocols such as HTTP/REST.</p><p>Even-though this architectural style separates the concerns and isolates failure boundaries still they can stop working intermittently due to transient failures because of some known issues which are not limited to slow-network connection , timeouts ,overcommitting resources or temporary unavailability of service. Ideally these issues are only transient and should recover on its own after a short period of time.</p><p>To build a robust service , it has to be fault tolerant enough to tackle such failures to minimise the impact . Here are below few of the patterns available to achieve the same.</p><blockquote><strong><em>Retry Pattern</em></strong></blockquote><p>This pattern states about enabling retry for a remote resource in case of transient failure. The ability to retry for a failed operation improves stability of the application. Continuous retry without any delay could also cause cascading effect , and hence to reduce it there should be a delay introduced between each retry. It will be more effective if the delay time is increased exponentially post each retry till it reaches the maximum limit. This strategy will increase the chances of retry to succeed as normally these faults are self -correcting in nature.</p><p>This can be successfully implemented using standard libraries like <strong><em>spring-boot retry module</em></strong> or the<strong><em> resilience-4j </em></strong>retry component.</p><p>W<strong><em>hen to use :</em></strong></p><ul><li>This could be useful only when the operation trying to access a remote resources causes failure which is transient in nature.</li><li>These faults are expected to be short lived, and repeating a request that has previously failed could succeed on a subsequent attempt.</li></ul><p>W<strong><em>hen Not to use :</em></strong></p><ul><li>If the faults are not short lived in nature . As it means the over all response time of application would increase .</li><li>The failures are not due to temporary environmental issues of service rather because of some internal exceptions caused due to some business logic failures in service.</li><li>As a substitution to scaling, means if the service is often responds back as “busy” because of lack of resources. Then retry will not help rather increasing resources of concerned service will help.</li></ul><blockquote><strong><em>Circuit Breaker Pattern</em></strong></blockquote><p>If the faults are not transient in nature and expected to last longer in that case it is not a good idea to keep retrying, as the probability of getting success is very less.</p><p>It can cause adverse effect on the system under heavy load, as many concurrent requests to the same operation to be blocked until the timeout period expires. These blocked requests will hold on to system resources such as memory, threads, database connections, and so on. Consequently, these resources could be exhausted, causing failure of other operations which are unrelated to these requests, due to lack of resources in the system.</p><p>So in these cases it is better to fail the operations immediately and don’t entertain more requests to same remote resource till we are confident that it is available and responding. Once the system knows that the service back online and working then the next calls will be completed. This can be achieved using a C<strong>ircuit Breaker .</strong></p><p>A circuit breaker prevents system to attempt for a remote resource(<strong><em>open circuit</em></strong>) that is more likely to fail there by saving critical system resources. This allows other operations to run smoothly . A circuit breaker also have ability to detect if the service is back to normal and allows the calls (c<strong><em>losed circuit</em></strong>) to go through.Apart from open and closed states , A typical circuit breaker have another transit state known as <strong>Half-Open Circuit.</strong></p><p>So circuit breaker can be implemented as a State-Machine with three states <strong><em>Open,Closed,Half-Open.</em></strong></p><p>The below figure shows how a typical circuit breaker works.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/552/1*NHInu_77fAeBhDxfRR0NMQ.png" /></figure><p><strong>Closed</strong> is the default state of the circuit breaker , in the figure here we are using a failure counter which is time based , if in a specific period of time the number of failures do not exceed the threshold then it will be reset , and the circuit will remain in Closed state. This will make sure the circuit will not enter to Open state in case of occasional failures.</p><p>The Circuit will enter in to <strong>Open </strong>state if in a given time period the number of failures exceeds a pre-defined threshold value. Once it enters Open state , it will initiate a failure timeout counter. As long as the counter is not expired the circuit breaker will remain in Open state and all the attempts will be blocked and error/default value will be returned whatever configured.</p><p>When in Open state and failure timeout is exceeded then circuit breaker will enter in to a state known as <strong>Half-Open , </strong>in this state system will maintain a success counter , which will be incremented for every success remote call. If the call fails then again state will be changed to Open , else if we get consecutive success operations till the counter exceeds a pre-defined threshold than it will change the state to Closed, and all the subsequent calls will be served.</p><p>Netflix’s <strong>Hystrix</strong> library provides an implementation of the <strong>Circuit Breaker</strong> pattern.</p><p><strong><em>Conclusion :</em></strong></p><p>The faults in services can come in many shape and size, we have discussed few cases above . Apart from Retry , Circuit breaker there are many more patterns available like BulkHead ,Rate-Limiting,Fail-Over Caching which when used effectively can improve the overall service stability.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=452b9a326d58" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Count-Min Sketch]]></title>
            <link>https://medium.com/@gopalkrushnapattanaik/understanding-count-min-sketch-8a10590fc936?source=rss-de8c416b338------2</link>
            <guid isPermaLink="false">https://medium.com/p/8a10590fc936</guid>
            <category><![CDATA[data-structures]]></category>
            <dc:creator><![CDATA[Gopalkrushna Pattanaik]]></dc:creator>
            <pubDate>Fri, 15 Mar 2019 09:07:26 GMT</pubDate>
            <atom:updated>2019-03-15T18:22:13.089Z</atom:updated>
            <content:encoded><![CDATA[<p><em>In computing, the count–min sketch (CM sketch) is a probabilistic data structure that serves as a frequency table of events in a stream of data. It uses hash functions to map events to frequencies, but unlike a hash table uses only sub-linear space, at the expense of over counting some events due to collisions.</em></p><p>In an ideal case for retrieving frequency of any streaming data we use HashTable as we can Store the HashValues in the Hash table and retrieve them easily at O(1). But by doing so we are storing all the data in the hash tables which will fall in to super liner Memory usage for very large (infinite) streaming of data.</p><p>To tackle this memory in efficiency model , we can use count min sketch to calculate the frequency in sub-liner space , because in this case we will not be storing the complete values of data stream , instead we will use a matrix to compute the frequency, where number of rows would be number of Hash functions we are using and columns would be number of out come of the HashFunctions.</p><p>Lets understand the count min sketch algorithm with an example</p><p>Lets say we have a stream of data</p><p>Stream = {A,A,B,A,B,D,A……..}</p><p>Lets define 4 hash functions H1,H2,H3,H4 and lets assume the below table for their out puts as shown in pic..</p><p>Now Lets Create a Matrix to keep a track of count of input streams</p><p>Here is the matrix of Hash function X possible Outputs (Matrix-1)</p><p>Now for each data from stream now lets calculate the Hash outputs and increment the corresponding counter in the table….</p><p>H1(A) = 1, H2(A) = 3, H3(A) = 1, H4(A)=2</p><p>So by increasing the corresponding counts in the matrix we will have .. matrix 2</p><p>Similarly next in stream we again get A so lets update the table .. so now the table will be matrix 3</p><p>Next in the stream we have B .. So the Hash output of B is H1(B)= 3 ,H2(B)= 5 , H3(B) = 3 , H4(B) =1 … so lets update matrix accordingly matrix 4</p><p>Next again A so updated matrix is matrix 5</p><p>Next in Stream is B so will be matrix 6</p><p>Now Next in Stream is D</p><p>H1(D)= 2 ,H2(D)= 1 , H3(D) = 4 , H4(D) =4</p><p>So updated matrix will be….matrix 7</p><p>Now again A…. so updated matrix is matrix 8</p><p>(Below Figure shows the Matrix at each stage…)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pX0XhX4baGBoZnT6.png" /></figure><p>Now lets calculate the frequency of A…</p><p>Again pass A to all hash functions and result is H1(A) = 1, H2(A) = 3, H3(A) = 1, H4(A)=2</p><p>Now take the array of these positions in matrix which comes to {4,4,4,4} .. so minimum of this comes to 4 so The frequency of A= 4.</p><p>Similarly Lets calculate frequency of B H1(B)= 3 ,H2(B)= 5 , H3(B) = 3 , H4(B) =1, So the frequency = min { 2,2,2,2} = 2</p><p>In some cases due to hash collision we might get the frequency little more than what is expected to come, hence it guarantees to give the exact frequency or more. The accuracy will depend upon how unique the hash functions return the values… and also the more the hash function the more accurate will be the frequency.</p><p>In this way Count min sketch allows to calculate frequency of large data streams in sub linear space using same O(1) constant time complexity.</p><p><strong><em>Count-Min Sketches are incredibly efficient. A 1000x8 Count-Min Sketch (that is, 8 hash functions that each map to a 1000-length array), would need to store eight-thousand 32-bit integers. That’s a total of 32 KB — literally orders of magnitudes smaller than the massive 32 GB Hash Table we were contemplating earlier!</em></strong></p><p><strong>Applications</strong></p><ul><li>Compressed Sensing</li><li>Networking</li><li>Databases</li><li>NLP, Security, Machine Learning..</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8a10590fc936" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>