<?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 Praveen Kumar JV on Medium]]></title>
        <description><![CDATA[Stories by Praveen Kumar JV on Medium]]></description>
        <link>https://medium.com/@pravsjv?source=rss-a0b392eaa0ac------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*akHJcoWbO-V7C_KT</url>
            <title>Stories by Praveen Kumar JV on Medium</title>
            <link>https://medium.com/@pravsjv?source=rss-a0b392eaa0ac------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 22:29:31 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@pravsjv/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[Scaling Databases (Part 3): The Art of Scaling Reads — From Caching to Architecture]]></title>
            <link>https://medium.com/@pravsjv/scaling-databases-part-3-the-art-of-scaling-reads-from-caching-to-architecture-d5396ec3b068?source=rss-a0b392eaa0ac------2</link>
            <guid isPermaLink="false">https://medium.com/p/d5396ec3b068</guid>
            <category><![CDATA[database]]></category>
            <category><![CDATA[scaling]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <dc:creator><![CDATA[Praveen Kumar JV]]></dc:creator>
            <pubDate>Mon, 05 Jan 2026 04:14:01 GMT</pubDate>
            <atom:updated>2026-01-05T04:23:29.170Z</atom:updated>
            <content:encoded><![CDATA[<h3>Scaling Databases (Part 3): The Art of Scaling Reads — From Caching to Architecture</h3><p>In the previous parts of this series, we explored <strong>Vertical Scaling</strong> and the fundamental power of <strong>Caching</strong>. But as your application grows from thousands to millions of users, “just adding a cache” isn’t enough. You eventually hit a wall where your database becomes the bottleneck for every page load, search, and dashboard.</p><p>Scaling reads is a game of strategy. To master it, you must follow a specific hierarchy of efficiency:</p><ol><li><strong>Eliminate</strong> the read entirely.</li><li><strong>Cheapen</strong> the read if you can’t eliminate it.</li><li><strong>Parallelize</strong> the read if it’s still too heavy.</li><li><strong>Isolate</strong> the read to specialized systems.</li><li><strong>Observe and Adapt</strong> based on real-world patterns.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VVO5Z_U9_RH-o1z35yNqsw.png" /></figure><h3>1. Eliminate Reads: Moving to the Edge</h3><p>The fastest read is the one that never hits your database.</p><h3>CDN (Edge Cache)</h3><p>For immutable content (images, JS, CSS) or “cache-safe” dynamic content, <strong>CDNs</strong> are your first line of defense. Modern CDNs can now cache dynamic API responses using sophisticated <strong>cache keys</strong> and short <strong>Time-to-Live (TTL)</strong> settings.</p><p><strong>The Trade-off:</strong> You gain speed but lose <strong>cache coherency</strong>. CDNs introduce eventual consistency; a user in New York might see an old version of a post while a user in London sees the new one.</p><h3>Application Cache</h3><p>If the data must come from your backend, use an <strong>Application Cache</strong> (like Redis or Memcached) to store the results of expensive queries.</p><ul><li><strong>Strategies:</strong> Cache-aside, Read-through, Write-through, and Write-back.</li><li><strong>Failure Mode:</strong> Beware of the <strong>“Cold Start”</strong> or <strong>“Thundering Herd.”</strong> If a highly-contested cache key expires or the cache service restarts, your database can be DDoSed by thousands of simultaneous requests trying to “refill” the cache.</li></ul><h3>2. Cheapen Reads: Indexes and Denormalization</h3><p>If the query must hit the database, make it as “cheap” as possible for the engine to execute.</p><h3>The Power of Indexing</h3><p>Relational databases rely on <strong>B-Tree indexes</strong>, which are optimized for point lookups and range scans.2</p><ul><li><strong>Covering Indexes:</strong> These are the “holy grail” of performance. If an index contains all the data required for a query, the DB never has to touch the actual table.</li><li><strong>Selectivity vs. Cardinality:</strong> * <strong>Cardinality</strong> is the number of distinct values (e.g., user_id is high, gender is low).3</li><li><strong>Selectivity</strong> is what matters for performance. If a query matches more than <strong>~5–10%</strong> of a table, the database optimizer may ignore the index entirely, as a full table scan becomes faster than jumping back and forth between the index and the disk.</li></ul><h3>The N+1 Query Trap</h3><p>A common performance killer in modern apps is the <strong>N+1 problem</strong>, often caused by ORMs or microservice architectures.4 This happens when you fetch 100 orders (1 query) and then loop through them to fetch the items for each order (100 additional queries).</p><p><strong>The Fix:</strong> Use <strong>Joins</strong> (carefully), <strong>Batching</strong>, or <strong>DataLoaders</strong> to collapse those 101 queries into 2 or 3.</p><h3>3. Parallelize Reads: Replication and Sharding</h3><p>When a single machine can no longer handle the throughput, you must spread the load.</p><h3>Read Replication</h3><p>By creating “Follower” replicas, you can distribute read traffic across multiple nodes.</p><ul><li><strong>The Consistency Trade-off:</strong> Replication scales reads by trading away <strong>Strong Consistency</strong> for <strong>Availability</strong>.</li><li><strong>Replica Lag:</strong> During write spikes, followers can fall behind. If a user updates their profile and immediately refreshes, they might see their old data — a failure of <strong>Read-after-write consistency</strong>.</li></ul><h3>Sharding (Partitioning)</h3><p>While replication copies the <em>entire</em> database, <strong>Sharding</strong> splits it.5</p><ul><li><strong>Horizontal Sharding:</strong> Different rows live on different servers based on a <strong>Shard Key</strong> (e.g., user_id).</li><li><strong>The Risk:</strong> Sharding only helps if your queries are “shard-local.”6 If you have to query every shard to get one result — a <strong>Scatter-Gather</strong> pattern — your performance will plummet.</li></ul><h3>4. Isolate Reads: Specialized Systems</h3><p>Sometimes, a relational database is simply the wrong tool for the job.</p><p>For complex searching, faceting, or ranking, move your read path to a <strong>Secondary Index</strong> system like <strong>Elasticsearch</strong> or <strong>Solr</strong>. These use <strong>Inverted Indexes</strong> (similar to a book index) rather than B-Trees.</p><ul><li><strong>Warning:</strong> These systems are almost always <strong>eventually consistent</strong> and introduce <strong>dual-write complexity</strong> (you must update both the DB and the search engine).</li></ul><h3>5. Observe and Adapt: The Feedback Loop</h3><p>Scaling is not a “set it and forget it” task. You must monitor:</p><ul><li><strong>P95/P99 Latency:</strong> Don’t look at averages; look at the slowest 1% of users.</li><li><strong>Cache Hit/Miss Ratio:</strong> If your hit rate is below 80%, your cache might be poorly tuned.</li><li><strong>Replica Lag:</strong> Monitor how many seconds your followers are behind the leader.</li></ul><h3>Conclusion</h3><p>Scaling reads is an iterative process. Start by optimizing your queries and indexes, then move to caching, and only reach for replication or sharding when the hardware limits demand it.</p><p><strong>Next in the series:</strong> <em>Scaling Databases (Part 4): The Complexity of Scaling Writes — Sharding, Conflict Resolution, and Consensus.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d5396ec3b068" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Navigating the Fog: Understanding Network Partitions in Distributed Systems]]></title>
            <link>https://medium.com/@pravsjv/navigating-the-fog-understanding-network-partitions-in-distributed-systems-5daed41632d8?source=rss-a0b392eaa0ac------2</link>
            <guid isPermaLink="false">https://medium.com/p/5daed41632d8</guid>
            <category><![CDATA[network-partition]]></category>
            <category><![CDATA[fault]]></category>
            <category><![CDATA[dist]]></category>
            <category><![CDATA[cap-th]]></category>
            <dc:creator><![CDATA[Praveen Kumar JV]]></dc:creator>
            <pubDate>Sat, 03 Jan 2026 01:17:13 GMT</pubDate>
            <atom:updated>2026-02-08T15:49:43.537Z</atom:updated>
            <content:encoded><![CDATA[<p>In a perfect world, our servers would talk to each other instantaneously, and data would flow without friction. But in the reality of distributed systems, the network is not reliable. It is a chaotic environment where messages vanish, routers misconfigure, and latency spikes without warning.</p><p>This reality brings us to the most critical challenge in system design: <strong>The Network Partition.</strong></p><h3>What is a Network Partition?</h3><p>A network partition occurs when nodes in a cluster remain alive and functional but lose the ability to communicate with one another. During a partition:</p><ul><li>Messages between nodes are delayed indefinitely, dropped, or lost.</li><li>The system splits into isolated “islands” of nodes.</li></ul><p>These aren’t just theoretical edge cases. They happen frequently due to <strong>data center link failures</strong>, <strong>availability zone outages</strong>, <strong>switch/router misconfigurations</strong>, or even <strong>long Garbage Collection (GC) pauses</strong> that make a node appear dead to its peers.</p><h3>The CAP Theorem: It’s Not a Constant Choice</h3><p>A common misconception is that you are always choosing between Consistency, Availability, and Partition Tolerance. In reality, <strong>Partition Tolerance is not optional.</strong> If you are running a distributed system, partitions <em>will</em> happen.</p><p>The CAP theorem only applies when a partition occurs. Under normal operation, your system can enjoy both consistency and availability. But when the network breaks, you must choose your priority:</p><h3>1. Consistency + Partition Tolerance (CP)</h3><p>Systems that prioritize CP will <strong>reject or block requests</strong> if consistency cannot be guaranteed.</p><ul><li><strong>Trade-off:</strong> Some nodes may become unavailable.</li><li><strong>Philosophy:</strong> Guarantees <strong>correctness over uptime</strong>.</li></ul><h3>2. Availability + Partition Tolerance (AP)</h3><p>Systems that prioritize AP will <strong>continue serving requests</strong> even if they cannot reach the rest of the cluster.</p><ul><li><strong>Trade-off:</strong> Data may be temporarily inconsistent.</li><li><strong>Philosophy:</strong> Guarantees <strong>uptime over correctness</strong>, relying on eventual consistency and conflict resolution.</li></ul><h3>The Uncertainty Principle: We Cannot Detect Partitions</h3><p>One of the most fundamental constraints in distributed systems is that <strong>you cannot distinguish between a slow node, a crashed node, or a partitioned node.</strong></p><p>Failure detection is inherently probabilistic. We use heartbeats and timeouts, but these are mere guesses, not absolute truths.</p><ul><li><strong>Aggressive Timeouts:</strong> Lead to false positives (evicting healthy nodes).</li><li><strong>Conservative Timeouts:</strong> Lead to high latency and stalled systems.</li></ul><p>This uncertainty ripples through every part of the stack, impacting leader election, replication protocols, and circuit breakers.</p><h3>Linearizability vs. Availability</h3><p><strong>Linearizability</strong> is the “gold standard” of consistency — it creates the illusion that there is only one copy of the data and all operations happen atomically. However, this illusion is expensive.</p><p>Under a partition, maintaining linearizability is often impossible without sacrificing availability. Because every node must agree on the state before responding to the user, the system must block or fail if communication is cut. In short: <strong>Linearizability and availability are fundamentally at odds in the presence of partitions.</strong></p><h3>Quorums: The Practical CAP Mechanism</h3><p>How do we actually implement these trade-offs? We use <strong>Quorums</strong>. By defining how many nodes must agree on a read or write, we can tune our system’s behavior.</p><p>Let N be the replication factor. We define W (write quorum) and R (read quorum).</p><ul><li><strong>Strong Consistency:</strong> If R + W &gt; N, you are guaranteed to read the latest write because the read and write sets will always overlap.</li><li><strong>Weak Consistency:</strong> If R + W &lt; N, you may read stale data, but the system will be faster and more available.</li></ul><h3>The “Split Brain” Nightmare</h3><p>When a partition occurs, a system might end up with two “leaders” in different islands, both thinking they have the authority to process writes. This “split brain” scenario leads to catastrophic data corruption.</p><p>To mitigate this, we use:</p><ul><li><strong>Fencing Tokens:</strong> A monotonically increasing number issued with a lock. Every storage operation checks this token; if a request comes in with an old token, it is rejected.</li><li><strong>Epoch Numbers:</strong> A logical clock that identifies the “generation” of leadership. When a new leader is elected, the epoch increments, rendering the old leader’s commands invalid.</li><li><strong>Consensus Algorithms:</strong> Using Raft or Paxos ensures that a leader can only be elected if they have a majority ($&gt; N/2$) of votes.</li></ul><h3>Consensus and Conflict Resolution</h3><h3>The CP Approach: Consensus</h3><p>Consensus algorithms like <strong>Raft</strong> or <strong>Paxos</strong> are designed for CP. They require a majority to make progress. If a partition leaves a minority of nodes isolated, those nodes will stop serving writes to preserve correctness.</p><h3>The AP Approach: Conflict Resolution</h3><p>If your system must stay available (AP), you accept that writes will happen in different partitions. This makes conflicts inevitable. The responsibility then shifts to <strong>Conflict Resolution</strong>, which must be deterministic:</p><ul><li><strong>Last Write Wins (LWW):</strong> Simple but can lose data.</li><li><strong>CRDTs (Conflict-free Replicated Data Types):</strong> Data structures that merge automatically.</li><li><strong>Version Vectors:</strong> Tracking the history of changes.</li></ul><p>Ultimately, <strong>conflict resolution is an application semantics problem</strong>, not a storage problem. Only the application truly knows how to merge two different versions of a shopping cart or a user profile.</p><h3>Final Thoughts</h3><p>Building distributed systems isn’t about avoiding failures — it’s about choosing how you want to fail. Do you stop the world to ensure the truth, or do you keep moving and clean up the mess later? There is no right answer, only the trade-off that fits your business needs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5daed41632d8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scaling Databases (Part 2): Caching — The Performance Multiplier with Hidden Trade-offs]]></title>
            <link>https://medium.com/@pravsjv/scaling-databases-part-2-caching-the-performance-multiplier-with-hidden-trade-offs-1e83d8ed1cb7?source=rss-a0b392eaa0ac------2</link>
            <guid isPermaLink="false">https://medium.com/p/1e83d8ed1cb7</guid>
            <category><![CDATA[scalability]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[Praveen Kumar JV]]></dc:creator>
            <pubDate>Mon, 29 Dec 2025 03:31:45 GMT</pubDate>
            <atom:updated>2025-12-29T03:31:45.118Z</atom:updated>
            <content:encoded><![CDATA[<h3>Scaling Databases (Part 2): Caching — The Performance Multiplier with Hidden Trade-offs</h3><p>Caching is one of the most effective — and deceptively complex — techniques for improving system performance. At a high level, caching reduces latency, lowers backend load, and increases throughput by serving frequently accessed data from faster storage layers. It is often the first optimization engineers reach for when systems start to strain under load.</p><p>However, caching is not a free optimization. It introduces correctness risks, consistency trade-offs, and distributed systems challenges that must be consciously designed for. Poorly designed caches can degrade reliability, violate user expectations, and amplify failures rather than absorb them.</p><p>At scale, caching is less about <em>where</em> data is stored and more about <em>how</em> freshness, correctness, and failure are managed.</p><h3>The Three Layers of Caching</h3><p>In modern systems, caching typically manifests across three distinct layers:</p><ol><li><strong>Application-level caches</strong></li><li><strong>Database-integrated caches</strong></li><li><strong>Distributed caches</strong></li></ol><p>Each layer serves a different purpose and comes with its own strengths, limitations, and failure modes.</p><h3>Application-Level Cache</h3><p>Application-level caching is the most common and flexible form of caching. It is managed directly by the application and typically stored in-memory using local data structures, libraries, or framework abstractions.</p><h3>Common Examples</h3><ul><li>In-process maps and LRU caches</li><li>Framework-level caching (e.g., Spring Cache, Guava Cache)</li><li>Custom memoization logic embedded in application code</li></ul><h3>Strengths</h3><ul><li><strong>Lowest latency</strong>: No network hop; data is accessed directly from memory.</li><li><strong>Fine-grained control</strong>: Developers decide exactly what to cache, when, and why.</li><li><strong>Context-aware caching</strong>: Application logic can incorporate request context, user identity, or business semantics into cache decisions.</li></ul><h3>Risks and Challenges</h3><ul><li><strong>Cache invalidation</strong>: The hardest problem in computer science. Stale reads, hidden coupling, and complex invalidation logic are common — especially in write-heavy systems.</li><li><strong>Horizontal scaling issues</strong>:</li><li>Inconsistent cache views across instances</li><li>Difficulty supporting read-your-writes guarantees</li><li>Increased divergence as the number of instances grows</li></ul><p>Application-level caches are powerful, but they scale poorly when consistency across nodes becomes a requirement rather than a convenience.</p><h3>Database-Integrated Cache</h3><p>Database-integrated caches operate below the application layer and are managed entirely by the database engine or operating system.</p><h3>Common Examples</h3><ul><li>Database buffer pools</li><li>OS-level page cache</li><li>Internal query caches</li></ul><h3>Strengths</h3><ul><li><strong>Transparent to the application</strong>: No application-level logic required.</li><li><strong>Stronger consistency guarantees</strong>: Cache coherence is handled by the database.</li><li><strong>Operational simplicity</strong>: Fewer moving parts and lower cognitive overhead.</li></ul><h3>Trade-offs</h3><ul><li><strong>Limited flexibility</strong>: Applications cannot fine-tune caching behavior.</li><li><strong>Less targeted optimization</strong>: These caches optimize general access patterns, not specific business use cases.</li></ul><p>Database-integrated caching is often the safest default and provides substantial performance benefits without introducing application-level complexity.</p><h3>Distributed Cache (Redis, Memcached)</h3><p>Distributed caches introduce a separate, network-accessible caching tier shared across multiple application instances.</p><h3>Common Use Cases</h3><ul><li>Read-heavy workloads</li><li>Frequently accessed keys (hot keys)</li><li>Reducing load on primary databases</li></ul><h3>Strengths</h3><ul><li><strong>Shared cache across instances</strong>: Enables consistency at the cache layer.</li><li><strong>Independent scalability</strong>: Cache capacity and throughput scale separately from the application.</li><li><strong>Effective database offloading</strong>: Particularly valuable for read-dominated traffic.</li></ul><h3>The Hidden Cost</h3><p>Once a cache is distributed, it inherits <em>all the failure modes of distributed systems</em>:</p><ul><li>Network partitions</li><li>Partial failures</li><li>Increased tail latency</li><li>Consistency trade-offs</li></ul><p>Distributed caches are powerful, but they demand careful design, monitoring, and operational discipline.</p><h3>The Thundering Herd Problem</h3><p>One of the most common — and damaging — failure modes in caching systems is the <strong>Thundering Herd Problem</strong>.</p><h3>The Problem</h3><p>When:</p><ul><li>A popular cache entry expires, or</li><li>A cache node fails</li></ul><p>Multiple concurrent requests may simultaneously attempt to recompute and reload the same value from the database. This can:</p><ul><li>Overwhelm the database</li><li>Trigger cascading failures</li><li>Completely eliminate the intended benefit of caching</li></ul><h3>Mitigation Strategies</h3><ul><li><strong>Request coalescing</strong>: Ensure only one request recomputes a missing value while others wait for the result.</li><li><strong>Probabilistic early expiration</strong>: Expire cache entries slightly before their TTL, randomly, to smooth refresh traffic.</li><li><strong>Background refresh</strong>: Refresh cache entries asynchronously instead of blocking user requests on recomputation.</li></ul><p>These techniques shift caching from a passive optimization to an actively managed subsystem.</p><h3>Closing Thoughts</h3><p>Caching is fundamentally a trade-off:</p><blockquote><strong><em>“Caching trades freshness and complexity for performance.”</em></strong></blockquote><p>As caches grow larger, more shared, and more critical to system behavior, they stop being simple performance accelerators and start behaving like distributed systems themselves.</p><blockquote><strong><em>“The larger and more shared a cache becomes, the more it behaves like a distributed system.”</em></strong></blockquote><p>Designing effective caching strategies requires more than choosing the right tool. It requires clarity around consistency guarantees, failure handling, and operational boundaries. When done well, caching can unlock orders-of-magnitude performance gains. When done poorly, it can quietly undermine the correctness and reliability of the entire system.</p><p>Understanding these trade-offs is what separates scalable systems from fragile ones.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1e83d8ed1cb7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scaling Databases (Part 1): Vertical Scaling and Its Hard Limits]]></title>
            <link>https://medium.com/@pravsjv/scaling-databases-part-1-vertical-scaling-and-its-hard-limits-9062036a3303?source=rss-a0b392eaa0ac------2</link>
            <guid isPermaLink="false">https://medium.com/p/9062036a3303</guid>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[scalability]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[Praveen Kumar JV]]></dc:creator>
            <pubDate>Sat, 27 Dec 2025 17:13:43 GMT</pubDate>
            <atom:updated>2025-12-27T17:13:43.064Z</atom:updated>
            <content:encoded><![CDATA[<p>Vertical scaling, commonly referred to as <em>scaling up</em>, is one of the earliest and most intuitive approaches to improving system performance. The idea is straightforward: instead of distributing work across multiple machines, the database is run on a more powerful single machine by adding CPU cores, memory, faster disks, or higher network bandwidth.</p><p>While vertical scaling is attractive and often highly effective in practice, <em>Designing Data-Intensive Applications (DDIA)</em> makes it clear that its limitations and long-term risks are unavoidable.</p><p><strong>Why Vertical Scaling Is Attractive</strong></p><p>The primary advantage of vertical scaling is that it preserves a single node mental model, which dramatically simplifies system design and operation. A single node system avoids many of the complexities that dominate distributed systems:<br>- No distributed transactions: All reads and writes occur within one process and one memory space. This avoids the need for two-phase commit, consensus protocols, or cross-node coordination.<br>- No partial failures: In distributed systems, individual nodes can fail independently, leading to split brain scenarios and degraded correctness. A single node system either works or it does not.<br>- No coordination overhead: Eliminates the need for leader election, quorum reads, replication lag handling or clock synchronization.</p><p>Because of this simplicity, vertical scaling is often fastest way to:<br>- improve latency<br>- increase throughput<br>- reduce architectural complexity<br>- accelerate early stage development</p><p><strong>Contention Does Not Disappear:</strong><br>Vertical scaling doesn’t eliminate contention but postpones it. As we increase the resources, new bottlenecks emerge:<br>CPU Contention: <br> — locks and latches protecting shared data structures<br> — mutex contention in query execution engines<br> — context switching overhead with many concurrent threads</p><p>Memory Bandwidth Contention:<br> — modern CPUs often share memory controllers<br> — large number of cores competing for memory access lead to diminishing returns<br> — cache coherence traffic increases dramatically on large machines</p><p>Disk I/O Queue Contention:<br> — even fast NVMe drives have finite queue depths<br> — high write amplification and fsync-heavy workloads saturate I/O paths<br> — I/O schedulers and kernel queues become bottlenecks</p><p>A single machine still has shared resources, and those shared resources fundamentally limit scalability.</p><p><strong>Amdahl’s Law and Diminishing Returns</strong></p><blockquote>If a fraction of a system is inherently serial, overall speedup is bounded regardless of how much you scale the parallel part.</blockquote><p>In databases, this law manifests clearly because many critical operations remain fundamentally serial.<br>Serial Parts in Databases:<br>- transaction coordination<br>- log writing<br>- lock acquisition<br>- index maintenance</p><p>As machine get larger:<br>- each additional CPU core contributes less incremental throughput<br>- performance improvements flatten rapidly<br>- cost per unit of performance increases sharply</p><p><strong>Single-Node Fragility: Limits beyond performance</strong><br> Kernel Scheduling Limits:<br> — scheduler overhead increases with thread count<br> — run queues become congested<br> — context switching costs grow non-linearly</p><p>NUMA Effects:<br> On multi-socket servers:<br> — memory access latency varies by CPU socket<br> — poor NUMA-aware design leads to cross-socket memory access<br> — performance becomes unpredictable and difficult to tune</p><p>Single Point of Failure:<br> — hardware failure takes down the entire system<br> — maintenance windows require full downtime unless replication exists<br> — recovery time tied to restoring a large, monolithic node</p><p><strong>When Vertical Scaling Still Makes Sense</strong><br>- workloads are well understood and bounded<br>- latency requirements favor single-node execution<br>- operational simplicity is paramount<br>- replication is used primarily for availability, not throughput</p><blockquote>“Vertical Scaling is a temporary optimization, not a long-term scaling strategy”</blockquote><p>Vertical Scaling offers elegance through simplicity, but physics, operating systems, and shared resources impose hard limits on single-node systems.</p><p><strong>Conclusion:</strong><br>Scaling up delays complexity — but it does not eliminate it. Systems that grow successfully eventually have to confront distribution, coordination, and failure as first-class concerns.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9062036a3303" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unmasking Latency: How API tracing supercharges Microservices troubleshooting]]></title>
            <link>https://medium.com/@pravsjv/unmasking-latency-how-api-tracing-supercharges-microservices-troubleshooting-3f2d84de300b?source=rss-a0b392eaa0ac------2</link>
            <guid isPermaLink="false">https://medium.com/p/3f2d84de300b</guid>
            <category><![CDATA[latency]]></category>
            <category><![CDATA[restful-web-service]]></category>
            <category><![CDATA[api-tracing]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Praveen Kumar JV]]></dc:creator>
            <pubDate>Wed, 01 Jan 2025 16:55:02 GMT</pubDate>
            <atom:updated>2025-01-01T16:55:02.839Z</atom:updated>
            <content:encoded><![CDATA[<p>In today’s landscape, many organizations rely on microservices architecture to power their applications. Microservices offer greater scalability, flexibility, and resilience. However, it also introduces new challenges particularly when it comes to troubleshooting the latency and performance of the applications.</p><blockquote>Latency is the delay or time taken for a request to travel from the source to the destination and for a response to be received.</blockquote><p>I was recently assigned a task to investigate a performance issue in our Big Data application which powers real-time risk assessment which is crucial for timely decison making. The application uses a combination of Spring Boot microservices, Trino, Iceberg catalog, and Flink for stream processing deployed in Microservices architecture. The APIs were taking too much time to complete their execution and a significant latency is observed.</p><p>With the complexity of microservices architecture involved, I knew troubleshooting could be challenging. So I started investigating the issue by looking at the logs and other metrics, but they didn’t offer much insight since our architecture is distributed.</p><p>After spending some time evaluating the need for better visibility into our system’s performance, I decided to implement <strong>API tracing</strong> across all layers. To achieve this, I began exploring and evaluating various tools, including <strong>Jaeger</strong>, <strong>Zipkin</strong>, <strong>Spring Cloud Sleuth</strong>, and <strong>OpenTelemetry</strong>.</p><p><strong>API tracing</strong> is a technique used to monitor and track the flow of requests as they pass through multiple services or components in a distributed system. In microservices architectures, where an API call may interact with multiple services, tracing allows you to follow the request from start to finish, capturing detailed performance data along the way. This provides valuable insights into where delays, failures, or bottlenecks occur.</p><blockquote>API tracing assigns unique trace IDs to each request, allowing you to track its flow across services, databases, and APIs.. These identifiers are passed from one service to the next, allowing each service to log its part of the process. The result is a detailed trace of the request’s lifecycle across services, databases, caches, and third-party APIs.</blockquote><p>As it’s a Spring Boot application, Spring-sleuth dependencies and Zipkin worked fine and added logic to create trace ids’ for each of the API calls.</p><p><strong>Observations:</strong></p><ul><li><strong>Spring Boot Microservices</strong>: The request processing by the Spring Boot APIs was efficient, with minimal overhead. However, when the API initiated a query to <strong>Trino</strong>, significant delays were observed.</li><li><strong>Trino &amp; Iceberg</strong>: This is where things started to get interesting. Trino was performing <strong>inefficient scans</strong> across multiple Iceberg partitions rather than narrowing the query to the most relevant data. This was a major contributor to the latency.</li><li><strong>Flink</strong>: The stream processing was mostly efficient, but there was a small but noticeable delay in data ingestion before it was written to Iceberg. This added a bit of time to the overall pipeline.</li><li><strong>Redis</strong>: Redis was not serving cached data as expected. I found that Redis was querying the backend data sources too frequently instead of using the cached results, which added unnecessary load on the system.</li></ul><p><strong>Conclusion:</strong></p><p>With the insights gained from the <strong>trace data</strong>, I was able to make <strong>targeted improvements</strong> by:</p><ol><li><strong>Optimizing database queries</strong>,</li><li><strong>Adjusting the Flink pipeline</strong> for faster data ingestion,</li><li><strong>Enhancing the caching strategy</strong>.</li></ol><p>After implementing these changes, the results were <strong>immediate and impactful</strong>: query times dropped from <strong>several minutes to just a few seconds</strong>, significantly boosting the application’s performance.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3f2d84de300b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Eager Initialization in the Singleton Pattern]]></title>
            <link>https://medium.com/@pravsjv/understanding-eager-initialization-in-the-singleton-pattern-73fb4e564290?source=rss-a0b392eaa0ac------2</link>
            <guid isPermaLink="false">https://medium.com/p/73fb4e564290</guid>
            <category><![CDATA[singleton]]></category>
            <category><![CDATA[thread-safe-singleton]]></category>
            <category><![CDATA[eager-initialization]]></category>
            <dc:creator><![CDATA[Praveen Kumar JV]]></dc:creator>
            <pubDate>Tue, 31 Dec 2024 17:35:25 GMT</pubDate>
            <atom:updated>2024-12-31T17:35:25.360Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>After covering the introduction and its use cases for Singleton here <a href="https://medium.com/@pravsjv/understanding-the-singleton-design-pattern-in-software-engineering-db34e1875e24">understanding-the-singleton-design-pattern-in-software-engineering</a>, let’s explore its eager initialization implementation.</blockquote><p><strong>Eager Initialization(Thread Safe):</strong> In this approach, Singleton instance is created at the time of class loading ensuring thread safety. The instance is created as soon as the class is loaded into the memory even if the instance was never used. Let’s see its implementation in java.</p><pre>public class Singleton {<br>    // Eagerly creating the instance of the Singleton<br>    private static final Singleton INSTANCE = new Singleton();<br><br>    // Private constructor to prevent external instantiation<br>    private Singleton() { }<br><br>    // Public method to provide access to the instance<br>    public static Singleton getInstance() {<br>        return INSTANCE;<br>    }<br>}</pre><p><strong>How it works:</strong></p><ul><li>The Instance is created as soon as the class is loaded by JVM.</li><li>The constructor is private to prevent instantiation from outside the class. This is a crucial part of the Singleton pattern to ensure only one instance can be created.</li><li>The getInstance() method returns the single instance of the class.</li></ul><p><strong>Why is this implementation Thread Safe:</strong></p><p>JVM by default ensures class loading thread-safe. The thread-safety of class loading means that when multiple threads are trying to load the same class, the JVM ensures that the class is loaded <strong>only once</strong>. It handles synchronization in such a way that only one thread can load a class at a time, even if multiple threads attempt to load the same class concurrently.</p><p><strong>Conclusion:</strong></p><p>Eager initialization is simple, thread-safe, and works well if you’re certain that the Singleton instance will be used throughout the lifetime of the application. However, if the Singleton might not be used, it could lead to unnecessary memory consumption. In such cases use Lazy Initialization.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=73fb4e564290" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding the Singleton Design Pattern in Software Engineering]]></title>
            <link>https://medium.com/@pravsjv/understanding-the-singleton-design-pattern-in-software-engineering-db34e1875e24?source=rss-a0b392eaa0ac------2</link>
            <guid isPermaLink="false">https://medium.com/p/db34e1875e24</guid>
            <category><![CDATA[use-cases]]></category>
            <category><![CDATA[singleton-design-pattern]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Praveen Kumar JV]]></dc:creator>
            <pubDate>Tue, 31 Dec 2024 14:31:54 GMT</pubDate>
            <atom:updated>2024-12-31T14:31:54.196Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Introduction:</strong></p><p>The <strong>Singleton Design Pattern</strong> is one of the most widely used creational design patterns. It ensures that a class has only one instance and provides a global point of access to that instance. This pattern is particularly useful in scenarios where a single object is required to coordinate actions across a system.</p><h4>When to Use the Singleton Design Pattern:</h4><p>The Singleton Pattern is commonly applied in the following situations:</p><ul><li><strong>Global Access to Shared Resources</strong>: When a resource needs to be shared globally throughout an application.</li><li><strong>Controlling Access to Shared Data</strong>: To prevent multiple instances from causing inconsistency or race conditions.</li><li><strong>Resource-Intensive Object Creation</strong>: When creating an object is expensive in terms of memory or processing, and you want to avoid unnecessary instantiation.</li><li><strong>Managing Shared State</strong>: For applications that require a consistent, globally accessible state.</li><li><strong>Preventing Multiple Instantiations</strong>: To ensure that only one instance of a class exists in the entire application.</li></ul><h4>Use Cases of Singleton Design Pattern</h4><p>Here are some practical examples where the Singleton Pattern can be beneficial:</p><ol><li><strong>Logging System: </strong>In large systems, logging often requires global access. If multiple components of the system create different instances of a logging service, this can lead to inconsistent formats, redundancy, or difficulty managing the log output. The Singleton pattern ensures that only one instance of the logger is created, promoting consistency, single responsibility, and better performance.</li></ol><pre>public class Logger {<br>    private static final Logger instance = new Logger();<br><br>    private Logger() { }<br><br>    public static Logger getInstance() {<br>        return instance;<br>    }<br><br>    public void log(String message) {<br>        // Write message to a log file or console<br>        System.out.println(message);<br>    }<br>}</pre><p><strong>Advantages</strong>: Consistent logging, performance improvements (by avoiding multiple instances), and ease of use.</p><p><strong>2. Configuration Settings</strong>Many applications need to manage configuration settings (such as config.properties) globally across the system. Without a Singleton, you might end up with inconsistent settings, multiple reads from a configuration file, or redundant database calls. The Singleton ensures a single point of access for configuration management.</p><pre>public class ConfigurationManager {<br>    private static ConfigurationManager instance;<br>    private Properties config;<br><br>    private ConfigurationManager() {<br>        // Load configuration from a file or database<br>        config = new Properties();<br>        // Example: config.load(new FileInputStream(&quot;config.properties&quot;));<br>    }<br><br>    public static ConfigurationManager getInstance() {<br>        if (instance == null) {<br>            instance = new ConfigurationManager();<br>        }<br>        return instance;<br>    }<br><br>    public String getConfig(String key) {<br>        return config.getProperty(key);<br>    }<br>}</pre><p><strong>Advantages</strong>: Lazy initialization, global access to configuration, and consistent settings management.</p><p><strong>3. Database Connection Pooling: </strong>Establishing new database connections can be expensive in terms of both time and resources. By using a Singleton for a connection pool, you ensure that only one instance of the connection pool is created. This centralized pool can be reused, which leads to better resource management, improved performance, and thread safety.</p><pre>public class ConnectionPool {<br>    private static ConnectionPool instance;<br>    private List&lt;Connection&gt; connections;<br><br>    private ConnectionPool() {<br>        // Initialize and populate the connection pool<br>        connections = new ArrayList&lt;&gt;();<br>        // Example: initialize connections with database credentials<br>    }<br><br>    public static ConnectionPool getInstance() {<br>        if (instance == null) {<br>            instance = new ConnectionPool();<br>        }<br>        return instance;<br>    }<br><br>    public Connection getConnection() {<br>        // Logic to return a connection from the pool<br>        return connections.get(0);  // Example; should implement more complex pooling logic<br>    }<br>}</pre><p><strong>Advantages</strong>: Efficient resource usage, thread safety, centralized management of connections.</p><p><strong>4. Cache Manager: </strong>Many modern applications rely on caching to reduce repetitive tasks like database queries. A Singleton Cache Manager ensures that all parts of the application use a single cache instance, avoiding unnecessary duplication of data, conserving memory, and maintaining a consistent cached state.</p><pre>public class CacheManager {<br>    private static CacheManager instance;<br>    private Map&lt;String, Object&gt; cache;<br><br>    private CacheManager() {<br>        cache = new HashMap&lt;&gt;();<br>    }<br><br>    public static CacheManager getInstance() {<br>        if (instance == null) {<br>            instance = new CacheManager();<br>        }<br>        return instance;<br>    }<br><br>    public Object get(String key) {<br>        return cache.get(key);<br>    }<br><br>    public void put(String key, Object value) {<br>        cache.put(key, value);<br>    }<br>}</pre><p><strong>Advantages</strong>: Memory efficiency, single source of truth, and better application performance.</p><h3>Additional Considerations</h3><p>While the Singleton pattern can be useful in many scenarios, it should be used with caution:</p><ol><li><strong>Global State Issues</strong>: Since the Singleton pattern provides global access to an instance, it can introduce tight coupling between components, making it harder to manage dependencies and test the application.</li><li><strong>Thread Safety</strong>: In multi-threaded environments, care must be taken to ensure that the Singleton instance is created in a thread-safe manner (e.g., using synchronized or double-checked locking).</li><li><strong>Testing</strong>: Singleton can be hard to test because it creates a global instance. When testing, consider using dependency injection or mocking frameworks to better control the instance.</li><li><strong>Lazy Initialization</strong>: The lazy initialization approach can introduce potential race conditions. A double-checked locking mechanism or an enum-based Singleton can help mitigate these issues.</li></ol><h3>Conclusion</h3><p>The Singleton Design Pattern is a powerful tool when you need a single, globally accessible instance of a class in your system. It is especially useful for managing shared resources, ensuring consistency, and optimizing performance. However, like all design patterns, it should be used judiciously. Overusing Singleton can lead to problems related to global state, tight coupling, and testing difficulties. Consider the specific needs of your application before deciding to implement this pattern.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=db34e1875e24" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Design Cache]]></title>
            <link>https://medium.com/@pravsjv/design-cache-4b6cd32a5492?source=rss-a0b392eaa0ac------2</link>
            <guid isPermaLink="false">https://medium.com/p/4b6cd32a5492</guid>
            <category><![CDATA[cache]]></category>
            <category><![CDATA[system-design-caching]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <dc:creator><![CDATA[Praveen Kumar JV]]></dc:creator>
            <pubDate>Wed, 29 Nov 2023 20:59:14 GMT</pubDate>
            <atom:updated>2023-11-29T20:59:14.069Z</atom:updated>
            <content:encoded><![CDATA[<p>To gain a comprehensive understanding of cache design principles, refer to the following article: <a href="https://medium.com/@pravsjv/delving-into-distributed-cache-a-comprehensive-guide-d12d70a620e3">https://medium.com/@pravsjv/delving-into-distributed-cache-a-comprehensive-guide-d12d70a620e3</a></p><blockquote><strong>Requirements:</strong></blockquote><p><strong>Functional Requirements:</strong></p><ul><li>Insert Data</li><li>Retrieve Data</li></ul><p><strong>Non-Functional Requirements:</strong></p><ul><li>high Performance</li><li>Scalability</li><li>High Availability</li><li>Consistency</li><li>Affordability</li></ul><blockquote><strong>API Design:</strong></blockquote><ul><li>Insert: /v1/insert : insert(key,value)</li><li>Retrieve: /vi/get : get(key)</li></ul><p>** To persist the cache data to avoid loading the cache data(if it&#39;s large) if there is any boot, it&#39;s better to have secondary data storage even though the reads are served from RAM.</p><blockquote><strong>High-Level Design:</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t_XYCNuMW8y37hiHLlD37g.png" /></figure><blockquote><strong>Detailed Design:</strong></blockquote><ul><li>How does the cache client realize the addition or failure of a cache server?</li></ul><p><strong>Maintain a cache server list:</strong></p><ul><li><em>Config file at all cache clients:</em> contains the cache server list, update health and metadata. A service can push this file to all the clients but the shortcoming is that it is manual operation.</li><li><em>Config file at a central location:</em> all cache clients read this file. But still, it&#39;s a manual operation even though a service is not required.</li><li><em>Configuration Service:</em> automatically and continuously monitors the health of the server and updates the config list. Robust but complex.</li></ul><p><strong>Hot Key problem(High Availability):</strong></p><ul><li>Add replica nodes to avoid SPOF and for faster reads.</li><li>One master node with 2 backup nodes in a cached shard.</li><li>Discuss about the replication lag and synchronous and asynchronous data transfer and synchronous communication suits better for this use case.</li></ul><p><strong>Data Structures:</strong></p><ul><li>HashMap: to store and or locate different entries from the cache server</li><li>Doubly Linked List: To evict the data or order the data based on the eviction policy, we need a doubly linked list as it offers constant time for the addition and removal of the entries.</li><li>Eviction Policy: depends on the application</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M4JbBqIGZEJtiYtRTumRwg.png" /></figure><p><strong>Flow:</strong></p><ul><li>User requests/posts the data</li><li>Load-Balancer distributes the data to Cache Client</li><li>Cache Client using a specific flavor(similar to used in dynamo database) of consistent hashing determines which cache server can handle the request. Also takes the cache server list from configuration service.</li><li>Cache Server has read replicas that serve this data.</li><li>Monitoring service is included that could handle logging data, metrics to improve the cache performance.</li></ul><blockquote><strong>Non-Functional:</strong></blockquote><p>High Performance:</p><ul><li>Consistent Hashing for finding the right cache server. Use algorithms that returns the key in O(LogN) time</li><li>HashMap/HashTables are used to locate the keys in cache server which is a constant time access</li><li>Doubly Linked List is used to manage the addition and eviction of the data which is constant time access.</li><li>HotKey problem is addressed by sharding</li><li>As data is served from RAM, the latency is minimal</li></ul><blockquote>To get an idea of how important an eviction algorithm is :</blockquote><blockquote>cache hit service: 99.99th percentile: 5ms</blockquote><blockquote>Cache Miss Service: 99.99th percentile: 30ms</blockquote><p><strong>Scalability:</strong></p><ul><li>cache servers and cache clients can be scaled</li><li>Shards within the key range and adding replicas can be increased based on the hotkeys and metrics from the monitoring system</li></ul><p><strong>High Availability:</strong></p><ul><li>Adding replicas using a leader-follower approach avoids the SPOF and thereby increases the availability</li></ul><p><strong>Consistency:</strong></p><ul><li>We can discuss async and sync updates to master and slaves. Sync helps in strong consistency but systems like cache should be performant, hence async replication is preferred</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4b6cd32a5492" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Real-time Communication: The Power of WebSockets]]></title>
            <link>https://medium.com/@pravsjv/real-time-communication-the-power-of-websockets-f24192124f89?source=rss-a0b392eaa0ac------2</link>
            <guid isPermaLink="false">https://medium.com/p/f24192124f89</guid>
            <category><![CDATA[websocket-api]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[websocket]]></category>
            <dc:creator><![CDATA[Praveen Kumar JV]]></dc:creator>
            <pubDate>Fri, 24 Nov 2023 05:44:46 GMT</pubDate>
            <atom:updated>2023-11-24T05:44:46.039Z</atom:updated>
            <content:encoded><![CDATA[<p>In today’s dynamic web landscape, applications demand seamless, real-time communication between users. Imagine building a chat application like WhatsApp or Telegram, where users instantly exchange messages or an online multiplayer game where players collaborate in real-time. How do we achieve this level of interactive communication? The answer lies in WebSockets, a powerful protocol that revolutionizes web communication.</p><p><strong>Why not a traditional Web communication?</strong></p><p>As we know traditional web communication relies on the HTTP protocol discussed in our previous article, which involves a request-response model. While this mode of communication is effective for static content, it falls short when it comes to real-time interactions. As HTTP is stateless, each message exchange requires a new connection, adding to latencies and performance. This makes HTTP unsuitable for applications that demand continuous data sharing and uninterrupted communication.</p><p><strong>Enter Web Sockets: The Paradigm Shift</strong></p><p>Web Sockets addresses the above limitation of HTTP by establishing a bi-directional communication channel between a web client and a web server. Unlike HTTP protocol, Web Sockets require a single connection throughout the session, enabling real-time data exchange and low-latency communication.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*nkZduKtHB_GCCqGFfpR6tA.png" /></figure><p><strong>Key Features of Web Sockets:</strong></p><ul><li>Full-Duplex communication: allows both client and server to send messages simultaneously enabling seamless real-time communication</li><li>Persistent Connections: Creates a single connection that persists throughout the communication session eliminating the overhead of creating new sessions.</li><li>Low Latency: designed for low latency communication making them ideal for responsive applications</li><li>Bi-directional communication: Both client and server can initiate message exchanges facilitating event-driven applications</li><li>Structured Data Transfer: employ a framing protocol to structure messages, ensuring data integrity and preventing message collisions.</li></ul><p><strong>Real-Time Applications:</strong></p><ul><li>Chat Applications: chat applications like WhatsApp, Telegram, and Slack enable instant message exchanges</li><li>Collaborative Editing Tools: Google Docs, ether pad etc., allow multiple users to modify the content simultaneously</li><li>Multi-Player games: essential for online multiplayer games like Fortinet, Pubg, etc., enabling real-time synchronization of player actions and game states.</li><li>Stock Tickers: provides real-time stock updates</li><li>IoT communication: facilitates real-time monitoring and control between IoT devices and servers.</li></ul><p>Before concluding, we should be aware that great power comes with added complexity. WebSockets introduce additional layers of abstraction, necessitating the implementation of framing protocols to structure messages, handling concurrent client connections efficiently, and employing fallback mechanisms for scenarios where WebSockets are not supported. Additionally, careful capacity planning is crucial to ensure that the WebSocket infrastructure can scale effectively as the number of connected clients grows.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f24192124f89" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Delving into Distributed Cache: A Comprehensive Guide]]></title>
            <link>https://medium.com/@pravsjv/delving-into-distributed-cache-a-comprehensive-guide-d12d70a620e3?source=rss-a0b392eaa0ac------2</link>
            <guid isPermaLink="false">https://medium.com/p/d12d70a620e3</guid>
            <category><![CDATA[caching]]></category>
            <category><![CDATA[distributed-cache]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <dc:creator><![CDATA[Praveen Kumar JV]]></dc:creator>
            <pubDate>Thu, 23 Nov 2023 01:49:59 GMT</pubDate>
            <atom:updated>2023-11-23T01:49:59.281Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2tdLE0VwQYnGBN2cUxhC3Q.png" /></figure><p><strong>Introduction</strong></p><p>In the fast-paced realm of web applications, performance is paramount. To address the performance bottlenecks that arise from frequent data access, distributed caching has emerged as a powerful solution. This article delves into the intricacies of distributed caching, exploring its concepts, implementation strategies, and functional requirements.</p><p><strong>What is a Distributed Cache?</strong></p><p>At its core, distributed caching is a caching mechanism that utilizes multiple cache servers, strategically dispersed across a distributed system. This approach contrasts with traditional single-server caching, offering enhanced scalability, fault tolerance, and performance.</p><p><strong>Key Concepts in Distributed Cache</strong></p><ol><li>Cache Hit: When a client requests data, the application server attempts to retrieve it from the cache. If the data is present, it’s a cache hit, resulting in faster response times.</li><li>Cache Miss: If the requested data is not found in the cache, it’s a cache miss. In this scenario, the request is routed to the database, potentially introducing latency.</li><li>Cache Invalidation: To maintain data consistency, stale cache entries need to be identified and removed. This process is known as cache invalidation.</li></ol><p><strong>Why Distributed Cache?</strong></p><ol><li>Avoiding Single Points of Failure (SPOFs): Distributed caching eliminates the reliance on a single cache server, preventing performance degradation or data loss in case of server failures.</li><li>Scalability: As data volumes and user traffic increase, distributed caching can seamlessly scale by adding more cache servers, ensuring optimal performance.</li><li>Reduced Latency: By storing frequently accessed data in the cache, distributed caching reduces the load on databases, leading to faster response times and improved user experience.</li></ol><p><strong>Layers of Distributed Cache</strong></p><ol><li>Web Cache: Accelerates the retrieval of static web content and manages user sessions.</li><li>Application Cache: Provides local caching and key-value data storage within the application layer.</li><li>Database Cache: Reduces data retrieval latency and I/O from the database, improving application performance.</li><li>Knowledge Base Cache: Enhances query performance by caching frequently accessed knowledge base data.</li></ol><p><strong>Cache Writing Policies</strong></p><ol><li>Write-Through Cache: Data is written to both the cache and database simultaneously, ensuring strong consistency but potentially introducing write latency.</li><li>Write-Back Cache: Data is initially written to the cache, and updates to the database occur asynchronously. While offering lower latency, this approach may lead to stale data reads.</li><li>Write-Around Cache: Data is written directly to the database, and cache updates are triggered on subsequent read requests. This policy prioritizes write latency but may result in cache misses.</li></ol><p><strong>Cache Eviction Policies</strong></p><p>As cache memory is limited, eviction policies determine which data to retain and which to remove. Common eviction policies include:</p><ol><li>Least Recently Used (LRU): Evicts the least recently accessed data.</li><li>Most Recently Used (MRU): Evicts the most recently accessed data, assuming it’s more likely to be accessed again soon.</li><li>Least Frequently Used (LFU): Evicts the data with the lowest frequency of access.</li><li>Most Frequently Used (MFU): Evicts the data with the highest frequency of access, assuming it’s less likely to be accessed again soon.</li></ol><p><strong>Cache Invalidation Approaches</strong></p><ol><li>Active Expiration: Continuously monitors the Time-to-Live (TTL) of cache entries and evicts those that have expired.</li><li>Passive Expiration: Checks the TTL of a cache entry only when it’s accessed, reducing computational overhead but potentially leading to stale data reads.</li></ol><p><strong>Storage Mechanisms in Distributed Cache</strong></p><ol><li>Hashing Functions: Used to determine the cache server responsible for storing a particular data item. Consistent hashing ensures even data distribution across servers.</li><li>Data Structures: Linked lists are commonly used for their efficiency in adding, removing, and accessing data.</li><li>Bloom Filters: Probabilistic data structures that efficiently determine if a data item exists in the cache, reducing the need for full data scans.</li></ol><p><strong>Data Sharding in Distributed Cache</strong></p><ol><li>Dedicated Cache Servers: Separates cache servers from application and web servers, allowing independent scaling of each component.</li><li>Colocated Cache: Embeds cache functionality within the application or web servers, simplifying deployment but limiting scalability.</li></ol><p><strong>Cache Client</strong></p><p>Resides in application servers to determine the appropriate cache server for data storage and retrieval. It ensures consistent results regardless of client interactions.</p><p><strong>Exploring Distributed Cache System Design</strong></p><p>In the next article, we will delve into the intricacies of designing a distributed cache system, exploring strategies for achieving high availability, scalability, and performance. We will discuss various design considerations, including cache invalidation mechanisms, data partitioning, and cache consistency models. Join us as we embark on this journey to design a robust and efficient distributed cache system.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d12d70a620e3" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>