<?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 Akash Shukla on Medium]]></title>
        <description><![CDATA[Stories by Akash Shukla on Medium]]></description>
        <link>https://medium.com/@akashshukla_1715?source=rss-18fac7af4925------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*UcKi6fxKak5KtBR7f8VRIA.jpeg</url>
            <title>Stories by Akash Shukla on Medium</title>
            <link>https://medium.com/@akashshukla_1715?source=rss-18fac7af4925------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 13:25:17 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@akashshukla_1715/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[Distributed Locks Are Not Enough: Why Fencing Tokens Matter]]></title>
            <link>https://medium.com/@akashshukla_1715/distributed-locks-are-not-enough-why-fencing-tokens-matter-2cdad7e85754?source=rss-18fac7af4925------2</link>
            <guid isPermaLink="false">https://medium.com/p/2cdad7e85754</guid>
            <category><![CDATA[resiliency]]></category>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[locks]]></category>
            <category><![CDATA[concurrency]]></category>
            <dc:creator><![CDATA[Akash Shukla]]></dc:creator>
            <pubDate>Wed, 21 Oct 2026 05:30:51 GMT</pubDate>
            <atom:updated>2026-10-21T05:30:51.802Z</atom:updated>
            <content:encoded><![CDATA[<p><em>An experiment in Go and Redis that turns a seemingly correct lock into a stale-write bug — and then fixes the ordering problem at the resource boundary.</em></p><p>Imagine two workers updating the same record. You add a Redis lock so only one worker can operate at a time. You use SET key value NX PX ttl, give it a sensible expiry, and release it only if the owner ID matches.</p><p>Looks safe, right?</p><p>It isn’t necessarily safe for <strong>correctness-critical writes</strong>. A worker can lose its lease without stopping its work. If another worker acquires the lock and commits a newer result, the old worker can still resume and overwrite it.</p><p>Let’s reproduce that bug, then introduce <strong><em>fencing tokens</em></strong>: monotonically increasing numbers that the <strong>resource being modified</strong> uses to reject stale requests.</p><h3>Why I started looking into this</h3><p>In my day-to-day backend work, I’ve dealt with Redis-based coordination, retries, asynchronous workflows, and changes to the infrastructure those systems depend on. That made me question an assumption I had been comfortable with: <strong>if a worker successfully acquires a distributed lock, is its subsequent write necessarily safe?</strong> The interesting edge case wasn’t two workers acquiring the same lock simultaneously, it was a worker that <em>used to</em> own the lock continuing to run after its lease expired. I decided to build a small, isolated experiment to understand that failure mode rather than relying on intuition. My biggest takeaway was that <strong>mutual exclusion at lock-acquisition time is not the same as protecting the resource from stale writes</strong>. This article walks through that learning with a reproducible Go and Redis example, not an account of a specific production incident.</p><blockquote><strong><em>Scope:</em></strong><em> This is an educational experiment with a single Redis instance and a Redis hash as the protected resource. The demo is deliberately not a production-ready locking system. We’ll cover why later.</em></blockquote><h3>1. Start with the usual Redis lock</h3><p>A common lock acquisition command is:</p><pre>SET demo:lock worker-A NX PX 300</pre><p>NX means “acquire only if the key does not exist.” PX 300 makes the lock expire after 300 milliseconds. The value identifies its owner so that unlock can use an atomic compare-and-delete operation rather than blindly deleting another worker&#39;s lock.</p><p>The expiry is useful: if worker A crashes, other workers don’t wait forever. But it’s a <strong>lease</strong>, not an instruction that automatically cancels the code running in A.</p><h3>2. Break it with a paused worker</h3><p>Here’s our controlled sequence:</p><ol><li>Worker A acquires the lock and begins work.</li><li>A pauses longer than the 300 ms lease. This models a long runtime pause, process suspension, or delayed operation — not a claim about a particular Go GC pause duration.</li><li>Redis expires A’s lock. Worker B acquires a new lease.</li><li>B writes newer-write-from-B to the resource.</li><li>A resumes and writes stale-write-from-A without realizing its lease expired.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9f2cV_07P0zPsPPIYgrzXQ.png" /><figcaption><em>Figure 1 — Redis correctly expires A’s lease, but expiration does not cancel A’s computation. B writes first; A resumes and overwrites it.</em></figcaption></figure><p>Both acquisitions were legitimate <strong>at the times they happened</strong>. Yet the final value is stale. A lock’s key disappearing does not invalidate an already-running CPU instruction, cancel an in-flight RPC, or rewind an old worker’s queued work.</p><h3>Why checking the lock again doesn’t fix it</h3><p>You might propose: “Before A writes, check whether it still owns the lock.”</p><p>That narrows the window, but doesn’t eliminate it. A can pause <em>after</em> its check and <em>before</em> the actual write. This is the familiar <strong>time-of-check to time-of-use (TOCTOU)</strong> race.</p><p>Even a carefully implemented release operation doesn’t address this: compare-and-delete prevents A from unlocking B’s lease, but doesn’t prevent A from writing stale data.</p><h3>3. Add fencing tokens</h3><p>Now imagine each successful lease acquisition receives a strictly increasing number:</p><pre>Worker A acquires lease  → token 1<br>Worker B acquires lease  → token 2</pre><p>Every write includes its token. The <strong>resource</strong> remembers the highest token it has accepted and rejects a write with a smaller token.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aRtJfqbbGowWqH7WTFntbg.png" /><figcaption><em>Figure 2 — Same scheduling, opposite result. The protected resource remembers token 2 and rejects A’s older token 1.</em></figcaption></figure><p>The crucial point isn’t the token alone: <strong>the destination must enforce it atomically with the write.</strong> If clients check the token in Redis and then perform an unguarded update in some other database, the same race is still possible.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fSWeC7T4-t_CRnz03c9aHw.png" /><figcaption><em>Figure 3 — The resource write gate, not a preliminary check in the caller, makes the correctness decision. Redis generates tokens only for this single-instance demonstration.</em></figcaption></figure><h3>Generate a token and acquire the lease atomically</h3><p>For our single-instance lab, a Redis Lua script combines checking the lease, incrementing a sequence, and establishing ownership:</p><pre>if redis.call(&#39;EXISTS&#39;, KEYS[1]) == 1 then<br>  return -1<br>end<br>local token = redis.call(&#39;INCR&#39;, KEYS[2])<br>redis.call(&#39;PSETEX&#39;, KEYS[1], ARGV[1], ARGV[2])<br>return token</pre><p>The script runs atomically on the Redis primary. Our experiment returns 1 to A and, after expiry, 2 to B.</p><p><strong>Important:</strong> Atomic issuance on one Redis primary is not the same as failover-proof monotonicity. A Redis counter can roll back if acknowledged writes are lost during a crash or failover. For a real correctness guarantee, token allocation must have suitable durability and ordering guarantees across failures.</p><h3>Enforce the token at the resource</h3><p>For the lab we store the protected value in a Redis hash. The following Lua script applies the token check and update atomically:</p><pre>local last = tonumber(redis.call(&#39;HGET&#39;, KEYS[1], &#39;last_token&#39;) or &#39;0&#39;)<br>local incoming = tonumber(ARGV[1])<br>if incoming &lt; last then<br>  return 0  -- stale write rejected<br>end<br>redis.call(&#39;HSET&#39;, KEYS[1],<br>  &#39;last_token&#39;, ARGV[1],<br>  &#39;value&#39;, ARGV[2])<br>return 1</pre><p>When B writes with token 2, the resource records last_token=2. When A eventually writes with token 1, the resource rejects it. The newer value survives.</p><p>The demo allows repeated writes with the <strong>same</strong> token because it rejects &lt;, not &lt;=. Applications needing single-use tokens or distinct operation-level deduplication should add that requirement separately. Fencing controls generations of ownership; it is not a replacement for idempotency.</p><h3>4. Run the experiment</h3><p>The accompanying [Go + Redis reproduction project](./README.md). It contains a deliberately unsafe path and a fenced path, there are no external Go library dependencies.</p><pre>docker compose up -d<br>go test ./...<br>go run .<br>docker compose down</pre><p>The code runs A’s lease, waits past expiry, lets B acquire the next lease and write, and then deliberately resumes A. <strong>The pause is scripted for determinism</strong>, not a real GC-induced suspension.</p><h3>Expected terminal output</h3><p><em>Illustrative expected output; this environment has not run the live Redis experiment.</em></p><pre>=== WITHOUT FENCING ===<br>A acquired 300ms Redis lease; simulated work pauses<br>Lease expired; B acquired the same lock<br>B wrote: newer-write-from-B<br>A resumed and overwrote B, despite expired lease<br>Final value: stale-write-from-A  &lt;-- WRONG<br>A&#39;s attempted unlock removed B&#39;s lock: false (must be false)</pre><pre>=== WITH RESOURCE-ENFORCED FENCING ===<br>A acquired lease, token=1; simulated work pauses<br>Lease expired; B acquired lease, token=2<br>Resource accepted B&#39;s newer write<br>Resource accepted A&#39;s stale write: false (must be false)<br>Final value: newer-write-from-B  &lt;-- CORRECT<br>Last accepted token: 2</pre><p>Notice that the unsafe run already uses a safe <em>unlock</em> script. The bug is specifically <strong>stale data modification</strong>, not accidental lock deletion.</p><h3>5. What fencing does — and does not — guarantee</h3><p>Fencing protects ordering: <strong>after the resource has accepted token 2, it rejects writes from token 1</strong>. It does <em>not</em> magically terminate A when its TTL expires.</p><p>There’s a subtle remaining case. Suppose A’s lease expired and B acquired token 2, but B hasn’t yet sent any write. A sends token 1 first. If the resource last saw token 0, it can still accept A’s write. The monotonic-token rule prevents <em>older writes from overwriting already accepted newer generations</em>; by itself it doesn’t enforce “no expired lease holder may ever write again.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tQxkdI45sxeNNbvRDKHFpw.png" /><figcaption><em>Figure 4 — Important boundary: fencing protects order relative to accepted writes, not lease validity in real time.</em></figcaption></figure><p>Other boundaries matter too:</p><ul><li><strong>Counter durability:</strong> INCR on a failover-prone Redis deployment isn&#39;t automatically a durable, linearizable fencing-token source.</li><li><strong>Resource enforcement:</strong> The real destination — not merely a separate lock cache — must check and update its token atomically with the protected operation.</li><li><strong>Non-transactional side effects:</strong> An external payment API or object store that cannot validate tokens needs a different ownership/serialization design. A preflight Redis check followed by an unprotected side effect isn’t equivalent.</li><li><strong>Same-generation retries:</strong> Fencing doesn’t automatically provide idempotency or deduplicate repeated operations with identical tokens.</li></ul><p>For database records that already have a transactional owner, a row lock, unique constraint, optimistic version check, or serializable transaction may be simpler and stronger than introducing a separate lock service. Choose the concurrency boundary based on where the authoritative state lives.</p><h3>6. When should you care?</h3><p>If a Redis lock just avoids redundant cache warmups, occasionally doing the same work twice may be acceptable. The engineering goal is <strong>efficiency</strong>.</p><p>If a lock protects money movements, inventory state, task ownership, or other operations where a stale write would corrupt the outcome, the goal is <strong>correctness</strong>. In those situations, ask a harder question:</p><blockquote><em>When the old lock owner wakes up, what stops its write at the actual resource?</em></blockquote><p>That’s the design question fencing tokens force us to answer.</p><h3>Takeaway</h3><p>A lock lease answers: <em>“Who is allowed to start work right now?” <br></em>A fencing check at the destination answers: <em>“Is this write older than a generation of ownership I’ve already accepted?”<br></em>They solve different problems. For correctness-critical workflows, don’t assume a Redis TTL alone makes an old worker harmless.</p><p>Here’s the working demo: <a href="https://github.com/AkashShukl/examples/tree/main/redis-fencing-tokens">https://github.com/AkashShukl/examples/tree/main/redis-fencing-tokens</a></p><h3>Further reading</h3><ul><li>Martin Kleppmann, <a href="https://martin.kleppmann.com/2016/02/08/how-to-do-distributed-locking.html">How to do distributed locking</a> — the foundational fencing-token explanation.</li><li>Redis, <a href="https://redis.io/docs/latest/develop/clients/patterns/distributed-locks/">Distributed Locks with Redis</a> — ownership tokens, TTLs and unlock safety.</li><li>Redis, <a href="https://redis.io/docs/latest/management/persistence/">Persistence documentation</a> — why counter durability and failover need separate scrutiny.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2cdad7e85754" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Features to Impact: My Journey Building High-Impact Backend Services at Scale]]></title>
            <link>https://medium.com/@akashshukla_1715/from-features-to-impact-my-journey-building-high-impact-backend-services-at-scale-cee2e68430f0?source=rss-18fac7af4925------2</link>
            <guid isPermaLink="false">https://medium.com/p/cee2e68430f0</guid>
            <category><![CDATA[growth]]></category>
            <category><![CDATA[journey]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[learning]]></category>
            <category><![CDATA[self-reflection]]></category>
            <dc:creator><![CDATA[Akash Shukla]]></dc:creator>
            <pubDate>Sun, 27 Jul 2025 12:56:47 GMT</pubDate>
            <atom:updated>2026-01-22T13:57:56.669Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><em>In fast-paced teams, it’s easy to get buried under feature tickets. But over the past 6 months as an engineer in the Order Management team, I’ve had the chance to design and deliver systems that not only shipped — but saved costs, scaled across business units, and improved the checkout experience for millions of users.</em></blockquote><h3>Introduction</h3><p>I currently work as a <strong>Backend Engineer</strong> in the <strong>Order Management System pod</strong> at a fast-growing product company. Our job is to ensure that once a customer hits “Place Order,” everything downstream works smoothly — integrations, payments, shipments, and analytics.</p><h3>1. Building Bridges: The Partner/Vendor Integration Service</h3><p>Soon after I joined the team, I was tasked with a high-impact challenge: <strong>to design and build the service from scratch, all while navigating a new role in a new organisation. </strong><br>The goal was clear but complex. Once a customer completed a purchase, our system needed to seamlessly connect with various external partners — like phone exchange vendors and installation service providers — to kick off the next steps. This moment marked a crucial handoff in the customer journey, and getting it right meant ensuring the entire downstream experience worked without a hitch.</p><p>This wasn’t just about writing API calls. I worked closely with the product and partner teams both within and outside the org to define contracts, handle edge cases, and set up retry mechanisms for flaky endpoints. With just two engineers on the task, we designed it to be <strong>robust, extensible, and observability-first</strong> from day one.</p><blockquote><strong>What I learned:</strong><em> </em>Even in high-velocity environments, taking the time upfront to define clear contracts and build robust monitoring pays off — it prevents weeks of reactive firefighting later.<br>Every tech company operates within its unique set of constraints, which deeply influence its design choices. At first glance, some decisions may seem counterintuitive or even flawed, but with deeper context, they often reveal themselves as well-reasoned and practical.</blockquote><h3>2. Cracking COD in Multi-Shipment Orders</h3><p>Next, I was assigned to a tricky problem that touched both product complexity and revenue: <strong>enabling Cash on Delivery (COD) for multi-shipment orders</strong>.</p><p>The system had to intelligently split payments, partially deducting from the customer’s wallet while accurately tracking the remaining amount for Cash on Delivery. But the real complexity kicked in with refunds. We had to support mixed-payment refunds in a legacy codebase filled with multiple entry points, manual, automatic, and more, each with its own set of edge cases. Making sure refunds were handled gracefully without breaking existing flows required deep dives and careful orchestration across the system.</p><p>With <strong>~30% of orders using COD</strong>, this feature opened up significant revenue potential that was previously left on the table due to system limitations.</p><blockquote><strong>What I learned:</strong><em> </em>When working with legacy systems, never rely solely on function names or comments — always trace the logic to its core. Digging into “edge cases” often reveals critical, high-impact scenarios that were hiding in plain sight. Solving “edge cases” often uncovers high-impact use cases hiding in plain sight.</blockquote><h3>3. Shipment Breakdown Based on Weight Thresholds</h3><p>We started noticing operational issues in last-mile deliveries — especially for bulky orders. Worked on a solution to <strong>automatically split orders into multiple shipments</strong> once they crossed a certain weight threshold.</p><p>This wasn’t just a backend logic change — we had to think through operations, API updates and rollout strategies. The root problem was that riders using smaller vehicles often couldn’t carry large, bulky shipments, resulting in frequent cancellations. By breaking down such orders into smaller, manageable shipments, we enabled smoother last-mile deliveries. This significantly reduced the number of failed deliveries and had a direct revenue impact, especially on high-value orders.</p><p>It was a major change that touched multiple system components, and I got to lead this effort single-handedly from the OMS pod. The most challenging part was delivering such a large feature to production without any downtime or critical bugs. It pushed me to think deeply about safe deployment strategies, backwards compatibility, and how to incrementally ship complex features without disrupting live traffic.</p><blockquote><strong>What I learned:<em> </em></strong>Operational constraints often spark some of the most meaningful architectural changes.</blockquote><h3>4. Offloading Complexity: The Order Enricher Service</h3><p>With a growing list of downstream consumers — analytics, metrics, notifications, etc. — our core order system was becoming a bottleneck. As we progress towards a distributed system, moving from the monolith. I picked this change to design and implement a new <strong>Service, </strong>lightweight but powerful, written in Golang, utilising Kafka, that listened to lifecycle events and enriched them before dispatching to respective consumers. It also includes failure management, retry and replay mechanisms, as each event is important for the downstream services, so we had to think and play around Kafka, DLQ and custom lambda functions to handle failures.</p><p>This decoupling made our core system leaner and gave dependent teams the flexibility to evolve independently.</p><blockquote><strong>What I learned:</strong><em> </em>Sometimes, the best way to scale is to <strong>remove responsibilities</strong>, not add more.</blockquote><h3>5. Automating Customer Support with Agentic AI</h3><p>The most recent and ongoing challenge I took on was building the foundational layer of an agentic AI platform aimed at automating customer support. This wasn’t just about deploying an LLM and calling it a day. We needed a production-grade system that could handle real-world edge cases while being cost-effective.</p><p>I initiated the base architecture and integrated LangGraph to orchestrate multi-step workflows. The impact? A projected cost saving of over $ <strong>300K USD/ month</strong>, with this figure expected to grow as we scale and reduce reliance on human agents.</p><p>What made this initiative exciting was not just the tech (LLMs, orchestrators, context management), but how quickly we had to move — from zero to production-ready MVP in a matter of 2 weeks.</p><blockquote><strong>What I learned:</strong> Designing with LLMs in production isn’t just a prompt-engineering problem — it’s a systems problem. Real impact comes from grounding intelligence in structured workflows, handling failures gracefully, and optimizing for cost at scale.</blockquote><h3>Beyond Code: Growing Through Ownership</h3><p>For every project, I ensured:</p><ul><li>Monitoring and alerting were in place from day one.</li><li>My code was production-safe, reviewed, and well-tested.</li><li>I didn’t just ship features — I shipped stability.</li></ul><p>But more than anything, I focused on <strong>understanding the “why”</strong> behind each project. That’s what allowed me to collaborate better, push back when needed, and propose solutions, not just implement tickets.</p><h3><strong>Why I’m Sharing This?</strong></h3><p>Over the last 6 months, I’ve had the opportunity to work on some impactful problems in a fast-paced startup environment. This post isn’t just a personal reflection — it’s a glimpse into what the work <em>actually</em> looks like when you’re navigating multiple priorities, tight deadlines, and high ownership. Whether you’re curious about what SDE-2s typically do in such settings, or just exploring how backend engineers drive business value beyond writing code, I hope this gives you a real, grounded perspective.</p><p><em>As I continue growing in this role, I’ll keep adding key milestones to this post.</em></p><h3>Let’s Connect!</h3><p>If you found this helpful or have questions about building backend systems in a high-growth startup, feel free to connect or drop a message. I’m always open to exchanging ideas, sharing experiences, or just having a good tech conversation.</p><p><a href="https://www.linkedin.com/in/akashshukl/"><strong><em>🔗 Connect with me on LinkedIn</em></strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cee2e68430f0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Observable Design Pattern — Golang]]></title>
            <link>https://medium.com/@akashshukla_1715/observable-design-pattern-golang-577d1e53c5f5?source=rss-18fac7af4925------2</link>
            <guid isPermaLink="false">https://medium.com/p/577d1e53c5f5</guid>
            <category><![CDATA[golang-tutorial]]></category>
            <category><![CDATA[observables]]></category>
            <category><![CDATA[go-design-patterns]]></category>
            <category><![CDATA[observer-pattern]]></category>
            <category><![CDATA[design-patterns]]></category>
            <dc:creator><![CDATA[Akash Shukla]]></dc:creator>
            <pubDate>Tue, 14 Nov 2023 06:46:55 GMT</pubDate>
            <atom:updated>2023-11-14T07:06:48.705Z</atom:updated>
            <content:encoded><![CDATA[<h3>Observable Design Pattern — Golang</h3><p>The Observer design pattern in Go, also known as the Observable pattern, facilitates a one-to-many relationship between objects. When the state of an Observable changes, it notifies multiple dependent Observer objects, enabling them to respond to the change.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4FkHaYmCLjEJHU_apYIFrA.png" /></figure><h3>Understanding the Pattern</h3><p>In our example, let’s create a simple implementation of the Observer pattern using Go, we are taking an example for a notification system that can be subscribed by different types of applications web, and phone, and can have different implementations to push these to end users:</p><h4>Observable Interface</h4><p>The Observable interface defines methods for managing observers, such as Subscribe(observer Observer) to add observers and NotifyObservers(data interface{}) to notify them about changes.</p><pre>package observable<br><br>import &quot;github.com/go-lld/observables/observer&quot;<br><br>// Observable represents an entity that allows <br>// observers to subscribe and receive notifications.<br>type Observable interface {<br> <br>// Subscribe registers an observer to <br>// receive notifications from this observable.<br> Subscribe(observer observer.Observer)<br> <br>// NotifyObservers notifies all subscribed <br>// observers about changes in the observable.<br> NotifyObservers(data interface{})<br>}</pre><p><strong>Concrete Notification Observable </strong>implements Observable</p><pre>package observable<br><br>import &quot;github.com/go-lld/observables/observer&quot;<br><br>// NotificationObservable represents an observable <br>// entity that manages a list of subscribed observers.<br>type NotificationObservable struct {<br> subscribedObservers []observer.Observer<br>}<br><br>// Subscribe adds a new observer to the <br>// list of subscribers for NotificationObservable.<br>func (n *NotificationObservable) Subscribe(obs observer.Observer) {<br> n.subscribedObservers = append(n.subscribedObservers, obs)<br>}<br><br>// NotifyObservers sends notifications to all<br>// subscribed observers of NotificationObservable about changes.<br>func (n *NotificationObservable) NotifyObservers(data interface{}) {<br> for _, obs := range n.subscribedObservers {<br>  obs.Notify(data)<br> }<br>}<br><br>// NewNotificationObservable creates and <br>// returns a new instance of NotificationObservable.<br>func NewNotificationObservable() Observable {<br> return &amp;NotificationObservable{}<br>}<br>Observer Interface</pre><h4>Observer Interface</h4><p>The Observer interface represents the contract that all observers must fulfill. It typically contains a method, such as Update(data interface{}) Notify(), which allows Observers to receive notifications.</p><pre>package observer<br><br>// Observer defines the interface that all <br>// observing entities must implement.<br>type Observer interface {<br> // Notify performs the action necessary when an observation occurs.<br> Notify(data interface{})<br>}</pre><h4>Concrete Web Notification Observer</h4><pre>package observer<br><br>import &quot;fmt&quot;<br><br><br>// WebObserver represents an observer <br>// specifically for handling web notifications.<br>type WebObserver struct {<br>}<br><br>// Notify implements the action for WebObserver <br>// when a web observation occurs.<br>func (w *WebObserver) Notify(data interface{}) {<br> fmt.Println(data)<br>}<br><br>// NewWebObserver creates and returns a new instance of WebObserver.<br>func NewWebObserver() Observer {<br> return &amp;WebObserver{}<br>}</pre><p><strong>Concrete Phone Notification observer</strong></p><pre>package observer<br><br>import &quot;fmt&quot;<br><br>// PhoneObserver represents an observer <br>// specifically for handling phone notifications.<br>type PhoneObserver struct {<br>}<br><br>// Notify implements the action for PhoneObserver <br>// when a phone observation occurs.<br>func (p *PhoneObserver) Notify(data interface{}) {<br> fmt.Println(data)<br>}<br><br>// NewPhoneObserver creates and returns a new instance of PhoneObserver.<br>func NewPhoneObserver() Observer {<br> return &amp;PhoneObserver{}<br>}Usage Example</pre><p>It can be extended to cover multiple scenarios. Different use cases may require varying mechanisms for providing notification-related data to observers.</p><h3>Mechanisms of Communication</h3><ol><li>Pull Model: Observers request necessary data from the Observable using the Update() method, allowing them to query the Observable for required information upon notification.</li><li>Push Model: The Observable directly provides information or messages to its Observers during notification by including the necessary data in the method call, e.g., Update(message interface{}).</li><li>Event Object: Observers might receive a pre-packaged event object containing relevant information about the change, encapsulating the message or data related to the event.</li></ol><h3>Conclusion</h3><p>The Observer pattern in Go offers a flexible means of establishing communication between Observable and Observer entities, facilitating a dynamic and efficient update mechanism. By allowing multiple Observers to react to changes in an Observable’s state, this pattern supports decoupling and promotes scalability and maintainability in software design.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=577d1e53c5f5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Strategy Desing Pattern — Python]]></title>
            <link>https://medium.com/@akashshukla_1715/strategy-desing-pattern-python-e6c87165f836?source=rss-18fac7af4925------2</link>
            <guid isPermaLink="false">https://medium.com/p/e6c87165f836</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[lld]]></category>
            <category><![CDATA[faang-interview-prep]]></category>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[design-patterns]]></category>
            <dc:creator><![CDATA[Akash Shukla]]></dc:creator>
            <pubDate>Sat, 12 Aug 2023 06:34:10 GMT</pubDate>
            <atom:updated>2023-08-12T06:35:11.053Z</atom:updated>
            <content:encoded><![CDATA[<h3>Strategy Desing Pattern — Python</h3><p>This is intended for individuals who are new to writing Object Oriented code. Useful for interview preparation and day-to-day dev work.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/485/1*_dgL7AJ1cwz1zZvlrHxYvw.gif" /></figure><p>Although the principles can be applied to any programming language, I will use Python for demonstration purposes. The aim is to assist anyone in producing well-organized and efficient object-oriented Python code.</p><p>The goal is to help anyone write clean object-oriented code.</p><p><strong>The Strategy design pattern</strong> defines a family of algorithms, encapsulates them in separate classes, and makes them interchangeable. This pattern allows you to choose an algorithm at runtime, providing flexibility and enabling easy extension of functionality without modifying existing code.</p><h3>Benefits of Strategy Pattern</h3><ol><li><strong>Easy Maintenance:</strong> Strategies can be developed and tested independently, making it easier to maintain and modify the codebase without disrupting other parts of the application.</li><li><strong>Code Reusability:</strong> The Strategy pattern promotes code reusability by encapsulating algorithms into separate classes. New algorithms can be added without affecting the existing codebase.</li><li><strong>Runtime Flexibility:</strong> By allowing you to switch between different algorithms at runtime, the Strategy pattern enables dynamic behavior changes without requiring extensive code modifications.</li><li><strong>Testing: </strong>Since strategies are self-contained classes, you can write unit tests for each strategy independently. This level of granularity in testing helps identify and rectify issues specific to a particular strategy, ensuring the correctness of its implementation.</li></ol><h3>Let’s write some code . . .</h3><p>Let’s Consider a scenario for a payments application. the requirement is to support multiple ways of payment</p><ul><li>Card Payment</li><li>Net Banking</li><li>Paypal</li></ul><pre>class PaymentStrategy:<br>    def pay(self, amount):<br>        pass<br><br>class CreditCardPayment(PaymentStrategy):<br>    def pay(self, amount):<br>        print(f&quot;Paid ${amount} using Credit Card&quot;)<br><br>class PayPalPayment(PaymentStrategy):<br>    def pay(self, amount):<br>        print(f&quot;Paid ${amount} using PayPal&quot;)<br><br>class NetBanking(PaymentStrategy):<br>    def pay(self, amount):<br>        print(f&quot;Paid ${amount} using Net Banking&quot;)<br><br>class Payment:<br>    def __init__(self, default_payment_mode, detail):<br>        self.payment_mode_strategy = default_payment_mode<br>        self.payment_detail = detail<br>        <br>    def set_payment_option(self, mode):<br>        if mode == &quot;credit_card&quot;:<br>            self.payment_mode_strategy = CreditCardPayment()<br>        elif mode == &quot;paypal&quot;:<br>            self.payment_mode_strategy = PayPalPayment()<br>        elif mode == &quot;net_banking&quot;:<br>            self.payment_mode_strategy = NetBanking()<br>    <br>    def make_payment(self):<br>        # This will use self.payment_mode_strategy and  <br>        # self.payment_detail to initiate payment<br>        pass<br><br>if __name__ == &#39;__main__&#39;:<br>    CREDIT_CARD = &quot;credit_card&quot;<br>    detail = {<br>        &quot;sender&quot;: &quot;some sender&quot;,<br>        &quot;receiver&quot;: &quot;some receiver&quot;,<br>        &quot;amount&quot;: &quot;100&quot;,<br>        &quot;description&quot;: &quot;some description&quot;<br>    }<br>    payment = Payment(CREDIT_CARD, detail)<br>    payment.make_payment()</pre><p>And, One fine day a new payment interface launches UPI . Now your organization needs to integrate this new method into its existing payment system as UPI has a very large user base and is simpler and more convenient.</p><blockquote>Given the extensible nature of the Strategy pattern, integration involves minimal disruption:</blockquote><p>All we need to do is create a new class <strong>UPIPayment</strong> and plug it into the <strong>set_payment_option </strong>method.</p><pre>class UPIPayment(PaymentStrategy):<br>    def pay(self, amount):<br>        print(f&quot;Paid ${amount} using Net Banking&quot;)</pre><pre>class Payment:<br>    def __init__(self, default_payment_mode, detail):<br>        self.payment_mode_strategy = default_payment_mode<br>        self.payment_detail = detail<br>        <br>    def set_payment_option(self, mode):<br>        if mode == &quot;credit_card&quot;:<br>            self.payment_mode_strategy = CreditCardPayment()<br>        elif mode == &quot;paypal&quot;:<br>            self.payment_mode_strategy = PayPalPayment()<br>        elif mode == &quot;net_banking&quot;:<br>            self.payment_mode_strategy = NetBanking()<br>        elif mode == &quot;upi&quot;:<br>            self.payment_mode_strategy = UPIPayment()<br>    <br>    def make_payment(self):<br>        # This will use self.payment_mode_strategy and <br>        # self.payment_detail to initiate payment<br>        pass</pre><p>we can test the UPI payment method and start working on it without having any design changes.</p><p>It is evident that any day if any new payment mechanism launches we will need minimal code changes and thus avoid errors.</p><p>This adaptable structure underscores the ease of accommodating new payment methods with minimal code alterations. Such an approach is helpful to significantly mitigate errors and enables the integration of future mechanisms.</p><p>In summary, the Strategy pattern provides a robust foundation for crafting modular and adaptable code, rendering it well-suited for scenarios where dynamic behavior and flexibility are required. This guide shows its utility through a concise and comprehensive example.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e6c87165f836" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Preventing Unnecessary Rerendering of Child Components in React Using useCallback and React.memo]]></title>
            <link>https://medium.com/@akashshukla_1715/preventing-unnecessary-rerendering-of-child-components-in-react-using-usecallback-and-react-memo-34f1423fe263?source=rss-18fac7af4925------2</link>
            <guid isPermaLink="false">https://medium.com/p/34f1423fe263</guid>
            <category><![CDATA[react-optimization]]></category>
            <category><![CDATA[usecallback]]></category>
            <category><![CDATA[prevent-rerendering-child]]></category>
            <category><![CDATA[react-render]]></category>
            <category><![CDATA[use-case-of-usecallback]]></category>
            <dc:creator><![CDATA[Akash Shukla]]></dc:creator>
            <pubDate>Sat, 25 Mar 2023 09:13:06 GMT</pubDate>
            <atom:updated>2023-03-25T09:13:06.573Z</atom:updated>
            <content:encoded><![CDATA[<p>React is a popular JavaScript library used for building web applications. One of the main features of React is its ability to efficiently update and render the components of a web application. However, as an application grows in complexity, it can become increasingly difficult to manage the rendering of child components within a parent component.</p><p>To address this issue, React provides two hooks, useCallback and React.memo, which can be used together to prevent the unnecessary re-rendering of child components within a parent component.</p><p>I have created a simple react program to showcase an example with code and highlighting. please take a look <a href="https://codesandbox.io/s/elated-resonance-i86qql?file=/src/App.js">https://codesandbox.io/s/elated-resonance-i86qql?file=/src/App.js</a></p><p>Before going further into it, we should know what makes a component re render. let’s assume them as rules for sometime.</p><ol><li><strong>state changes</strong></li><li><strong>props changes</strong></li><li><strong>Re render of Parent Component.</strong></li></ol><p>Let’s consider an example, we have a parent component <strong>App </strong>and a child component <strong>Card</strong>, we are passing props in child component, and we don’t want our child components to re-render every time something changes in the parent component which is not directly impacting child component.</p><p><strong>Problem Statement : Every time some state changes in the parent component, it makes the child component to re render. But many times Child components do not require re renders as those states are not used by all child components.</strong></p><p>for example, lets look at this code, in App component we are using Card component and passing props: count and increment.</p><p>now every time we click on “Update Parent to Cause Re render” button. It will re-render Card component.<strong> why? </strong>because of state change in App component (rule 1), makes it re render and re-render of parent component makes Card re render (rule 3).</p><figure><img alt="Sample UI for problem statement" src="https://cdn-images-1.medium.com/max/613/1*vLM0pdD77t8FFU4MNfddfg.png" /></figure><pre>export default function App() {<br>  const [random, setRandom] = useState(10);<br>  const [count, setCount] = useState(0);<br>  <br>  const increment = () =&gt; (setCount(count + 1));<br>  <br>  const newRandom = () =&gt; setRandom(Math.floor(Math.random() * 100));<br>          <br>  return (<br>      &lt;div id=&quot;parent&quot;&gt;<br>        &lt;Card count={count} updateCount={increment} /&gt;<br>        {random}<br>        &lt;button onClick={newRandom}&gt;<br>          Update Parent to Cause Rerender<br>        &lt;/button&gt;<br>      &lt;/div&gt;<br>  );<br>}</pre><p>To avoid re rendering of component if props are not changing , we can use “React.memo” and thus our card component now looks like this</p><pre>// Card.jsx<br>function Card({ count, updateCount }) {<br>  return (<br>    &lt;div id=&quot;card&quot; className=&quot;card-default&quot;&gt;<br>      This is Card Component<br>      current Count : {count}<br>      &lt;button onClick={updateCount}&gt;<br>         Update Count to Cause Rerender Child<br>      &lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}<br>export default React.memo(Card)</pre><p>okay, now we have used memo, and wait, what? still it is making card component re render when we click on “Update Parent to Cause Re render” . <strong>why? this is because when our parent component re renders everything gets </strong>recreated, including the function reference to “increment()”. Since, the reference of function is now changed. for child component it is an update, As a result, the props change and the card component gets re-rendered, in accordance with rule 2.</p><p>Now we are set, if somehow, we could tell react, that<strong> “hey react you don’t need to re initialize the function unless we ask you for it”</strong>. to solve this problem specifically React gives us <strong>useCallback</strong> hook.</p><blockquote><em>useCallback(function, [dep1, dep2])</em></blockquote><p>With useCallback we can define a function that has referential equality between renders. it will only recompute the function when its dependency changes and return a memoized callback.</p><p>After wrapping our increment function with useCallback, we’ve noticed that the Card component no longer re-renders upon state updates in the parent component for states that aren’t being used by the Card component. This is because the useCallback hook helps to optimize the performance of our code by memoizing the function reference and only updating it when necessary. So, our final code now looks like this.</p><pre>//App.jsx<br>export default function App() {<br>  const [random, setRandom] = useState(10);<br>  const [count, setCount] = useState(0);<br>  <br>  const increment = () =&gt; (setCount(count + 1));<br>  // <br>  const memoizedUpdateCount = useCallback(increment, [count]);<br>  return (<br>      &lt;div id=&quot;parent&quot;&gt;<br>        &lt;Card count={count} updateCount={memoizedUpdateCount} /&gt;<br>        {random}<br>        &lt;button<br>          onClick={() =&gt; {<br>            setRandom(Math.floor(Math.random() * 100));<br>          }}<br>        &gt;<br>          Update Parent to Cause Rerender<br>        &lt;/button&gt;<br>      &lt;/div&gt;<br>  );<br>}</pre><pre>// Card.jsx<br>function Card({ count, updateCount }) {<br>  return (<br>    &lt;div id=&quot;card&quot; className=&quot;card-default&quot;&gt;<br>      This is Card Component<br>      current Count : {count}<br>      &lt;button onClick={updateCount}&gt;<br>         Update Count to Cause Rerender Child<br>      &lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}<br>export default React.memo(Card)</pre><p>I have created a simple react program to showcase above example with animation. please take a look <a href="https://codesandbox.io/s/elated-resonance-i86qql?file=/src/App.js">https://codesandbox.io/s/elated-resonance-i86qql?file=/src/App.js</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=34f1423fe263" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring Non-Blocking Concurrent Execution in Go and JavaScript]]></title>
            <link>https://medium.com/@akashshukla_1715/exploring-non-blocking-concurrent-execution-in-go-and-javascript-873203befade?source=rss-18fac7af4925------2</link>
            <guid isPermaLink="false">https://medium.com/p/873203befade</guid>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[javascript-vs-go]]></category>
            <category><![CDATA[multithreading-in-go]]></category>
            <dc:creator><![CDATA[Akash Shukla]]></dc:creator>
            <pubDate>Sat, 18 Mar 2023 08:06:47 GMT</pubDate>
            <atom:updated>2023-03-18T08:06:47.808Z</atom:updated>
            <content:encoded><![CDATA[<p>If you’re like me, who is coming from a frontend engineering background and started learning Golang. You might have come across Golang’s one of the most promising features i.e. Go Routine and are confused about how it is different from Async Javascript. Let’s delve deeper and see what&#39;s there to uncover.</p><p><strong>Firstly, How are go routines similar to async JS?</strong></p><p>Go routines and asynchronous JavaScript are similar as they allow for non-blocking concurrent task execution.</p><p>however,</p><ul><li>Go routines use a statically allocated stack, which makes them more efficient and predictable in terms of memory usage compared to asynchronous JavaScript functions, which use a dynamically allocated heap.</li><li>Go routines are managed by the Go runtime, which uses a fixed number of OS threads to schedule them, while asynchronous JavaScript functions are managed by the JavaScript engine, which uses an event loop to schedule them.</li></ul><p><strong>But, is it even a good idea to compare a multi-threaded language(Go) to a single-thread language?</strong></p><p>Instead of comparing Go routines and asynchronous JavaScript directly, it may be more useful to compare the concurrency models of the two languages. Go has a model based on communicating sequential processes (CSP), which emphasizes message passing and synchronization between concurrent processes, while JavaScript uses an event loop model, which relies on callbacks and promises to manage asynchronous operations.</p><p>In general, the CSP model used by Go can be more intuitive and easier to reason about for certain types of concurrent operations, while the event loop model used by JavaScript can be more flexible and easier to implement for others. The choice of which model to use depends on the specific requirements of the application and the trade-offs between simplicity, performance, and other factors.</p><p><strong>Let’s even go further and find out How actually is Go lang achieving concurrency.</strong></p><p>In Go, the runtime uses a technique called “multiplexing” to schedule Go routines on a fixed number of OS threads. Multiplexing is a way of managing concurrency by allowing multiple tasks to be executed on a single thread in a way that makes them appear to be running simultaneously. When a Go program starts, the Go runtime creates a fixed number of OS threads (usually equal to the number of available CPU cores) and schedules Go routines onto them. The Go runtime uses a scheduling algorithm called “work stealing” to ensure that the workload is balanced across all threads.</p><blockquote>The work-stealing algorithm is a scheduling algorithm used in concurrent programming to balance the workload across multiple threads of execution. It is used in programming languages and libraries that support task-based parallelism, where the computation is broken down into tasks that can be executed independently.</blockquote><p>Overall, it’s important to recognize that Go routines and asynchronous JavaScript both provide ways to achieve concurrency and non-blocking task execution, but they use different concurrency models and techniques to achieve these goals. Go routines use a statically allocated stack and a model based on communicating sequential processes, while asynchronous JavaScript functions use a dynamically allocated heap and an event loop model.</p><p>The choice of which concurrency model to use ultimately depends on the specific requirements of the application and the trade-offs between simplicity, performance, and other factors. Additionally, understanding the underlying techniques and algorithms used by each language to manage concurrencies, such as Go’s use of multiplexing and work stealing, can be useful in optimizing the performance and efficiency of concurrent programs.</p><h3>References :</h3><ul><li><a href="https://medium.com/swlh/work-stealing-distilled-d2ed86d3065d">https://medium.com/swlh/work-stealing-distilled-d2ed86d3065d</a></li><li><a href="https://gobyexample.com/goroutines">https://gobyexample.com/goroutines</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=873203befade" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>