<?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 Aravinth Ravichandran on Medium]]></title>
        <description><![CDATA[Stories by Aravinth Ravichandran on Medium]]></description>
        <link>https://medium.com/@arvinth-16?source=rss-c956c0513b45------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*o4tMD36UFPzzZqky.jpg</url>
            <title>Stories by Aravinth Ravichandran on Medium</title>
            <link>https://medium.com/@arvinth-16?source=rss-c956c0513b45------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 13:55:44 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@arvinth-16/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[Building a Task Scheduler in Java: A Step-by-Step Guide]]></title>
            <link>https://arvinth-16.medium.com/building-a-task-scheduler-in-java-a-step-by-step-guide-fb440df964bc?source=rss-c956c0513b45------2</link>
            <guid isPermaLink="false">https://medium.com/p/fb440df964bc</guid>
            <dc:creator><![CDATA[Aravinth Ravichandran]]></dc:creator>
            <pubDate>Mon, 30 Dec 2024 22:56:51 GMT</pubDate>
            <atom:updated>2024-12-30T22:56:51.770Z</atom:updated>
            <content:encoded><![CDATA[<p>Scheduling tasks is a critical component in many software applications, from running periodic background jobs to executing delayed tasks. In this blog, I will share how I implemented a task scheduler in Java, its key features, and how you can build one too. By the end of this guide, you’ll have a clear understanding of creating a robust task scheduler that meets various use cases.</p><h4>Why Build a Task Scheduler?</h4><p>Task schedulers are useful for:</p><ol><li><strong>Automating repetitive tasks</strong>: e.g., sending email reminders, cleaning up logs.</li><li><strong>Delayed execution</strong>: e.g., retrying failed transactions after a specific interval.</li><li><strong>Resource management</strong>: e.g., ensuring tasks do not overload the system.</li></ol><p>Although Java provides libraries like Quartz and features like ScheduledExecutorService, building your scheduler can provide flexibility and control.</p><h4>Architecture Overview</h4><p>A task scheduler typically consists of the following components:</p><ol><li><strong>Task Queue</strong>: Stores tasks to be executed, often sorted by execution time.</li><li><strong>Worker Threads</strong>: Dedicated threads to execute tasks.</li><li><strong>Timer</strong>: Monitors the queue and dispatches tasks at the appropriate time.</li><li><strong>Job Interface</strong>: A common structure for all tasks to ensure uniform handling.</li></ol><p><strong>Key features</strong></p><ul><li><strong>Priority-based execution</strong>: Tasks are executed based on their scheduled time.</li><li><strong>Thread safety</strong>: Supports concurrent task submissions without race conditions.</li><li><strong>Dynamic task scheduling</strong>: Tasks can be added, removed, or updated dynamically.</li><li><strong>Graceful shutdown</strong>: Ensures no tasks are lost during shutdown.</li></ul><pre><br>class Job implements Comparable&lt;Job&gt; {<br>    Runnable task;<br>    long epochTimeMilliSecs;<br><br>    public Job(Runnable task, long time) {<br>        this.task = task;<br>        this.epochTimeMilliSecs = time;<br>    }<br><br>    @Override<br>    public int compareTo(final Job o) {<br>        return (int) (this.epochTimeMilliSecs - o.epochTimeMilliSecs);<br>    }<br>}<br><br>class Scheduler {<br>    PriorityBlockingQueue&lt;Job&gt; queue;<br>    ExecutorService executorService;<br>    Thread daemon;<br>    ReentrantLock lock;<br>    Condition canDeque;<br>    Condition canEnque;<br>    Condition waitTimeCondition;<br>    int capacity;<br>    AtomicBoolean running;<br><br>    public Scheduler(int threadPoolSize, int capacity) {<br>        this.queue = new PriorityBlockingQueue&lt;&gt;();<br>        this.executorService = Executors.newFixedThreadPool(threadPoolSize);<br>        this.lock = new ReentrantLock();<br>        this.canDeque = lock.newCondition();<br>        this.canEnque = lock.newCondition();<br>        this.waitTimeCondition = lock.newCondition();<br>        this.capacity = capacity;<br>        this.running = new AtomicBoolean();<br>        running.set(true);<br>        startScheduler();<br>    }<br><br>    private void startScheduler() {<br>        daemon = new Thread(this::process);<br>        daemon.setDaemon(true);<br>        daemon.start();<br>    }<br><br>    public void process() {<br>        while (running.get() || !queue.isEmpty()) {<br>            lock.lock();<br><br>            try {<br>                if (queue.isEmpty()) {<br>                    canDeque.await();<br>                }<br>                Job job = queue.peek();<br>                if (job != null) {<br>                    long waitTime = job.epochTimeMilliSecs - System.currentTimeMillis();<br>                    if (waitTime &gt; 0) {<br>                        waitTimeCondition.await(waitTime, TimeUnit.MILLISECONDS);<br>                    }<br>                    queue.poll();<br>                    canEnque.signal();<br>                    executorService.submit(job.task);<br>                }<br><br>            } catch (InterruptedException e) {<br>                throw new RuntimeException(e);<br>            } finally {<br>                lock.unlock();<br>            }<br><br>        }<br>    }<br><br>    public void schedule(Job job) {<br>        lock.lock();<br>        try {<br>            queue.add(job);<br>            canDeque.signal();<br>        } finally {<br>            lock.unlock();<br>        }<br>    }<br><br>    public void shutdown() {<br>        running.set(false);<br>        lock.lock();<br>        try {<br>            canDeque.signal(); <br>        } finally {<br>            lock.unlock();<br>        }<br>        daemon.interrupt();<br>        executorService.shutdown();<br>    }<br><br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fb440df964bc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Bloom Filters: Fast, Space-Efficient Data Structures]]></title>
            <link>https://arvinth-16.medium.com/bloom-filters-fast-space-efficient-data-structures-aa2a6f4634e7?source=rss-c956c0513b45------2</link>
            <guid isPermaLink="false">https://medium.com/p/aa2a6f4634e7</guid>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[bloom-filter]]></category>
            <dc:creator><![CDATA[Aravinth Ravichandran]]></dc:creator>
            <pubDate>Mon, 28 Oct 2024 10:55:48 GMT</pubDate>
            <atom:updated>2024-10-28T10:57:35.505Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/397/1*0y7tUAIX_tSnNbKfNlxYpQ.png" /></figure><p>When it comes to working with large datasets, particularly in situations where memory usage and speed are crucial, data structures like hash tables and arrays often fall short. Enter the <strong>Bloom Filter</strong> — a clever, probabilistic data structure that excels in answering membership queries with a significant reduction in memory usage. But what makes Bloom Filters so special, and how do they work?</p><p>In this blog, we’ll explore:</p><ol><li>What Bloom Filters are</li><li>How they work</li><li>Their advantages and limitations</li><li>Where they’re used in real-world applications</li></ol><h3>What is a Bloom Filter?</h3><p>A <strong>Bloom Filter</strong> is a probabilistic data structure designed to test whether an element is a member of a set. Unlike other data structures, Bloom Filters don’t store the elements themselves but provide an efficient way to check for membership.</p><p>Bloom Filters allow two types of responses:</p><ul><li><strong>Element might be in the set.</strong></li><li><strong>Element is definitely not in the set.</strong></li></ul><p>This means they are capable of <em>false positives</em> (indicating an element is in the set when it’s not) but never <em>false negatives</em> (indicating an element is not in the set when it actually is).</p><h4>When Should You Use a Bloom Filter?</h4><p>Bloom Filters shine when:</p><ul><li>Memory is constrained.</li><li>A small probability of false positives is acceptable.</li><li>Speed is a priority, as they offer constant-time membership checks.</li></ul><h3>How Does a Bloom Filter Work?</h3><p>A Bloom Filter uses a bit array and multiple hash functions to store information about set membership. Here’s how it works:</p><ol><li><strong>Bit Array Initialization:</strong> Start with an array of m bits, all set to 0 initially.</li><li><strong>Hash Functions:</strong> Define k independent hash functions that each map an element to one of the m array positions uniformly at random.</li><li><strong>Adding an Element:</strong> When adding an element, compute the k hash values for it, resulting in k indices in the bit array. Set the bits at these indices to 1.</li><li><strong>Checking for Membership:</strong> To check if an element is in the set, compute its k hash values and check the bits at the resulting indices:</li></ol><ul><li>If all bits are set to 1, the element <em>might</em> be in the set.</li><li>If any bit is 0, the element is <em>definitely not</em> in the set.</li></ul><h4>Example</h4><p>Imagine adding the names “Aravinth,” “Kishore,” and “preethi” to a Bloom Filter:</p><ol><li>Each name is hashed k times, resulting in a set of k indices in the bit array.</li><li>For each name, the bits at the respective indices are set to 1.</li><li>When checking if “bilal” is in the filter, if any of his corresponding bits are 0, we know he’s not in the set. If all are 1, he <em>might</em> be in the set.</li></ol><h3>The Math Behind Bloom Filters</h3><p>To understand why Bloom Filters are effective, consider these parameters:</p><ul><li><strong>m:</strong> The size of the bit array.</li><li><strong>k:</strong> The number of hash functions.</li><li><strong>n:</strong> The number of elements added to the Bloom Filter.</li></ul><p>As elements are added, the probability of a false positive (when all k bits for a non-member are accidentally set to 1) increases. With optimal tuning of m and k, the Bloom Filter can keep this probability low. The false positive rate can be approximated as:</p><pre>p = (1 - e ^ (-kn/m)) ^ k</pre><p>where e is the base of the natural logarithm.</p><p>With appropriate m and k values, Bloom Filters are incredibly space-efficient compared to other data structures for the same task.</p><h3>Advantages of Bloom Filters</h3><ol><li><strong>Space Efficiency:</strong> Bloom Filters require far less memory compared to storing the entire dataset.</li><li><strong>Speed:</strong> The constant-time complexity O(k) for membership checks and additions makes them highly performant.</li><li><strong>No False Negatives:</strong> Bloom Filters are guaranteed to never return a false negative.</li></ol><h3>Limitations of Bloom Filters</h3><ol><li><strong>False Positives:</strong> There’s a small probability of false positives, meaning an element might appear to be in the set even if it’s not.</li><li><strong>No Deletion Support:</strong> Removing elements from a Bloom Filter is tricky because doing so can lead to erroneous results.</li><li><strong>Static Nature:</strong> Bloom Filters don’t adapt well to varying dataset sizes. They need to be preconfigured with an approximate size and error rate, making them less flexible.</li></ol><h3>Real-World Applications of Bloom Filters</h3><p>Due to their unique properties, Bloom Filters are widely used in applications requiring fast, probabilistic membership checking, such as:</p><ol><li><strong>Database Systems:</strong> Used for efficient indexing and cache lookups, particularly in large-scale distributed systems.</li><li><strong>Web Crawlers:</strong> To track visited URLs quickly without storing the entire set of URLs, allowing faster operation and reduced storage.</li><li><strong>Spam Filtering:</strong> Email systems employ Bloom Filters to identify and block known spam patterns or addresses.</li><li><strong>Blockchain and Cryptocurrencies:</strong> Used for lightweight clients in Bitcoin to verify transactions without downloading the entire blockchain.</li></ol><h4>Java</h4><pre>import java.security.MessageDigest;<br>import java.security.NoSuchAlgorithmException;<br>import java.util.BitSet;<br><br>public class BloomFilter {<br>    private final BitSet bitSet;<br>    private final int bitSetSize;<br>    private final int hashCount;<br><br>    public BloomFilter(int bitSetSize, int hashCount) {<br>        this.bitSetSize = bitSetSize;<br>        this.hashCount = hashCount;<br>        this.bitSet = new BitSet(bitSetSize);<br>    }<br><br>    <br>    private int[] getHashes(String data) throws NoSuchAlgorithmException {<br>        int[] hashes = new int[hashCount];<br>        MessageDigest md = MessageDigest.getInstance(&quot;MD5&quot;);<br>        <br>        for (int i = 0; i &lt; hashCount; i++) {<br>            md.update((data + i).getBytes());<br>            byte[] digest = md.digest();<br>            int hash = Math.abs(bytesToInt(digest) % bitSetSize);<br>            hashes[i] = hash;<br>        }<br>        <br>        return hashes;<br>    }<br><br>   <br>    private int bytesToInt(byte[] bytes) {<br>        int result = 0;<br>        for (int i = 0; i &lt; Math.min(bytes.length, 4); i++) {<br>            result &lt;&lt;= 8;<br>            result |= (bytes[i] &amp; 0xFF);<br>        }<br>        return result;<br>    }<br><br><br>    public void add(String data) throws NoSuchAlgorithmException {<br>        int[] hashes = getHashes(data);<br>        for (int hash : hashes) {<br>            bitSet.set(hash);<br>        }<br>    }<br><br><br>    public boolean mightContain(String data) throws NoSuchAlgorithmException {<br>        int[] hashes = getHashes(data);<br>        for (int hash : hashes) {<br>            if (!bitSet.get(hash)) {<br>                return false; <br>            }<br>        }<br>        return true; <br>    }<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aa2a6f4634e7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Count-Min Sketch: A Space-Efficient Probabilistic Data Structure]]></title>
            <link>https://arvinth-16.medium.com/understanding-count-min-sketch-a-space-efficient-probabilistic-data-structure-0da38e7e44e4?source=rss-c956c0513b45------2</link>
            <guid isPermaLink="false">https://medium.com/p/0da38e7e44e4</guid>
            <category><![CDATA[datastrucutre]]></category>
            <category><![CDATA[probability]]></category>
            <category><![CDATA[count-min-sketch]]></category>
            <dc:creator><![CDATA[Aravinth Ravichandran]]></dc:creator>
            <pubDate>Fri, 11 Oct 2024 07:32:48 GMT</pubDate>
            <atom:updated>2024-10-11T07:32:48.171Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/531/1*3pzeCc4eqmwOup2EqVBkLg.png" /></figure><p>In the era of big data, the ability to efficiently process and summarize large datasets is crucial. One such data structure that excels in this regard is the <strong>Count-Min Sketch (CMS)</strong>. It provides a way to count the frequency of events in a stream of data while using significantly less space than traditional methods. This blog will explore the Count-Min Sketch algorithm, its applications, and how to implement it in JavaScript.</p><blockquote>What is Count-Min Sketch?</blockquote><p>Count-Min Sketch is a probabilistic data structure that is used for estimating the frequency of events in a large data stream. It provides a space-efficient way to count distinct elements without needing to store all the elements explicitly. The Count-Min Sketch is particularly useful in scenarios where:</p><ul><li>The data stream is too large to fit into memory.</li><li>You require approximate counts rather than exact counts.</li><li>You are okay with a small probability of error in your estimates.</li></ul><blockquote>How Does It Work?</blockquote><p>Count-Min Sketch uses a combination of hashing and arrays to store counts. The basic idea is to maintain multiple hash functions and corresponding counters. Each time an event occurs, the algorithm hashes the event to multiple indices in different arrays and increments the counts at those indices.</p><h4>Key Concepts</h4><ol><li><strong>Hash Functions</strong>: We use multiple hash functions to map each event to different indices.</li><li><strong>Count Arrays</strong>: Each hash function has its own count array. The size of these arrays is determined by the desired accuracy and the number of hash functions.</li><li><strong>Estimation</strong>: To get the count of an event, we hash it through all the hash functions and retrieve the counts at the resulting indices. The minimum count among these indices is returned as the estimated frequency.</li></ol><h4>Error Characteristics</h4><ul><li>The Count-Min Sketch allows for over-counting but never under-counts. This means the estimated frequency can be higher than the actual frequency, but never lower.</li><li>The error margin can be controlled by adjusting the size of the count arrays and the number of hash functions used.</li></ul><p>Let’s implement a simple version of Count-Min Sketch.</p><p>JavaScript</p><pre><br>class CountMinSketch {<br>    constructor(epsilon, delta) {<br><br>        this.width = Math.ceil(Math.E / epsilon);<br>        this.depth = Math.ceil(Math.log(1 / delta);<br><br><br>        this.counts = Array.from({ length: this.depth }, () =&gt; Array(this.width).fill(0));<br><br><br>        this.hashFunctions = Array.from({ length: this.depth }, () =&gt; {<br>            return this.createHashFunction();<br>        });<br>    }<br><br><br>    createHashFunction() {<br>        return (x) =&gt; {<br>            return (x.split(&#39;&#39;).reduce((acc, char) =&gt; acc + char.charCodeAt(0), 0) + Math.random()) % this.width;<br>        };<br>    }<br><br><br>    add(element) {<br>        for (let i = 0; i &lt; this.depth; i++) {<br>            const index = this.hashFunctions[i](element);<br>            this.counts[i][index] += 1;<br>        }<br>    }<br><br><br>    estimate(element) {<br>        let minCount = Infinity;<br><br>        for (let i = 0; i &lt; this.depth; i++) {<br>            const index = this.hashFunctions[i](element);<br>            minCount = Math.min(minCount, this.counts[i][index]);<br>        }<br><br>        return minCount;<br>    }<br>}</pre><p>Kotlin</p><pre>import kotlin.math.ceil<br>import kotlin.math.exp<br>import kotlin.math.ln<br>import kotlin.random.Random<br><br>class CountMinSketch(epsilon: Double, delta: Double) {<br>    private val width: Int = ceil(exp(1.0) / epsilon).toInt()<br>    private val depth: Int = ceil(ln(1.0 / delta)).toInt()<br>    private val counts: Array&lt;IntArray&gt; = Array(depth) { IntArray(width) }<br>    private val hashFunctions: Array&lt;(String) -&gt; Int&gt; = Array(depth) { createHashFunction() }<br><br>    private fun createHashFunction(): (String) -&gt; Int {<br>        return { element: String -&gt;<br>            element.fold(0) { acc, char -&gt; acc + char.code } + Random.nextInt() % width<br>        }<br>    }<br><br>    fun add(element: String) {<br>        for (i in 0 until depth) {<br>            val index = hashFunctions[i](element) % width<br>            counts[i][index]++<br>        }<br>    }<br><br>    fun estimate(element: String): Int {<br>        var minCount = Int.MAX_VALUE<br><br>        for (i in 0 until depth) {<br>            val index = hashFunctions[i](element) % width<br>            minCount = minOf(minCount, counts[i][index])<br>        }<br><br>        return minCount<br>    }<br>}</pre><h4>Conclusion</h4><p>Count-Min Sketch is a powerful tool for handling large data streams, allowing you to estimate frequencies with limited space. This algorithm is widely used in network traffic monitoring, recommendation systems, and various applications in big data processing.</p><p>The JavaScript implementation provided in this blog offers a simple yet effective way to incorporate Count-Min Sketch into your projects. By adjusting the parameters epsilon and delta, you can control the accuracy of your estimates based on your application&#39;s needs.</p><p>Feel free to explore further and integrate this data structure into your applications. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0da38e7e44e4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Browser Forward-Backward Cache (bfCache) and How to Utilize It]]></title>
            <link>https://arvinth-16.medium.com/understanding-browser-forward-backward-cache-bfcache-and-how-to-utilize-it-69e235e2bb9f?source=rss-c956c0513b45------2</link>
            <guid isPermaLink="false">https://medium.com/p/69e235e2bb9f</guid>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[browsers]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Aravinth Ravichandran]]></dc:creator>
            <pubDate>Mon, 07 Oct 2024 04:52:01 GMT</pubDate>
            <atom:updated>2024-10-07T06:37:12.943Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/596/1*UEamH2NOsxJwLMh-0r4iBA.png" /></figure><p>When developing modern web applications, performance is a top priority. A key player in web performance optimization is the browser’s forward-backward cache (bfCache), a feature that ensures a faster and smoother user experience when navigating back and forth between pages. In this blog, we’ll delve into what the bfCache is, how it works, and how you can optimize your website to utilize it effectively.</p><blockquote>What is bfCache?</blockquote><p>The forward-backward cache (bfCache) is a browser feature that saves a complete snapshot of a page, including the DOM, JavaScript state, event listeners, and even scroll position. When a user navigates back to a page stored in the bfCache (or forward to a page after navigating backward), the page is restored instantly, providing a much faster experience compared to reloading the page from scratch.</p><p>Unlike other forms of caching (like HTTP caching, which stores resources like HTML, CSS, and JavaScript), bfCache retains the full page state as it was, meaning that when a user navigates back to a cached page, everything is exactly as they left it — without re-running scripts, re-fetching data, or reconstructing the DOM.</p><blockquote>How bfCache Works</blockquote><p>When a user navigates away from a page (either forward or backward), the browser checks if the page can be saved in the bfCache. If it’s eligible, the browser takes a snapshot of the page, freezing its JavaScript execution and saving its entire state. This snapshot is then held in memory.</p><p>When the user returns to the page via navigation (e.g., using the back button), the browser restores the page from the cache, including all its visual and interactive states, without reloading it or sending any additional network requests.</p><p>However, not all pages are eligible for bfCache. Some of the most common reasons for a page being ineligible include:</p><ul><li><strong>Page contains unload event listeners</strong>: These are often used to clean up or track analytics before the user leaves a page.</li><li><strong>JavaScript that interferes with the page lifecycle</strong>: Some scripts may assume that navigating away destroys the page, making it unsuitable for caching.</li><li><strong>Cross-origin iframes</strong>: Pages containing iframes from different origins may also be excluded from bfCache due to security concerns.</li><li><strong>Background timers or active network connections</strong>: Active background processes can interfere with caching.</li></ul><blockquote>How to Utilize bfCache</blockquote><p>To make the most of bfCache, you need to ensure that your pages are “bfCache-friendly.” This involves following best practices to avoid common issues that make pages ineligible for bfCache.</p><h3>1. Avoid unload Event Listeners</h3><p>One of the primary reasons a page becomes ineligible for bfCache is the use of unload event listeners. These listeners were traditionally used to handle cleanup when the page is about to be unloaded, but they prevent bfCache because the browser assumes that the page needs to be completely torn down.</p><p>Instead, use the pagehide event, which is fired when a page is going to be placed in the cache, making it a suitable replacement for unload.</p><pre>window.addEventListener(&#39;pagehide&#39;, function(event) {<br>  if (event.persisted) {<br>    console.log(&#39;Page is now in the bfCache&#39;);<br>  }<br>});</pre><h3>2. Use the pageshow Event</h3><p>When a page is restored from bfCache, the pageshow event is fired. You can use this event to detect when the page is being restored from bfCache and optimize your logic accordingly.</p><pre>window.addEventListener(&#39;pageshow&#39;, function(event) {<br>  if (event.persisted) {<br>    console.log(&#39;Page was restored from bfCache&#39;);<br>  }<br>});</pre><h3>3. Handle Background Tasks Carefully</h3><p>If your page uses background tasks, such as network requests, WebSockets, or setInterval, ensure they are paused when the page is cached, as these can prevent the page from being eligible for bfCache.</p><p>The pagehide event is again useful here, as it allows you to stop such tasks when the page is being hidden, and restart them when the page is shown again.</p><pre>window.addEventListener(&#39;pagehide&#39;, function(event) {<br>  clearInterval(myInterval);<br>});<br><br>window.addEventListener(&#39;pageshow&#39;, function(event) {<br>  if (event.persisted) {<br>    myInterval = setInterval(myTask, 1000);<br>  }<br>});</pre><h3>4. Test for bfCache Eligibility</h3><p>Testing for bfCache compatibility is crucial, and fortunately, most modern browsers provide tools to help with this. For example, Chrome and Firefox offer a back-forward cache tab in the devtools.</p><p>Here’s how to test your page’s eligibility for bfCache:</p><ol><li><strong>Open Chrome DevTools</strong>: Press F12 or Ctrl+Shift+I.</li><li><strong>Navigate to the </strong><strong>Application tab</strong>: Look for the Back/forward cache section.</li><li><strong>Perform navigation and observe results</strong>: Navigate away and back to your page, and check the logs to see if your page was stored in bfCache or if it was excluded. If excluded, the logs will show reasons why, helping you identify which features need adjustments.</li></ol><h3>5. Reduce Memory Usage</h3><p>Since bfCache stores the entire state of a page in memory, it’s essential to be mindful of the memory usage of your web application. Reducing unnecessary DOM nodes and optimizing your JavaScript performance can increase the likelihood of the page being stored in the cache.</p><h3>6. Avoid Dynamic URL Changes</h3><p>Avoid unnecessary URL changes when handling back/forward navigation. For example, avoid altering query parameters or fragments (#) purely for state management unless necessary, as they can make the page ineligible for caching.</p><h3>Conclusion</h3><p>The forward-backward cache (bfCache) is a powerful browser feature that significantly enhances user experience by making navigation almost instantaneous. However, making your pages bfCache-compatible requires following certain best practices. By avoiding unload event listeners, handling background tasks correctly, and optimizing JavaScript and memory usage, you can ensure your web applications take full advantage of this cache, leading to faster, smoother browsing for your users.</p><p>By leveraging these strategies, you can create a more responsive and efficient web experience, giving your users the best possible performance, especially on mobile and low-powered devices where bfCache can make a noticeable difference.</p><p>Stay tuned for more tips on optimizing web performance!</p><p>Feel free to ask questions or share your experiences with bfCache in the comments!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=69e235e2bb9f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Microservices Architecture: A Comprehensive Guide]]></title>
            <link>https://arvinth-16.medium.com/mastering-microservices-architecture-a-comprehensive-guide-0e8e82202bec?source=rss-c956c0513b45------2</link>
            <guid isPermaLink="false">https://medium.com/p/0e8e82202bec</guid>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[domain-driven-design]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[kafka]]></category>
            <dc:creator><![CDATA[Aravinth Ravichandran]]></dc:creator>
            <pubDate>Sun, 06 Oct 2024 09:05:12 GMT</pubDate>
            <atom:updated>2024-10-06T09:05:12.534Z</atom:updated>
            <content:encoded><![CDATA[<p>In today’s fast-paced world of software development, microservices architecture has become a go-to solution for building scalable, resilient, and maintainable systems. But to truly harness the power of microservices, one must understand the key principles, design patterns, and implementation strategies behind this architecture.</p><p>In this blog, we will dive deep into the world of microservices, explore its components, and walk through practical code examples and design diagrams.</p><blockquote><strong>What are Microservices?</strong></blockquote><p>Microservices is an architectural style where applications are built as a collection of small, loosely coupled services. Each service focuses on a specific business capability, operates independently, and communicates with other services through lightweight protocols like HTTP or messaging queues.</p><blockquote><strong>Key Characteristics of Microservices:</strong></blockquote><ol><li><strong>Decentralized Data Management</strong>: Each microservice manages its own database, fostering independence and reducing coupling.</li><li><strong>Scalability</strong>: Services can scale independently based on load.</li><li><strong>Resilience</strong>: Failure in one service doesn’t necessarily take down the entire system.</li><li><strong>Deployability</strong>: Continuous delivery is easier due to independent deployment cycles.</li></ol><p>Let’s take a look at the architecture of a typical microservices application.</p><h3>Microservices Architecture Design Diagram</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/847/1*Q5Gl-tadClq-rD1syDhfrg.png" /></figure><blockquote>Why Microservices Over Monolith?</blockquote><p>In a <strong>monolithic architecture</strong>, all components of an application are packaged and deployed together. While this works well for smaller applications, it becomes difficult to maintain, scale, and deploy as the system grows.</p><p>Microservices offer:</p><ul><li><strong>Independent Deployment</strong>: Each service can be developed, deployed, and scaled separately.</li><li><strong>Technology Diversity</strong>: Different services can use different tech stacks, allowing teams to choose the best tool for each task.</li><li><strong>Fault Isolation</strong>: Failures in one service do not bring down the entire application.</li></ul><h3>Designing Microservices: Key Concepts</h3><h3>1. Domain-Driven Design (DDD)</h3><p>Microservices naturally align with the principles of Domain-Driven Design. Each service should represent a specific bounded context — a domain or business capability.</p><p>Example:</p><ul><li><strong>User Service</strong>: Handles user management (registration, login, profiles).</li><li><strong>Order Service</strong>: Manages order placement and tracking.</li><li><strong>Payment Service</strong>: Processes payments and manages transactions.</li></ul><p>When designing microservices, it’s crucial to identify the bounded contexts of your application and create services around them.</p><h3>2. API Gateway Pattern</h3><p>An <strong>API Gateway</strong> acts as the single entry point into a microservices system. It handles routing requests to appropriate services, authentication, logging, and more.</p><p>Here’s how you can set up an API Gateway using <strong>Spring Cloud Gateway</strong>:</p><pre>@SpringBootApplication<br>public class ApiGatewayApplication {    <br>public static void main(String[] args) {<br>        SpringApplication.run(ApiGatewayApplication.class, args);<br>    }<br>@Bean<br>    public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {<br>        return builder.routes()<br>            .route(&quot;user_service&quot;, r -&gt; r.path(&quot;/users/**&quot;)<br>                .uri(&quot;http://localhost:8081&quot;))<br>            .route(&quot;order_service&quot;, r -&gt; r.path(&quot;/orders/**&quot;)<br>                .uri(&quot;http://localhost:8082&quot;))<br>            .build();<br>    }<br>}</pre><p>In this code, we define two routes: /users/** routes requests to the <strong>User Service</strong> running on localhost:8081, and /orders/** routes to the <strong>Order Service</strong> on localhost:8082.</p><h3>3. Asynchronous Communication with Message Queues</h3><p>Microservices should communicate asynchronously to reduce coupling and improve resilience. One common pattern is using a message broker like <strong>Kafka</strong> or <strong>RabbitMQ</strong>.</p><p>For example, let’s say you want to publish an event when a new order is placed:</p><pre>// OrderService.java<br><br><br>@Autowired<br>private KafkaTemplate&lt;String, String&gt; kafkaTemplate;<br><br>public void placeOrder(Order order) {<br>    // Order processing logic<br>    kafkaTemplate.send(&quot;order_created&quot;, order.toString());<br>}</pre><p>This decouples the <strong>Order Service</strong> from the downstream services (e.g., <strong>Inventory</strong>, <strong>Shipping</strong>) that need to react to the order being created.</p><h3>4. Database Per Service Pattern</h3><p>Each microservice should have its own database to ensure autonomy. For instance, the <strong>User Service</strong> may use MySQL, while the <strong>Order Service</strong> uses PostgreSQL, and the <strong>Payment Service</strong> uses MongoDB. This avoids data coupling and allows services to scale independently.</p><h4>Example:</h4><ul><li><strong>User Service</strong>: Stores user data in MySQL.</li><li><strong>Order Service</strong>: Stores order details in PostgreSQL.</li><li><strong>Payment Service</strong>: Manages transactions in MongoDB.</li></ul><p>This architecture enables better fault isolation and scalability since no service depends on a shared database.</p><h3>5. Circuit Breaker Pattern</h3><p>In a microservices architecture, services may fail, and these failures can propagate across the system. The <strong>Circuit Breaker</strong> pattern prevents cascading failures by temporarily stopping requests to an unresponsive service.</p><p>Here’s an example of using <strong>Resilience4j</strong> in Spring Boot to implement a circuit breaker:</p><pre>@CircuitBreaker(name = &quot;orderService&quot;, fallbackMethod = &quot;fallback&quot;)<br>public String getOrderDetails(String orderId) {<br>    return restTemplate.getForObject(&quot;http://order-service/orders/&quot; + orderId, String.class);<br>}<br><br><br>public String fallback(String orderId, Throwable t) {<br>    return &quot;Order service is currently unavailable. Please try again later.&quot;;<br>}</pre><p>In this example, if the <strong>Order Service</strong> fails, the circuit breaker will open and fall back to a predefined message instead of continuously retrying the failed service.</p><h3>Sample Code: Deploying a Microservice</h3><p>Here’s a simplified version of a <strong>User Service</strong> using Spring Boot:</p><pre>@RestController<br>@RequestMapping(&quot;/users&quot;)<br>public class UserController {<br><br>    @Autowired<br>    private UserService userService;<br><br>    @PostMapping(&quot;/register&quot;)<br>    public ResponseEntity&lt;User&gt; registerUser(@RequestBody User user) {<br>        User createdUser = userService.registerUser(user);<br>        return ResponseEntity.status(HttpStatus.CREATED).body(createdUser);<br>    }<br><br>    @GetMapping(&quot;/{id}&quot;)<br>    public ResponseEntity&lt;User&gt; getUser(@PathVariable Long id) {<br>        User user = userService.getUserById(id);<br>        return ResponseEntity.ok(user);<br>    }<br>}<br><br>@Service<br>public class UserService {<br>    @Autowired<br>    private UserRepository userRepository;<br><br>    public User registerUser(User user) {<br>        return userRepository.save(user);<br>    }<br><br>    public User getUserById(Long id) {<br>        return userRepository.findById(id)<br>                .orElseThrow(() -&gt; new UserNotFoundException(&quot;User not found&quot;));<br>    }<br>}</pre><h3>Conclusion</h3><p>Mastering microservices architecture requires a deep understanding of distributed systems, design patterns, and resilience strategies. By adopting these best practices, you can build scalable, fault-tolerant applications that can evolve over time.</p><p>Whether you are developing a startup product or migrating an enterprise application, microservices can help you deliver software that is easier to scale, manage, and deploy.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0e8e82202bec" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>