<?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 Abhishek Gupta on Medium]]></title>
        <description><![CDATA[Stories by Abhishek Gupta on Medium]]></description>
        <link>https://medium.com/@abhishek10005?source=rss-848ec7d41b8c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*f_VG8iUbhRYRHq0LI-vZHA.jpeg</url>
            <title>Stories by Abhishek Gupta on Medium</title>
            <link>https://medium.com/@abhishek10005?source=rss-848ec7d41b8c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 10:15:03 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@abhishek10005/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[Request Coalescing: Preventing Duplicate Work in High-Concurrency Systems]]></title>
            <link>https://levelup.gitconnected.com/request-coalescing-preventing-duplicate-work-in-high-concurrency-systems-85ff4a8f49dd?source=rss-848ec7d41b8c------2</link>
            <guid isPermaLink="false">https://medium.com/p/85ff4a8f49dd</guid>
            <dc:creator><![CDATA[Abhishek Gupta]]></dc:creator>
            <pubDate>Tue, 11 Aug 2026 15:53:34 GMT</pubDate>
            <atom:updated>2026-08-12T01:26:55.158Z</atom:updated>
            <content:encoded><![CDATA[<p>Imagine an endpoint GET /users/123 that reads from a database. Everything is fine until 1,000 requests for the same user arrive at nearly the same instant — the cache entry for a hot key just expired, or a normally quiet account suddenly went viral. Without protection, the database does identical work 1,000 times:</p><pre>Request 1    ──&gt; DB ──&gt; User 123<br>Request 2    ──&gt; DB ──&gt; User 123<br>...<br>Request 1000 ──&gt; DB ──&gt; User 123</pre><p>If every request needs the <em>same</em> result, why not let them share a single in-progress operation? That is the idea behind <strong>request coalescing</strong>:</p><blockquote>When multiple concurrent requests ask for the same resource, combine them into one in-progress operation and share its result with all callers.</blockquote><pre>A ──┐                          ┌──&gt; A<br>B ──┼──&gt; One DB request ──&gt; Result ──&gt; B<br>C ──┘                          └──&gt; C</pre><p>Simple in spirit, but a correct implementation has to answer: How do requests discover that a fetch is already underway? How do they wait for it? What happens on failure, timeout, or across multiple application instances? We’ll build it up step by step.</p><h3>The In-Flight Registry</h3><p>We need a place to track operations that are <em>currently in progress</em>. In Java:</p><pre>ConcurrentHashMap&lt;String, CompletableFuture&lt;User&gt;&gt; inFlight;</pre><p>The key identifies the resource (&quot;user:123&quot;); the value is the operation that will eventually produce the result. Crucially, this is not a cache of completed results — it holds <strong>work in progress</strong>.</p><p>A CompletableFuture is a promise: <em>&quot;I don&#39;t have the User yet, but I will.&quot;</em> Because it&#39;s a handle to a pending result rather than the result itself, we can hand the same Future to many callers.</p><h3>Coalescing in Action</h3><p>The first request for user:123 finds an empty map and creates Future F1, which kicks off the DB call:</p><pre>inFlight: &quot;user:123&quot; ──&gt; F1 ──&gt; DB</pre><p>A second and third request arrive before the DB responds. They find F1 already present and simply share it — no new database calls:</p><pre>A ──┐<br>B ──┼──&gt; F1 ──&gt; DB<br>C ──┘</pre><p>The magic is doing the “check for an existing operation, or create one” step atomically. A naive version has a race:</p><pre>if (!inFlight.containsKey(userId)) {          // two threads can both<br>    inFlight.put(userId, fetchUserFromDB(userId)); // pass this check<br>}</pre><p>computeIfAbsent() gives us the atomic check-and-create we need instead.</p><h3>The Complete Local Implementation</h3><pre>private final ConcurrentHashMap&lt;String, CompletableFuture&lt;User&gt;&gt; inFlight =<br>        new ConcurrentHashMap&lt;&gt;();<br><br>public CompletableFuture&lt;User&gt; getUser(String userId) {<br>    return inFlight.computeIfAbsent(userId, key -&gt; {<br>        CompletableFuture&lt;User&gt; future = fetchUserFromDB(key);<br>        future.whenComplete((result, error) -&gt; inFlight.remove(key, future));<br>        return future;<br>    });<br>}</pre><p>Two lines carry the weight: computeIfAbsent() and whenComplete().</p><p><strong>return future does not block.</strong> It hands back the pending Future immediately — like a restaurant ticket that represents food not yet ready. This is the opposite of future.get() or future.join(), which block the calling thread until the result arrives. Returning the Future (or chaining with thenApply(...)) lets the request wait <em>logically</em> for the result without a thread sitting idle — which is exactly why async matters under high concurrency.</p><p><strong>whenComplete() registers a cleanup callback</strong> that runs once the Future finishes, whether it succeeds or fails:</p><pre>future.whenComplete((result, error) -&gt; inFlight.remove(key, future));</pre><p>We remove the entry <em>after</em> completion, not before — the registry is meant to hold only live operations. Removing it immediately would be wrong, since the DB call is still running. On success, the entry clears so a later request can start fresh work; on failure, it also clears so the next caller can retry.</p><h3>Failure, Timeout, and Cancellation</h3><p>When the DB call fails, F1 completes exceptionally, all shared callers observe the failure, whenComplete() removes it, and the next request starts a clean attempt.</p><p>Timeouts hide a subtler trap. Suppose the caller times out at T=5 but the database keeps working:</p><pre>T=0   App starts DB request #1<br>T=5   caller times out, entry removed<br>T=6   new request starts DB request #2<br>T=10  DB request #1 finally completes  ← duplicate work</pre><blockquote><strong>The lesson:</strong></blockquote><blockquote>A caller giving up is not the same as cancelling the underlying operation.</blockquote><p>A production implementation must define cancellation semantics deliberately.</p><p>Retries compound the risk. If a coalesced operation covering 1,000 callers fails and all 1,000 retry at once, you’ve manufactured a thundering herd. Coalescing is therefore usually paired with bounded retries, exponential backoff with jitter, circuit breakers, and caching.</p><h3>Coalescing vs. Caching</h3><p>These are complementary, not competing:</p><ul><li><strong>Caching</strong> stores a <em>completed result</em>: &quot;user:123&quot; → User</li><li><strong>Coalescing</strong> tracks an <em>operation in progress</em>: &quot;user:123&quot; → Future&lt;User&gt;</li></ul><p>Together they defend against a cache stampede:</p><pre>Request ──&gt; check cache ──HIT──&gt; return<br>               │<br>              MISS<br>               │<br>          check in-flight ──EXISTS──&gt; join existing Future<br>               │<br>          NOT EXISTS<br>               │<br>          start DB op ──&gt; store in cache ──&gt; complete Future</pre><p>One subtlety: coalesced callers all receive the result computed at a single moment. If the fetch starts and a caller joins four seconds later, that caller gets four-second-old data. Usually harmless, but worth reasoning about deliberately when freshness is critical. Relatedly, the registry key must capture <em>everything</em> that distinguishes the result — not just the ID, but any parameter, tenant, or auth scope that changes what gets returned. Coalescing requests that only <em>look</em> identical is a correctness bug.</p><h3>When Coalescing Is the Wrong Tool</h3><p>Coalescing is a win only for <strong>read-heavy, idempotent, cacheable</strong> operations where duplicate work is genuinely wasteful. It backfires elsewhere:</p><ul><li><strong>Writes and non-idempotent operations.</strong> Ten POST requests are usually ten distinct intents. Collapsing them into one silently drops nine.</li><li><strong>Requests that differ per caller.</strong> If the result depends on who’s asking — permissions, tenant, feature flags — sharing one Future leaks one caller’s data to another. (This is the key-scope problem above, stated as a hard rule: if the output can differ, don’t coalesce.)</li><li><strong>Cheap or rarely-contended operations.</strong> The registry, the callbacks, and the cleanup all cost something. If duplicate calls are rare or trivially cheap, coalescing adds complexity for no benefit.</li></ul><p>The technique earns its keep specifically when identical, expensive reads pile up under concurrency — not as a default wrapper around everything.</p><h3>Scaling Out: Why Local Coalescing Breaks</h3><p>Most systems run several instances behind a load balancer, and each JVM has its own ConcurrentHashMap. Three requests for the same user landing on three instances produce three separate Futures — and three DB calls:</p><pre>App-1: user:123 → F1 ──&gt; DB<br>App-2: user:123 → F2 ──&gt; DB<br>App-3: user:123 → F3 ──&gt; DB</pre><p>The coalescing benefit is gone across instances. To recover it we need shared coordination — but note the key constraint:</p><blockquote>You cannot put a CompletableFuture in Redis. A Future is a JVM-local object.</blockquote><p>So distributed coalescing coordinates <strong>who does the work</strong>, while each instance still uses local Futures for its own callers.</p><h3>Coordination with Redis</h3><p>A distributed lock is one approach. An instance tries an atomic set-if-absent with an expiry:</p><pre>SET request-lock:user:123 &lt;token&gt; NX EX 5</pre><p>NX creates the key only if absent; EX 5 expires it after five seconds. Whoever wins becomes the leader and performs the DB call; the others are followers who need to obtain the result. Two common ways to propagate it:</p><ul><li><strong>Store the result in Redis</strong> (user-result:123 → User), which followers then read.</li><li><strong>Publish via Pub/Sub</strong>, notifying followers directly — but Pub/Sub messages aren’t durable, so a follower disconnected at publish time misses it. A fallback is required. <strong>Redis Streams</strong> offer durable delivery at the cost of added complexity.</li></ul><h3>The lock-TTL problem</h3><p>If the lock’s TTL is shorter than the operation, it expires mid-flight and a second instance acquires it — two DB calls again:</p><pre>App-1 holds lock (TTL 5s) ──&gt; DB takes 10s<br>T=5  lock expires<br>     App-2 acquires lock ──&gt; DB</pre><p>Mitigations — longer TTLs, lock renewal/heartbeats, fencing tokens — each add complexity. The same TTL/expiry mechanism is also what lets the system recover if the leader crashes: the lock eventually expires and a follower takes over.</p><h3>Coordination with ZooKeeper</h3><p>ZooKeeper is purpose-built for distributed coordination (leader election, locks, membership, failure detection). A common pattern uses <strong>ephemeral sequential nodes</strong>:</p><pre>/coalesce/user:123/<br>    request-00001  → Leader   (lowest sequence)<br>    request-00002  → Follower<br>    request-00003  → Follower</pre><p>Because the nodes are <em>ephemeral</em>, if the leader’s session dies, ZooKeeper removes its node automatically and request-00002 becomes the new leader — clean failover without manual TTL tuning.</p><p>But ZooKeeper is the <strong>coordination layer, not the result-sharing layer</strong>. It decides who owns the work; the result still has to travel through a cache or messaging system.</p><h3>Do You Even Need to Build This?</h3><p>Usually not. The from-scratch version above is worth understanding because it shows what’s happening under the hood — but in production, prefer a maintained implementation:</p><ul><li><strong>Go:</strong> the standard golang.org/x/sync/singleflight package is the canonical implementation. Its very name is the concept: at most one flight of a given key at a time.</li><li><strong>JVM:</strong> Caffeine’s LoadingCache coalesces concurrent misses automatically — a request for a key already being loaded waits on the in-progress load rather than starting its own. For most Java services this is the right answer, not a hand-rolled ConcurrentHashMap.</li></ul><p>Whatever you use, add a metric for the <strong>coalesced-hit ratio</strong> (how many requests joined an existing operation versus started a new one). Without it you can’t tell whether coalescing is actually firing or silently doing nothing.</p><h3>Prefer the Simplest Architecture</h3><p>Reaching for a distributed lock on every request is usually the wrong instinct. Ask first whether you truly need <em>distributed</em> coalescing. Often this layered approach is enough:</p><pre>Request ──&gt; L1 local cache ──miss──&gt; L2 Redis cache ──miss──&gt;<br>        local request coalescing ──&gt; Database</pre><p>This gives fast local reads, a shared cache across instances, reduced DB traffic, and coalescing of concurrent misses — without a distributed lock in the hot path.</p><h3>The Deeper Lesson</h3><p>The local implementation is genuinely simple: ConcurrentHashMap + CompletableFuture + computeIfAbsent() + whenComplete(). The complexity lives in distribution, where you must reason about leader election, lock expiration, leader crashes, partitions, duplicate execution, result propagation, retries, cancellation, stale data, and thundering herds.</p><blockquote>Distributed request coalescing isn’t only a concurrency problem — it’s a distributed coordination problem.</blockquote><p>Mentally, the local version is a fan-in of callers onto one Future; the distributed version is a fan-out of instances onto a coordination layer that decides ownership and routes the result back.</p><p>The idea starts deceptively small — <em>if ten requests need identical work, why do it ten times?</em> Locally the answer is elegant. The moment the system spans machines, the question becomes: across many nodes, who does the work, how do the others find the result, and what happens when that node disappears? That’s where a small concurrency optimization becomes a genuinely interesting distributed-systems problem.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=85ff4a8f49dd" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/request-coalescing-preventing-duplicate-work-in-high-concurrency-systems-85ff4a8f49dd">Request Coalescing: Preventing Duplicate Work in High-Concurrency Systems</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Transactional Design Pattern to enforce consistency through code]]></title>
            <link>https://levelup.gitconnected.com/transactional-design-pattern-to-enforce-consistency-through-code-127c75b660e5?source=rss-848ec7d41b8c------2</link>
            <guid isPermaLink="false">https://medium.com/p/127c75b660e5</guid>
            <dc:creator><![CDATA[Abhishek Gupta]]></dc:creator>
            <pubDate>Tue, 04 Jul 2023 03:47:07 GMT</pubDate>
            <atom:updated>2023-07-04T03:47:07.241Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*NNX6NRMRDStaeaoSXo2zng.png" /><figcaption>credits: netlify.app</figcaption></figure><h4>Who is the target audience?</h4><p>This article is intended for primarily software developers, technical architects and those who are learning about incorporating scalable designs in their code</p><h4>What will you learn from this article?</h4><p>You will learn about how can few operations be bound to exhibit atomicity and transactional (either all of them succeed, or all of them rollback) behavior. We would be going through the code samples in Java, however, the same ideologies can be further implemented in any language of choice.</p><p>Let’s begin…</p><pre>try{<br>  execute();<br>}catch(Exception e){<br>  rollback();<br>}</pre><p>The above code is enough to summarize the intent of this article.</p><p>Execute. Rollback. Done.</p><p>Let me share a low-level-code design scenario.</p><p>Imagine, you (as a die-hard developer) is working on a feature. And the feature demands more than one operation(like, always), which are tied together, have to be performed in sequence. However, the condition is that either all actions execute successfully, or none. This is to ensure atomicity of entire operation.</p><p>Let’s consider an example. Suppose you are a car assembler who outsourses the raw materials such as tyres, engines, body, etc from various manufacturers and then puts the pieces together to finally ship the car. You cannot ship an incomplete car. Therefore, the method implementation may look like as follows (skipping the details for brevity):</p><pre>public void assemble(){<br>  orderTyres();<br>  orderEngine();<br>  orderBody();<br>  ...<br>}</pre><p>This poses an interesting challenge. Suppose, you have already successfully placed order for Tyres and an engine. However, the order for body failed due to shortage of supply. Now, what do you do? You cannot go ahead assembling the car without a body, would you? This is called maintaining<strong> consistent </strong>state.</p><p>To address this problem, you have to catch the exception and start rolling back the operations one by one that were to be executed during the assembling process. It would look something like following:</p><pre>public void assemble(){<br>  try{<br>    orderTyres();<br>    orderEngine();<br>    orderBody();<br>    ...<br>  }catch(AssemblyFailedException ae){<br>    ...<br>    rollbackBody();<br>    rollbackEngine();<br>    rollbackTyres();<br>  }<br>  <br>}</pre><p>Notice that the order of rollback in the catch block is exactly opposite to the order of execution in the try block. This is to ensure assertiveness of any transactional operation. Still, the above solution has few problems with this approach.</p><ol><li>No matter at what stage assembly operation fails, the above code attempts to rollback all set of operations, some of which may not even have been executed. This can further lead to undesirable side-effects. The e<strong><em>xpectation</em></strong> is — only the successful operations should be attempted for rollback, and not all. It’s no point cancelling the order for seats, if the order itself was never placed in the first place.</li><li>The above approach requires developer’s knowledge of adding a rollback process if a new operation has to be defined. If the developer forgets to add rollback for the new process, then it might lead to unexpected results or state of the system. <strong><em>Expectation</em></strong> is that developer should be <strong>forced</strong> to define the rollback process but should never worry about when to execute that rollback. This ensures a good amount of decoupling between the execution criteria(dealing with order or rollback) and the high level operation itself (the assembly process).</li></ol><p>Now, since the problem statement is clear, let’s jump to the solution and see how we can solve this problem while honoring the SOLID design principles.</p><h4>Design</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/681/1*tX8WBWGc3STb9rfmhbD6cQ.png" /></figure><p>At 10,000ft, this is is the picture you get where:</p><ol><li><strong><em>TaskContext</em></strong> is an interface (or abstract class) whose contract contains only execute and rollback methods. <strong><em>TaskA</em></strong> and <strong><em>TaskB</em></strong> resemble the tasks that need to adhere to the <strong><em>TaskContext</em></strong> in order to become part of the atomicity of the entire transaction</li><li><strong><em>TaskManager</em></strong> is the controller class, which maintains the state of each task that has been executed and rolls back each one that has been processed successfully in the past as part of the entire transaction.</li></ol><p>More precisely, the code for <strong><em>TaskContext</em></strong> and <strong><em>TaskManager</em></strong> looks as below:</p><p><strong>TaskContext</strong>:</p><pre>package com.example.task;<br><br>public abstract class TaskContext {<br><br>    private TaskContext nextTask;<br><br>    public abstract void execute() throws Exception;<br><br>    public abstract void rollback() throws Exception;<br><br>    public void next(TaskContext nextTask){<br>        if(nextTask != null){<br>            this.nextTask = nextTask;<br>        }<br>    }<br><br>    public boolean hasNextTask(){<br>        return this.nextTask != null ;<br>    }<br><br>    public TaskContext getNextTask(){<br>        return this.nextTask;<br>    }<br><br>}</pre><p><strong>TaskManager:</strong></p><pre>package com.example.task;<br><br>import lombok.extern.slf4j.Slf4j;<br><br>import java.util.LinkedHashMap;<br>import java.util.Map;<br>import java.util.Stack;<br><br>@Slf4j<br>public class TaskManager {<br><br>    private TaskContext entryTask;<br>    private Stack&lt;TaskContext&gt; rollbackTasks = new Stack&lt;&gt;();<br><br>    public TaskManager(TaskContext entryTask){<br>        this.entryTask = entryTask;<br>    }<br><br>    public void execute() throws Exception {<br>        executeTask(entryTask);<br>    }<br><br>    private void executeTask(TaskContext task) throws Exception {<br>        if(task != null){<br>            task.execute();<br>            rollbackTasks.add(task);<br>            if(task.hasNextTask()){<br>                executeTask( task.getNextTask());<br>            }<br>        }<br>    }<br><br>    public void rollback() throws Exception {<br>        while(!rollbackTasks.isEmpty()){<br>            Task taskToRollback = rollbackTasks.pop();<br>            try{<br>                taskToRollback.rollback();<br>            }catch (Exception e){<br>                log.error(&quot;Rollback for task {} failed with error &quot;, taskToRollback.getClass().getName(), e);<br>            }<br>        }<br>    }<br>}</pre><p>Let’s define a few tasks based on our previous example to order tyres, engine and body.</p><p><strong>OrderTyresTask:</strong></p><pre>package com.example.task;<br><br>import lombok.extern.slf4j.Slf4j;<br><br>@Slf4j<br>public class OrderTyresTask extends TaskContext{<br><br>    @Override<br>    public void execute() throws Exception {<br>        log.info(&quot;Ordering the tyres now&quot;);<br>    }<br><br>    @Override<br>    public void rollback() throws Exception {<br>        log.warn(&quot;Rolling back the orders for tyres&quot;);<br>    }<br>}</pre><p><strong>OrderEngineTask:</strong></p><pre>package com.example.task;<br><br>import lombok.extern.slf4j.Slf4j;<br><br>@Slf4j<br>public class OrderEngineTask extends TaskContext{<br><br>    @Override<br>    public void execute() throws Exception {<br>        log.info(&quot;Ordering the engine now&quot;);<br>    }<br><br>    @Override<br>    public void rollback() throws Exception {<br>        log.warn(&quot;Rolling back the orders for engine&quot;);<br>    }<br>}</pre><p><strong>OrderBodyTask:</strong></p><pre>package com.example.task;<br><br>import lombok.extern.slf4j.Slf4j;<br><br>@Slf4j<br>public class OrderBodyTask extends TaskContext{<br><br>    @Override<br>    public void execute() throws Exception {<br>        log.info(&quot;Ordering the body now&quot;);<br>    }<br><br>    @Override<br>    public void rollback() throws Exception {<br>        log.warn(&quot;Rolling back the orders for body&quot;);<br>    }<br>}</pre><p>Now let’s plug them together in the main application</p><pre>package com.example.task.app;<br><br>import com.example.task.*;<br>import lombok.extern.slf4j.Slf4j;<br><br>@Slf4j<br>public class AssemblyMainApp {<br><br>    public static void main(String[] args) throws Exception {<br>        // Registering the tasks in order<br>        TaskContext orderTyresTask = new OrderTyresTask();<br>        TaskContext orderEngineTask = new OrderEngineTask();<br>        TaskContext orderBodyTask = new OrderBodyTask();<br><br>        // Now, let&#39;s chain them together<br>        orderEngineTask.next(orderBodyTask);<br>        orderTyresTask.next(orderEngineTask);<br><br>        TaskManager taskManager = null;<br>        try{<br>            taskManager = new TaskManager(orderTyresTask);<br>            // Execute the tasks by just invoking task manager<br>            taskManager.execute();<br>        }catch(Exception e){<br>            assert taskManager != null;<br>            // Execute the rollback by invoking rollback from the task manager<br>            taskManager.rollback();<br>        }<br><br>    }<br>}</pre><p><strong>Successful Output:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u2Tjqk3nwprY5BDDhacoIA.png" /><figcaption>Orders being processed in the order</figcaption></figure><p><strong>Failed output: </strong>Assuming that ordering body failed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v31PRjRFE82yTwXtW-V-uA.png" /></figure><h4>Conclusion:</h4><p>This resulting code exhitbits atomicity and transactional nature.</p><p>Atomicity — OrderTyres, OrderEngine and OrderBody are grouped as an atomic task</p><p>Transactional — if any of the above task fails, it is rolled back automatically.</p><p>Hope you enjoyed reading the article and learnt something new!</p><h4>Reference:</h4><p><strong>Github Link</strong>: <a href="https://github.com/abhi10005/design-patterns/tree/master/execute-rollback">https://github.com/abhi10005/design-patterns/tree/master/execute-rollback</a></p><h2>Level Up Coding</h2><p>Thanks for being a part of our community! Before you go:</p><ul><li>👏 Clap for the story and follow the author 👉</li><li>📰 View more content in the <a href="https://levelup.gitconnected.com/?utm_source=pub&amp;utm_medium=post">Level Up Coding publication</a></li><li>💰 Free coding interview course ⇒ <a href="https://skilled.dev/?utm_source=luc&amp;utm_medium=article">View Course</a></li><li>🧠 AI Tools ⇒ <a href="https://www.aimind.so/">View Now</a></li></ul><p>🔔 Follow us: <a href="https://twitter.com/gitconnected">Twitter</a> | <a href="https://www.linkedin.com/company/gitconnected">LinkedIn</a> | <a href="https://newsletter.levelup.dev/">Newsletter</a></p><p>🚀👉 <a href="https://jobs.levelup.dev/talent/welcome?referral=true"><strong>Join the Level Up talent collective and find an amazing job</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=127c75b660e5" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/transactional-design-pattern-to-enforce-consistency-through-code-127c75b660e5">Transactional Design Pattern to enforce consistency through code</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to retain Hadoop logs longer on data nodes without worrying about high disk usage?]]></title>
            <link>https://medium.com/whatfix-techblog/how-to-retain-hadoop-logs-longer-on-data-nodes-without-worrying-about-high-disk-usage-a1258a5df6cb?source=rss-848ec7d41b8c------2</link>
            <guid isPermaLink="false">https://medium.com/p/a1258a5df6cb</guid>
            <category><![CDATA[datanodes]]></category>
            <category><![CDATA[hadoop-cluster]]></category>
            <category><![CDATA[script]]></category>
            <category><![CDATA[hadoop]]></category>
            <category><![CDATA[logs]]></category>
            <dc:creator><![CDATA[Abhishek Gupta]]></dc:creator>
            <pubDate>Fri, 04 Jun 2021 04:46:29 GMT</pubDate>
            <atom:updated>2021-06-04T04:46:29.480Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/390/1*6Crq4FMAn1wL_p5ol2pguQ.jpeg" /><figcaption>Courtesy: <a href="https://techdifferences.com/">https://techdifferences.com/</a></figcaption></figure><p>With distributed systems, come distributed challenges. When we focus extensively on improving one area, and not paying enough attention to the others, unforeseen challenges are bound to come. Things can turn ugly pretty quickly if they remain unaddressed in time.</p><p>At <a href="https://whatfix.com/">Whatfix</a>, we strive to provide improved experiences to both, the customers and fellow engineers. As an improvement in one of our infrastructure components, we had to upgrade the Hadoop version from 1 to 3. The performance improvements of using Hadoop 3 were significantly visible, right from day 1 of the upgrade. However, it can be treated as a different discussion altogether.</p><h3>Setting up the ground work</h3><blockquote>I will be using job and application interchangeably, but they imply the same things with the context of this article</blockquote><p>By default, for any Hadoop job that runs, the associated logs and temporary resources (found in <strong><em>/tmp/hadoop-&lt;user&gt;</em></strong> by default) get deleted almost immediately. However, we wanted to retain the logs for 15 days duration for addressing some use cases as required by one of the teams who would be using Hadoop for their jobs. We could achieve that by setting the following property in the yarn-site.xml. The value is in seconds.</p><h4>yarn.nodemanager.delete.debug-delay-sec=abc</h4><p>Good so far. But wait! Little did we know we were falling into a self-built trap. The retention duration not only applies for logs, but also for the temporary data associated with the jobs, which gets stored in<strong> <em>/tmp/hadoop-&lt;user&gt;/nm-local-dir/usercache/&lt;user&gt;/appcache/application_*</em></strong><em>. </em>That is where the problem starts.</p><p>The <strong><em>/tmp</em></strong> resource folder stores and tracks the intermediate resources needed by the application for a successful run. It consists of job.xml, relevant jar files, container wise information, map/reduce attempt information, intermediate and final outputs, etc. Subjected to the nature of a job, the size of the application<strong> <em>/tmp</em></strong> resources could vary. It could be anywhere from Kbs to Gbs, or even beyond that. Besides, these resources are managed entirely by Hadoop. The user’s application or job has no idea of the processings involved where it eventually led to bulky resource folders.</p><h3>The Impact</h3><p>One fine early morning around 4 a.m IST, we started getting alerts via AppDynamics on low disk space available on a couple of data nodes. At first, we thought it to be a temporary glitch and might settle down by itself. However, in a matter of a few minutes, almost all the data nodes started alerting of low disk space. It took us some time to realise the issue with <strong>/tmp</strong> folder consuming more than 90% of the disk space. On digging further, we found that an application was trying to process downloaded data from an external data source. But since there was not enough disk space for storing the processed data, Hadoop would kill the container and re-launch the application on another data node, without deleting the information from the previous data node. The application would then again start downloading data on the subsequent data node and process. This single application almost brought down the entire Hadoop cluster. As an immediate resolution, we killed the running application and cleared the <strong><em>/tmp</em></strong> data associated with the application. The RCA was the lack of sufficient disk space for the application to process.</p><h3>Solution Approaches</h3><p>We came up with some approaches as described below. It is beneficial to discuss the pros and cons of each one before implementation.</p><ol><li><strong>Manual cleaning of <em>/tmp</em> resources — </strong>As software engineer, we should never resort to such a thing, if we are looking for a long-term solution. Besides, it becomes difficult to manually monitor and clean up when the system tends to scale up.</li><li><strong>Reduce the retention duration </strong>— As an immediate solution, this approach could work. As described above, retention time is applicable for application logs as well as <strong><em>/tmp</em></strong> resources. We would then need to compromise with the retention duration for logs, as well. However, it would also go on toss if the number of applications in a given unit of time increase or start processing more unit of data. Hence, this is not a scalable solution either. Besides, any changes made to configuration files would require Hadoop to restart and incur additional downtime.</li><li><strong>Hadoop level management — </strong>Unfortunately, no such privilege exists with Hadoop to date for managing the<strong> <em>/tmp</em></strong> resources alone. If it did, life would have been full of roses!</li><li><strong>Moving logs to a separate location </strong>— We started working on moving logs to Kibana so that we can reduce the retention duration to only a few hours or minutes before Hadoop clears them up. However, it was required to identify the logging patterns for parsing so that the logs can be accessed using Kibana Query Language. The only challenge was with the parsing as we did not want to leave out any crucial information related to the application which would require us to monitor logs through Kibana and double-check that it throws out whatever we expect out of it. Hence, we could not entirely switch to this solution before being 100% confident on the delivery through KQL (Kibana Query Language).</li><li><strong>Script to clear /tmp on each data node </strong>— We felt that it would be easier if we could have a service that could easily remove the <strong>/tmp</strong> resources of the finished application periodically. We chose to write a Linux service as it is a lightweight process that does not need an overhead of restarting any additional component. This service would need to run on each data node.</li></ol><blockquote><strong>This article is to discuss Solution#5 in detail<em>.</em></strong></blockquote><p>Before we discuss the exact solution, let us take a look at the elements involved in it.</p><ol><li>Namenode IP address — If you are running namenode on the same machine, then 0.0.0.0 can work for you. We will use this address to hit the namenode server to extract information for each application.</li><li>Temporary resource directory location on disk- usually it is under <strong>/tmp</strong> folder by default. But in case you have overridden, you need to provide the path. Ex: On my machine path would be like <strong>/tmp/hadoop-abhishek/nm-local-dir/usercache/abhishek/appcache</strong></li><li>Terminal states — Hadoop supports three terminal states — FINISHED, KILLED and FAILED. It is easy to work with these states than with all of them. These states are useful to track the status of each application.</li><li>Error handling — Interestingly, Hadoop manages only up to the latest 1000 finished/completed jobs at once(also configurable through the property) of which we can track status. Accessing information through the URL that we will be using to get the state of a job that goes beyond the latest 1000 jobs would result in a Hadoop thrown exception. Hence, we need to handle the same in our script.</li><li>Get status of a application : http://&lt;namenode IP&gt;:8088/ws/v1/cluster/apps/&lt;application_id&gt;/state</li></ol><p>Following is a ready-to-use script: <a href="https://github.com/abhi10005/hadoop-tmp-cleanup/tree/master">Github Link</a></p><p>This script can be run as a standalone application or as a Linux based service on every data node. However, in production, it is preferred to have it as Linux based service. We are using <strong>systemctl</strong> (a Linux based service) to manage our script.</p><p>Few caveats before using the above script:</p><ol><li>Provide the correct path to your resource directory that is used by Hadoop to manage application resources. (Field = application_dir)</li><li>Provide the correct namenode IP address for your environment. (Field = namenode_ip)</li><li>This script will run at every 120-sec interval. You might not want that. Hence make sure to change the sleep time based on your requirements.</li></ol><p>Having done this, you are all set to use the Hadoop cluster without worrying about the high disk consumption of the finished applications and also retaining Hadoop application logs longer.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a1258a5df6cb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/whatfix-techblog/how-to-retain-hadoop-logs-longer-on-data-nodes-without-worrying-about-high-disk-usage-a1258a5df6cb">How to retain Hadoop logs longer on data nodes without worrying about high disk usage?</a> was originally published in <a href="https://medium.com/whatfix-techblog">WhatfixEngineeringBlog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unit Testing 101]]></title>
            <link>https://medium.com/whatfix-techblog/unit-testing-101-714b507da2ef?source=rss-848ec7d41b8c------2</link>
            <guid isPermaLink="false">https://medium.com/p/714b507da2ef</guid>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[unittest]]></category>
            <category><![CDATA[unit-testing-fundamentals]]></category>
            <dc:creator><![CDATA[Abhishek Gupta]]></dc:creator>
            <pubDate>Thu, 22 Oct 2020 01:50:34 GMT</pubDate>
            <atom:updated>2020-10-22T01:50:34.908Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*6P2ECWnBoZEThPjZrlFLmA.png" /></figure><p>How often do you run into a late-night bug fix in the production only to realise that it turned out to be a silly code mistake which could have been avoided even before raising a <a href="https://www.atlassian.com/git/tutorials/making-a-pull-request">pull request</a> itself?</p><p>Or beat this — How often do you spend sleepless nights brooding over your code that had just hit the production where you have no idea if existing functionalities have remained intact as always?</p><p>All mature software engineers go through such phases in their career. However, nobody likes to remain glued to the dumb screen in the middle of the night, fixing a production bug. Including me!</p><p>As wise people say — prevention is better than cure, smart software engineers follow the same. They write plenty of extensive test cases only to sleep peacefully at night! I have always believed that Unit Testing is not Quality Engineers responsibility but lies with the developer.</p><p>There are <a href="https://blog.testlodge.com/types-of-test-cases-in-software-testing/">several kinds of testing</a>. Unit Testing is one of them.</p><h3>What is Unit Testing</h3><p>Unit testing is the most basic level of testing that should be done right at the development phase. It has to do with the methods of a class only and not with the whole project or with any other external interactions, be it another component or database, etc. Unit testing intends to validate whether a “unit” piece of work within a module is <strong>independently functioning</strong> as expected or not, given any variation of acceptable valid or invalid inputs. Ex: What if <strong>null </strong>is passed as an argument?</p><blockquote>What is a “unit”?</blockquote><blockquote>A unit is an independently manageable and testable code that can be :</blockquote><blockquote>1. an individual method with a clearly defined responsibility to test</blockquote><blockquote>2. functionality exhibited by method(s) aimed to achieve a certain goal/output.</blockquote><p>As mentioned above, unit testing should always be provisioned during the development cycle of a feature/component, not after a feature hits the production. Another way to drive development is by writing test cases with stubs in advance and then developing the feature around it. That is called <a href="https://en.wikipedia.org/wiki/Test-driven_development">Test Driven Development or TDD.</a> For TDD to work effectively, the requirements should be well-known beforehand so that the test cases can be defined accordingly.</p><blockquote><em>If it gets too hard to identify and test a unit then always break the unit in sub-units which are easier to manage. Lesser complicated the code, the easier it is to test.</em></blockquote><h3>How to Unit Test in Java</h3><p>Java provides a <a href="https://junit.org/junit5/">JUnit</a> library, which helps in writing test cases in isolation. Let’s see a sample structure of JUnit Test</p><p>import org.junit.Assert.*<br>import org.junit.Before<br>import org.junit.Test</p><p>public class SampleJUnitTest {</p><p>@Before<br> public void setup() {<br> // Setup the class dependencies here<br> // Which are required to run a successful test<br> }</p><p>@Test<br> public void testSomeMethod() {<br> // Call the required logic<br> // Assert the returned result<br> }<br> <br> @After<br> public void tearDown(){<br> // De-initalize the resources, if any after each test run<br> }<br> <br>}</p><p>All the above annotations used in above code snippet carry a special meaning in terms of execution:</p><ol><li><strong>@Before</strong> — indicates the JVM to run the <em>setup</em> method before each test case</li><li><strong>@Test — </strong>Test case to test the “unit”.</li><li><strong>@After — </strong>Runs after each test case, primarily used to de-allocate resources after each test case.</li></ol><blockquote>JUnit5 comes with the added support of JUnit Jupiter and Vintage. That’s like adding a turbocharger to your basic car. Ex: Jupiter enables nesting of test cases, parallel executions, timeouts, etc.</blockquote><blockquote>Ref: <a href="https://junit.org/junit5/docs/current/user-guide/">https://junit.org/junit5/docs/current/user-guide/</a></blockquote><h4>Naming convention recommendation:</h4><p>It’s always recommended to have appropriate naming conventions for variables, methods, classes, packages, projects, etc. So why should a test case be any different?</p><p>However, a verbose test case often expresses clearly what it is supposed to test, including what it is expecting as input/output for test case execution.</p><p>As an example, if I am testing login functionality, I usually follow these templates for naming a test case:</p><ol><li><strong>testActionWhenInputExpectOutput </strong>— Eg. testLoginWhenNullUserNameExpectInvalidDetailsMessage. This test case simply (and clearly) specifies what it’s testing. If a null username is passed, “invalid details” message is expected.</li><li><strong>testActionWhenInputThrowException</strong> — Eg. testLoginWhenIncorrectCredentialsThrowUserAccessException. This test case will test the login flow for checking if the code under test (CUT) throws UserAccessException or not on providing incorrect credentials.</li></ol><p>It’s plain simple English, eh?</p><blockquote>Do not be conservative on the length of the test case name. If the test case name gets too long, it’s still okay. The idea is to have a name as verbose as possible.</blockquote><blockquote>Imagine this — there will be 100 or 1000 of test cases for any project, and it would become a tedious task to look into each failed test case to understand what it is doing. Hence, keep the name such that it is intuitive enough for others to read and derive the meaning out of it.</blockquote><h4>Interactions with external objects/components:</h4><p>Till now, we have discussed to test a “unit” for each test cases. However, in real-world software, you wouldn’t find the “unit” operating in complete isolation. There are high chances that the “unit” will interact with objects of other classes. In essence, several “units” come together to collaborate and bring out the required behaviour of the system. Have a look at the below diagram</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/671/1*SbGvqjULVXiM-uYObjfEnA.png" /></figure><p>As established above, we should write unit tests for Class A and Class B separately. Logically, we should write unit tests of Class B before we write those for Class A as the methods of Class B are expected to be used outside its scope. Hence, all the “units” of Class B must be extensively tested of their expected behaviour and functionality.</p><p>When a unit of any other class (like Class A in our example) interact with a unit of Class B, <strong>we need not re-test the behaviour of Unit 2 </strong>while testing <strong>Unit 1</strong> as it is understood that Class B works as expected. Hence, we <strong>mock </strong>the interaction between <strong>Unit 1</strong> and <strong>Unit 2</strong>. Mocking allows <strong>unit 1 </strong>to proceed ahead with the execution without being involved in the unnecessary execution cycles by <strong>Unit 2</strong>.</p><blockquote>We should only mock those interactions where we are 100% sure that the mocked unit will behave exactly likewise for the real-world application.</blockquote><p>Mocking is incredibly handy when interaction across the units is processing intensive. E.g. if <strong>Unit 2</strong> makes a call to DB to fetch details of a user and then filters them out based on certain criteria. All these processing of <strong>unit 2</strong> will take some CPU cycles which don’t serve any purpose while testing <strong>unit 1.</strong> However, these interactions do serve great purposes during integration testing, which is outside the scope of this article.</p><blockquote>Java provides a handful of good mocking libraries like <a href="https://easymock.org/">Easymock</a>, <a href="http://jmock.org/">JMock</a>, <a href="https://site.mockito.org/">Mockito</a> and <a href="https://github.com/powermock/powermock/wiki/Mockito">PowerMock</a>. Now-a-days, developers prefer to use Mockito and PowerMock due to their simplicity of usage and wide range of mocking options.</blockquote><blockquote><strong>Did you know that you could also mock private and static methods using PowerMock?</strong></blockquote><h3>Limitations of Unit Testing</h3><p>No individual testing strategy is fool-proof. So is with the unit testing. Even though, having unit tests reduce the possibilities of bugs in the system exponentially, yet these are not 100% reliable. We have other forms of testing like integration testing, black box testing, UAT, etc to make the system more predictable and reliable. Let us visit some of the limitations of Unit testing:</p><ol><li>Since the scope of unit tests is limited to a class (or a group of class), we really cannot make out how the overall system performs.</li><li>As unit tests are written with an intention of only to test the functionality of the code, these are generally not used for testing performance. For performance testing, whole system interaction comes to play. Issues like latency, multi-threading, etc are hard to evaluate using unit tests.</li><li>Writing efficient unit tests is time taking. When code has to be refactored, associated unit tests also have to be modified.</li><li>Efficiency and effectiveness of a unit test are inversely proportional to the complexity of the “unit” under test. More complex the actual code, the lesser effective will the unit test grow out to be.</li></ol><h3>Conclusion</h3><p>From the above discussion, it’s clear that unit testing serves an important role in maintaining a healthy codebase. It is an assurance that the past written code doesn’t break with the new changes. In fact, in the absence of proper unit testing in place, there is no certain way of determining the correctness of code, and relying solely on manual testing of code is not always feasible. Unit testing works on the principle of <a href="https://dzone.com/articles/fail-fast-principle-in-software-development">fail fast, fail early</a>, i.e. fail as quickly as possible during the development phase itself. The longer it takes the discovery of the failure, the higher the impact on fixing it.</p><blockquote>The quality and quantity of unit tests determine the level of confidence in the system.</blockquote><p>Besides all the arguments, having good unit tests (as well as integration tests) gives a new developer an extensive idea of the whole system. For many developers like me, unit and integration tests are play area for familiarizing ourselves with the codebase and its functionalities.</p><p>Unit tests are also widely used for determining the code coverage — an area which gives an added assurance to the developer. It’s a good practice to have coverage as close to 100% as possible. Well written unit tests (along with good coverage) make the major refactoring of code (especially legacy ones) a smooth process as there are multiple possibilities of missing out on a few functionalities leading to production bugs otherwise.</p><blockquote>Code coverage can be checked at different stages e.g. development, testing, or deployment (by setting up CI/CD pipeline integrated with third party tools). However, for most organisations, developers have limited access to CI/CD pipelines (during deployment). Hence, it is often a best practice to have code coverage check done at the development phase itself(along with other stages). Almost all the IDEs can be equipped with plugins for testing code coverage. One such plugin is JaCoCo. With JaCoCo, you can even set the <a href="https://mkyong.com/maven/maven-jacoco-code-coverage-example/">build goals</a>.</blockquote><h4>After all, it’s not about always firefighting. It’s more about careful planning and execution!</h4><p>This is a series on Unit Testing. We will dive into depth in subsequent articles.</p><p>Hope you enjoyed reading this article. Show your support by claps and comments.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=714b507da2ef" width="1" height="1" alt=""><hr><p><a href="https://medium.com/whatfix-techblog/unit-testing-101-714b507da2ef">Unit Testing 101</a> was originally published in <a href="https://medium.com/whatfix-techblog">WhatfixEngineeringBlog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[EGO can be a charmer catalyst to growth]]></title>
            <link>https://medium.com/@abhishek10005/ego-can-be-a-charmer-catalyst-to-growth-bf2c3b579b30?source=rss-848ec7d41b8c------2</link>
            <guid isPermaLink="false">https://medium.com/p/bf2c3b579b30</guid>
            <category><![CDATA[productivity]]></category>
            <category><![CDATA[self-improvement]]></category>
            <category><![CDATA[ego]]></category>
            <category><![CDATA[self-awareness]]></category>
            <dc:creator><![CDATA[Abhishek Gupta]]></dc:creator>
            <pubDate>Sat, 16 May 2020 11:56:35 GMT</pubDate>
            <atom:updated>2020-05-16T11:56:35.670Z</atom:updated>
            <content:encoded><![CDATA[<h3>EGO can be a charming catalyst to growth</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/660/1*J9yVLOQ1AOg8feQiCAQa7g.jpeg" /></figure><h4>Disclaimer: It’s real life experience</h4><p>It was year 2009, when I was preparing for engineering entrance exam.</p><p>Out of all the topics, PROBABILITY was the most scaring. Even with all my might, I was unable to get hold of the concepts. Hence, quite frequently I looked upon others for help. One of those help was from my best friend. Or so, as I had thought !!</p><p>One fine day, I reached out to him. A problem statement was bothering me. He looked at the problem. And then, looked at me with disgust. He mocked, “Forget that you can even solve this simple problem. You should rather forget probability”. That struck me as a bolt of lightening. I had always told myself earlier that I sucked at Probability. But such harsh words from a friend shattered me completely.</p><p>With heavy heart I walked back. But somehow, his words hit my ego. And I resolved to myself — “If ever, I get an opportunity to learn probability, I will master it”.</p><p>Two years later, God gave me an opportunity to prove myself. It was second year of engineering. In a batch of 250 students, only 15–20 of them had elected for probability and statistics. That means more than 90% of the batch went for other elective course to ditch probability.</p><p>I had two choices -</p><p>1. Go with 90% of my friends and forget about the past</p><p>2. Compete with 10% who were already thorough with the concepts. They obviously didn’t feel as an underachiever while signing up for the course.</p><p>I opted for (2). I worked hard at it. It was harder than I thought as engineering probability is advanced version. I felt defeated at times. With the same sinking feeling I had years back. But whenever I thought to quit, my ego wouldn’t allow me to.</p><p>Gradually, things started to make sense to me. I started helping out my friends who were lagging behind.</p><p>When the results were declared, I got A+ , along with another peer. That was such a relief for me. I had put in everything I had. I felt like an underdog. That old friend was no longer in touch, but till today, I look myself with respect.</p><p>I hear a lot of people pointing out, “You shouldn’t have ego.”. But for me it was my ego, which did something which was impossible and terrifying for me. It was my ego, which constructed a dream for me. And made me work towards it.</p><p>Today, when I decode this, I realize that empty and inflated ego is of no use. But when you attach a challenge or mission to your ego, you can see magic happening.</p><p>Same is applicable for people who don’t bother to change their existing conditions. All they need is ego with a mission. Not just only ego.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bf2c3b579b30" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Are you (over)thinking?]]></title>
            <link>https://medium.com/@abhishek10005/are-you-over-thinking-56fe70dfd5df?source=rss-848ec7d41b8c------2</link>
            <guid isPermaLink="false">https://medium.com/p/56fe70dfd5df</guid>
            <dc:creator><![CDATA[Abhishek Gupta]]></dc:creator>
            <pubDate>Sat, 04 Apr 2020 10:23:44 GMT</pubDate>
            <atom:updated>2020-04-04T10:23:44.522Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WgilMOlg6zFaC2eRFCayxw.jpeg" /><figcaption>Credit: Getty Images/iStockphoto</figcaption></figure><h3><strong>The Parable:</strong></h3><p>Once upon a time in an Indian village, a couple was having a discussion on purchasing a cow. It was dinner time hence an earthen pot was placed on earthen stove for cooking rice.</p><p>Ram: “I hear that a man in Chawdi Bazaar can arrange for a good breed cow.”</p><p>Sudha: “That’s exciting !! A good breed cow would definitely help us from this existing financial crisis”</p><p>Ram: “That’s for sure! In fact, I’ll go tomorrow itself to buy a cow”. Saying this, he placed the currency notes under the straw meant for sitting next to earthen stove.</p><p>That spread a smile on Sudha’s face as she longed to have a cow since she got married. Last year, she had insisted strongly to her husband, but the crops didn’t yield enough to have cow as a luxury. Moreover her neighbor, Radha, was getting prosperous by selling cow’s milk everyday. Hence, she got more excited than usual at the thought of having a cow. After a long series of imaginations, she said to her husband.</p><p>Sudha: “When we have our cow, I’ll sell their milk in the neighboring village. I have heard they pay good price”</p><p>Even Ram couldn’t resist the excitement at this thought. He said, “And then, with the money we get, we will buy another cow in a year”</p><p>Sudha: “And another one next year”. She closed her eyes happily imagining what her life would be then. She had never felt so relaxed before. She could then face Radha, eye-to-eye.</p><p>Ram: “And then, we can pay all our dues to bank and zamindar.”</p><p>Sudha, now completely transfixed said, “Then, I will send some milk to my brothers. I hope they appreciate us.”</p><p>Ram frowned at the thought. He said, “Where were your brothers when we needed them last year when the crops went dry. We are not going to give anything to them.”</p><p>Sudha, now less excited and more angry, “Why do you forget that they are my siblings. We share blood relationship”</p><p>This made Ram angrier and he punched a tight fist against other hand, “WE ARE NOT GIVING THEM ANYTHING”.</p><p>He got so angry that he kicked the burning stove which was still cooking rice inside the pot.</p><p>And the straw next to it caught fire immediately. So did the Rupees under the straw. These were the same Rupees which Ram was going to use to buy the cow from.</p><p>Immediately, both put their hands on their mouth with utter surprise and horror to what had happened. This was truly uncalled for. Tears welled up in both their eyes as they could do nothing. It was too late to realize!</p><h4>What did the parable teach us?</h4><p>No matter how disappointing the ending of the parable seems to be, but their lies a hidden message. That is overthinking. I define overthinking as :</p><blockquote>“Thinking beyond one’s capacity to perform in the present”</blockquote><p>You are overthinking when you do followings without taking appropriate actions:</p><ol><li>You have been wanting to change your job since quite some time.</li><li>You have been wanting to start a business</li><li>You want to propose a girl/boy you know of.</li><li>You want to write an article</li><li>You want to go for holidays.</li></ol><h4><strong>Overthinking is not same as thinking BIG</strong></h4><p>Do not confuse thinking big or setting goals with overthinking. Thinking for future is justified. Thinking big is also justified. But what isn’t is to lose your focus on what needs to be done in the present moment. When you set goals, you create a vision for yourself where you would like to reach. Then, next step is to take action.</p><p>In the parable, Ram and Sudha did set a goal, what they envisioned for themselves. But then they couldn’t stop themselves in creating an imaginary world. The only control they had was to buy a cow. But their thoughts spiraled way too much in future which was out of control for them.</p><p>This is somewhat relatable to entrepreneurs too. Most of the time, entrepreneurs tend to build castle in the air, without much proof on the ground. The first deal they break or the first few customers they get or the first funding they draw. Most businesses fail not because of lack of expertise but because of lack of vision or lack of ability to make decisions apt for current situation or both. Thinking too much in future for a business without properly attending to existing requirements has been fatal for such businesses.</p><h4>Why do we overthink?</h4><p>Have you noticed that you don’t overthink when you’re consciously involved into something? Like watching sci-fi movie or listening to relaxed music, or playing an instrument or watching cricket match. That’s because we are immersed into the act of performance (or at least being engaged into an act). We overthink only when we grant ourselves enough luxury of time, like while brushing our teeth, or waiting on somebody at the bus stop. Anything that doesn’t need our conscious involvement. So should we always indulge ourselves into doing something or other? Well, that’s not practical either. But we need to think deeper what causes us to overthink.</p><p>We tend to overthink when:</p><ol><li><strong>Fear </strong>takes over us. When we are uncertain of future and afraid of what might happen if things don’t go as planned. That’s a classic problem among entrepreneurs.</li><li>You are way more <strong>excited. </strong>I remember being over excited when I wrote my first game app during a college tech fest. I literally, couldn’t sleep 2 continuous nights as thought were circling around with what possibilities lay ahead of me.</li><li>You continuously reflect <strong>past incidents/events.</strong> Especially those which have left deep impression upon you. In such cases, you are somewhere stuck with those events in the present. You can’t get rid of those thoughts. Learning from past is wisdom, but not staying in it. It’s time to move on.</li><li>You <strong>overplan to avoid making mistakes</strong>. If making mistakes is not something to be found in your dictionary, buy a new dictionary! High achievers are not afraid to make mistakes. Stop being perfect. Perfection will only stop you from action. Instead, plan and then act.</li><li>You <strong>overanalyze every single decision</strong>. Don’t fall into the trap of overanalysis. It leads to paralysis of mind.</li><li>Too many <strong>distractions </strong>to defocus from your work, especially those of technology. Set the scope of your work and consciously shut out all the distractions.</li><li>You operate in an <strong>cluttered environment.</strong> Instead, try to adapt minimalism.</li></ol><h4><strong>Psychological drawback of overthinking</strong></h4><blockquote>Overthinking cripples our ability to make decision</blockquote><p>Overthinking has done more damage than any gains. It is an activity done in the present which has nothing to do about present. Few perfectionists believe that overthinking will improve their productivity. This is a complete farce.</p><p>Overthinking spirals us out of control and we get stuck in a loop. Every second you spend in overthinking, you move away from the action. It’s probably only activity our mind indulges in which leads to zero or less output. Haven’t you ever wondered that you feel tired after intensive overthinking. Your output is negligible and you don’t have any productivity at the end of the day. Yet, you feel mentally exhausted. This is the major drawback. Overthinking sucks energy out of you. Action restores mental energy.</p><h4>How to prevent overthinking?</h4><p>First of all, you need to identify that you are overthinking. If you look closer, you will find some pattern that correlates with you thinking methodologies. The important thing is that you need to keep a check on your emotions. Don’t let emotions, such as fear of failure, spiral you out of control. Following can be helpful in preventing overthinking:</p><ol><li>Try to incorporate 80/20 rule: Think 20% of time and act 80% of time</li><li>Not all thoughts that we encounter everyday are useless. Hence, keep a small notepad to note down your useful thoughts.</li><li>Practice meditation. There is no medicine to treat this psychological behavior. Only meditation and active thinking can help you with developing mindfulness.</li><li>De-clutter your environment. Practice minimalism</li><li>Develop the ability to put things in proper perspective. Having more than 1 perspective is very helpful.</li><li>If you have signs of anxiety or depression, it’s recommended to be in close circle of the people you love. Spend more time with them.</li></ol><p>If you liked the article, don’t forget to give a clap. Follow me for more such articles.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=56fe70dfd5df" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why self-help books won’t work upon you]]></title>
            <link>https://medium.com/@abhishek10005/why-self-help-books-wont-work-upon-you-e1769eacb6ee?source=rss-848ec7d41b8c------2</link>
            <guid isPermaLink="false">https://medium.com/p/e1769eacb6ee</guid>
            <category><![CDATA[creative-non-fiction]]></category>
            <category><![CDATA[self-improvement]]></category>
            <category><![CDATA[books]]></category>
            <category><![CDATA[creativity]]></category>
            <dc:creator><![CDATA[Abhishek Gupta]]></dc:creator>
            <pubDate>Wed, 07 Nov 2018 04:01:16 GMT</pubDate>
            <atom:updated>2018-11-07T04:01:16.409Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/760/1*RXCMkteFoJcqhrMkmtpy4w.jpeg" /></figure><p>I have been an avid reader of books. I have had a great fortune to have my parents inculcate the habit of reading since the very childhood. They used to bring me comics or storybooks with any potential to teach a lesson or moral values. Later, as I grew up, I took charge of this habit and began exploring the world of books on my own. Initially, it began with novels, thrillers, adventurous reads. However, later it converged to the self-help section which I have found to be quite enchanting. My interest of reading self-development books grew over a period of time and has converted into a habit (it wouldn’t be presumptuous if I call it an addiction). Little did I know that just an addiction to reading self-development content is not good enough.</p><p>Quite recently, I decided to read this book, <em>Power of Habit </em>by Charles Duhigg and I wished to experiment with its content. After reading sufficient reviews online, I formulated a list of habits(since the content of the book revolved around habits) that I wished to develop after I had finished reading the book. I wrote the list of habits on a piece of paper and then used it as a bookmark for this book.</p><p>Let me quickly explain the intention behind doing all of this. In his book <em>7 Habits of Highly Effective People</em>, Stephen Covey mentions in a chapter to “begin with an end in mind”. Interestingly, most areas of our lives revolve around goals and expectations. Reading self-help book is also one of them, but is rarely paid attention to. I experimented with the book to set my expectations what would I get after reading it. I didn’t know whether the content would be relevant to me or not. I just started. I had not imagined how fascinating this would turn out to be. Setting a goal or an expectation sets you on fire. You are no longer reading the book for mere amusement or killing time. Now, you are reading in search for answers (as in my case how to develop few habits or replace some of them).</p><p>Why make the paper, with a list of expectations, as a bookmark? Well, here’s what I implemented a technique supporting my subconscious mind. Using my goals as bookmarks ensured that I looked at it everytime I flipped through the pages of the book. <strong>And every time I looked at it, it signaled my brain to start thinking how to achieve those goals</strong>. <strong>This would make me Stop, Think, and Proceed while reading the book.</strong></p><p>The advantage of doing all of this is that you become goal oriented and can draw more out of the book that would have been missed otherwise.</p><p>Imagine yourself going to a well-renowned restaurant in your neighborhood. You glance over the menu and say “Bring me anything”. Isn’t that odd? The waiter would be puzzled but still politely ask your choice(It’s their job anyway!). Remember, the restaurant has plenty of good stuff to offer. However, they don’t know what would go with your taste. Would you still pay for <em>anything</em>? Obviously, not. Similarly, writing down your learning from a self-help book <em>after reading it </em>is like ordering anything that gets committed to your memory. Whereas, writing down what to expect in return of reading the book <em>before actually reading it </em>is like making your own choices. When you make your own choice, there’s a sense of pride and confidence. Do not remain at the mercy of leftovers.</p><p>To summarize, here are the steps to get maximum out of any book:</p><ol><li>Go through the reviews of the book before starting to read.</li><li>Make a list of relevant objectives from your personal or professional or social life which you’d want the book to help you with.</li><li>Write the list on a piece of paper and use it as a bookmark. You can get all creative you want to be.</li><li>Review your list at a regular interval, say every second night before going to bed. Check the items on the list as and when you see them getting accomplished.</li></ol><p>This not only holds good for physical books, but also for audio books and e-books.</p><p>Now let’s grab a book and take a plunge into the ocean of wisdom!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e1769eacb6ee" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>