<?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 Saurabh Rajesh Pande on Medium]]></title>
        <description><![CDATA[Stories by Saurabh Rajesh Pande on Medium]]></description>
        <link>https://medium.com/@spande6894?source=rss-aea3d88bf956------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*tl4y3-dxIR3gDs5PzgPWSQ.jpeg</url>
            <title>Stories by Saurabh Rajesh Pande on Medium</title>
            <link>https://medium.com/@spande6894?source=rss-aea3d88bf956------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 21:48:45 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@spande6894/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[How Limited-Time Coupon Codes Actually Work Under the Hood]]></title>
            <link>https://medium.com/@spande6894/how-limited-time-coupon-codes-actually-work-under-the-hood-93c9f3143c1c?source=rss-aea3d88bf956------2</link>
            <guid isPermaLink="false">https://medium.com/p/93c9f3143c1c</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[low-level-design]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[high-level-design]]></category>
            <category><![CDATA[coupon-codes]]></category>
            <dc:creator><![CDATA[Saurabh Rajesh Pande]]></dc:creator>
            <pubDate>Sat, 19 Sep 2026 19:27:37 GMT</pubDate>
            <atom:updated>2026-09-19T19:27:37.524Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Cover image" src="https://cdn-images-1.medium.com/max/1024/1*a_s0SQ5j57NKQlyAaB4Nfg.png" /><figcaption>cover image</figcaption></figure><p>You got a coupon. You used it. But did you ever wonder — how does the backend know it expired exactly at 1:00 AM?</p><h4>The Core Idea -</h4><p>A limited-time coupon like LAUNCH30 is not magic. It&#39;s just a database row with a start time, an end time, and a few rules.</p><p>The backend never “deletes” the code the moment it expires. Instead, every time someone tries to use a coupon, the server looks at the clock and asks: <em>“Is right now within the valid window?”</em> If yes — discount applied. If no — rejected.</p><p>Simple premise. The interesting part is everything underneath it.</p><h4>How It Works (Step by Step) —</h4><p><strong>Step 1: Creating the Coupon</strong></p><p>When the marketing team hits “Launch Offer,” the backend creates a record in the database that looks like this:-</p><pre>code        → LAUNCH30<br>discount    → 30%<br>start_time  → 2026-09-20 00:00:00<br>end_time    → 2026-09-20 01:00:00<br>is_active   → true<br>max_uses    → 1000  (optional cap)<br>used_count  → 0</pre><p>That <strong>end_time </strong>is the single source of truth for everything that follows.</p><p><strong>Step 2: User Applies the Code (Live Validation)</strong></p><p>When you type LAUNCH30 and hit &quot;Apply,&quot; the server runs this check in real time:-</p><pre>1. Does this code exist in the database?<br>2. Is is_active = true?<br>3. Is current_time &gt;= start_time?<br>4. Is current_time &lt;= end_time?<br>5. Is used_count &lt; max_uses?</pre><p>All five must pass. If the clock says <strong>01:00:01</strong>, condition 4 fails — and you get back: <em>&quot;Sorry, this coupon has expired.&quot;</em></p><p>No delay. No batch job needed. It’s instant because the check happens at the moment you click.</p><p><strong>Step 3: Background Cleanup</strong></p><p>The live check handles rejection fine. But the system also needs to clean up expired coupons so:</p><ul><li>The UI (countdown timer, promo banners) stays accurate</li><li>The database doesn’t grow stale data forever</li></ul><p>Two tools handle this:</p><p><strong>Cron Job</strong> — A script runs every minute and flips <strong>is_active = false</strong> for any coupon where <strong>end_time</strong> has passed. This is the standard approach for most apps.</p><pre>UPDATE coupons<br>SET is_active = false<br>WHERE end_time &lt; NOW() AND is_active = true;</pre><p><strong>Redis TTL</strong> — For high-traffic apps, active coupons are cached in Redis (an in-memory store) with a TTL (Time-To-Live). You tell Redis: <em>“Store this for 3600 seconds.”</em> When the timer hits zero, Redis deletes it automatically — no cron needed. This is faster and scales better.</p><p><strong>Step 4: Double Validation at Payment</strong></p><p>Here’s the tricky part. You apply the coupon at <strong>00:59:55</strong>. Valid. Then you spend 2 minutes filling in your card details. By the time you hit &quot;Pay Now,&quot; it&#39;s <strong>01:01:30</strong>. Expired.</p><p>To handle this, good backends validate the coupon <strong>twice</strong>:-</p><ul><li><strong>Once</strong> when you apply it to the cart</li><li><strong>Again</strong> at the exact moment the payment is processed</li></ul><p>If it fails the second check, the payment is rejected and you’re shown an error. A bit annoying for the user but necessary to prevent abuse.</p><h4>High-Level Design -</h4><figure><img alt="HLD" src="https://cdn-images-1.medium.com/max/1024/1*slqMZ5cgEBTEhbBlcDRbNg.png" /><figcaption>High Level Design</figcaption></figure><ul><li>The <strong>API Gateway</strong> is the front door. Every request from the user comes here first. It doesn’t do any business logic it just routes the request to the right service.</li><li>The <strong>Coupon Validation Service</strong> is the brain of the whole operation. It decides whether a coupon is valid or not. It doesn’t do this alone though it first checks Redis (the fast cache) and only goes to the database if the cache doesn’t have the answer.</li><li><strong>Redis</strong> sits in front of the database as a speed layer. Since thousands of users might apply coupons at the same time, hitting the database every single time would be slow and expensive. Redis holds the hot data in memory and responds in microseconds.</li><li>The <strong>Coupons DB</strong> is the actual source of truth. Redis might be fast, but the database is what holds the real, permanent record.</li><li>The <strong>Cart Service</strong> only gets involved after the coupon is confirmed valid. It applies the discount to your order total.</li><li>The <strong>Payment Service</strong> is the last stop and it calls the Coupon Validation Service one more time before charging you. This is the double validation we talked about earlier.</li><li>The <strong>Cron Job</strong> runs quietly in the background every minute. It has nothing to do with individual user requests it just keeps the database clean by marking expired coupons as inactive.</li></ul><h4>Low Level Design</h4><figure><img alt="LLD" src="https://cdn-images-1.medium.com/max/1024/1*Qx797Y6gj2NJYoyvXo83-Q.png" /><figcaption>Low Level Design</figcaption></figure><ul><li><strong>The first block (apply coupon)</strong> starts when the user submits the code. The API server passes it to CouponService, which checks Redis first. If Redis has it (cache hit), great — no need to go to the database. If not (cache miss), it fetches from the DB and then stores the result in Redis so the next request is faster.</li><li><strong>The </strong><strong>alt block</strong> is how Mermaid shows an if/else. Either the cache has it, or it doesn&#39;t. Both paths eventually lead to the same validation check.</li><li><strong>The validation check</strong> (<strong>CS-&gt;&gt;CS</strong>) is the coupon service checking its own logic — comparing current time against <strong>start_time</strong> and <strong>end_time</strong>, checking <strong>is_active</strong>, and checking <strong>used_count</strong>. This all happens in memory, no extra DB call needed.</li><li><strong>The second block (place order)</strong> shows what happens when the user actually pays. The Payment Service triggers a fresh call to CouponService — this is the second validation. Note that used_count only gets incremented here, at the point of confirmed payment, not when the coupon is just applied to the cart.</li><li>The <strong>--&gt;&gt;</strong> (dashed arrow) means a response going back. The <strong>-&gt;&gt;</strong> (solid arrow) means a request going out. That&#39;s just Mermaid&#39;s way of showing the direction and type of communication.</li></ul><h4>Challenges Engineers Actually Face -</h4><p><strong>Clock Skew</strong><br> If your app runs across multiple servers, their clocks might differ by a few milliseconds. A coupon that’s expired on Server A might still look valid on Server B. Fix: sync all servers using NTP (Network Time Protocol) and always use UTC timestamps.</p><p><strong>Race Conditions on </strong><strong>max_uses</strong><br> Imagine 500 users applying the coupon at the exact same millisecond. Without proper locking, <strong>used_count </strong>might not update fast enough and the coupon gets used 600 times instead of 500. Fix: use atomic database operations or Redis <strong>INCR</strong> + check pattern to handle this safely.</p><p><strong>Cache and DB Getting Out of Sync</strong><br> If you update the coupon in the DB (say, you deactivate it early) but Redis still has the old version cached, users might still apply it. Fix: always invalidate (delete) the Redis key when the coupon is modified in the DB.</p><p><strong>User Experience at the Edge</strong><br> A user who applies a coupon at <strong>00:59:50</strong> and gets rejected at payment because it expired 2 seconds ago — that&#39;s a frustrating experience. Some companies add a small grace window (30–60 seconds) after <strong>end_time</strong> to soften this edge case.</p><h4>Security: What Stops Someone From Cheating? -</h4><p>This is something most articles skip but engineers actually have to think about.</p><p><strong>Replay attacks</strong> — What if someone captures a valid coupon request and replays it later? Fix: tie the coupon to a user session or user ID. <strong>LAUNCH30 </strong>should only be usable once per account, not once per device.</p><p><strong>Brute forcing codes</strong> — Someone could write a script to try thousands of random codes hoping one hits. Fix: rate limit the <strong>/apply-coupon</strong> endpoint. After 5 failed attempts, block that IP or account for a few minutes.</p><p><strong>Tampering with the discount on the client side</strong> — Never trust the frontend to calculate the discount amount. The backend should always compute <strong>final_price = original_price * (1 - discount_rate)</strong> itself. The frontend only shows the result.</p><p><strong>Code sharing</strong> <strong>LAUNCH30 </strong>is a public code so sharing is expected. But for personal offer codes (like referral codes), the backend should lock the code to a specific user ID so nobody else can use it.</p><h4>How Real Companies Scale This -</h4><p>For a small app with a few hundred users, a single database + cron job works fine. But for something like a Flipkart Big Billion Days sale with millions of concurrent users, the architecture needs to be more thought out.</p><p><strong>Read replicas</strong> — The database gets a lot of read traffic (everyone checking coupons). Companies add read replicas — copies of the database that only handle reads. The main database only handles writes.</p><p><strong>Distributed Redis</strong> — A single Redis instance can handle a lot, but not unlimited. Redis Cluster lets you split the data across multiple nodes so the load is shared.</p><p><strong>Queue-based </strong><strong>used_count updates</strong> — Instead of updating <strong>used_count</strong> in the DB synchronously on every order, companies push those updates to a queue (like Kafka or RabbitMQ) and process them in batches. This prevents the DB from getting hammered during a spike.</p><p><strong>CDN for the countdown timer</strong> — The countdown you see on a product page? That doesn’t hit the backend every second. It’s usually calculated once and rendered client-side in JavaScript based on the <strong>end_time </strong>value returned in the initial page load.</p><h4>Quick Tech Stack Reference -</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/1*IXIzwJhMJs_ClIZl7GbSJg.png" /><figcaption>Tech stack</figcaption></figure><p>What looks like a simple discount code on the frontend is actually a coordination between a cache layer, a database, background workers, atomic operations, and carefully handled edge cases on the backend.</p><p>The next time a countdown timer hits zero and your coupon stops working you now know exactly what happened in those 10 milliseconds it took the server to say no</p><p><em>Found this useful? Follow for more backend explainers no fluff, just how things actually work. To get more context about me you can read below cool stuff. See you in next interesting one !!!!</em></p><ul><li><a href="https://medium.com/@spande6894/how-live-streaming-works-a-deep-dive-into-the-system-design-behind-it-acfb1f651475">How Live Streaming Works? :-A Deep Dive into the System Design Behind It</a></li><li><a href="https://medium.com/@spande6894/progressive-web-apps-pwas-in-depth-service-workers-manifests-offline-first-design-765db45753bc">Progressive Web Apps (PWAs) in Depth: Service Workers, Manifests &amp; Offline-First Design</a></li><li><a href="https://medium.com/@spande6894/behind-the-reel-how-instagram-decides-what-shows-up-in-your-feed-cd36a5f812d5">Behind the Reel: How Instagram Decides What Shows Up in Your Feed</a></li><li><a href="https://medium.com/@spande6894/system-design-for-ai-powered-search-recommendation-0f3f60f212a3">System Design for AI-Powered Search &amp; Recommendation</a></li><li><a href="https://medium.com/@spande6894/modern-browser-rendering-pipeline-from-html-to-pixels-266c4274b44a">Modern Browser Rendering Pipeline: From HTML to Pixels</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=93c9f3143c1c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Behind the Reel: How Instagram Decides What Shows Up in Your Feed]]></title>
            <link>https://medium.com/@spande6894/behind-the-reel-how-instagram-decides-what-shows-up-in-your-feed-cd36a5f812d5?source=rss-aea3d88bf956------2</link>
            <guid isPermaLink="false">https://medium.com/p/cd36a5f812d5</guid>
            <category><![CDATA[low-level-design]]></category>
            <category><![CDATA[instagram]]></category>
            <category><![CDATA[high-level-design]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Saurabh Rajesh Pande]]></dc:creator>
            <pubDate>Fri, 24 Jul 2026 19:08:42 GMT</pubDate>
            <atom:updated>2026-07-24T19:08:42.173Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mqsrm8gVm1WyKD3MPxTP7g.png" /><figcaption>cover image</figcaption></figure><h3>The Problem</h3><p>When you open Instagram, a ranking system answers one question, millions of times per second, across billions of (user, content) pairs:</p><blockquote><strong><em>Given everything this user has ever done, everything their network has done, and every piece of content that exists — what are the ~500 items most worth showing next, in what order?</em></strong></blockquote><p>The “friend liked/commented, so I saw it” phenomenon we are experiencing is <strong>not a separate feature bolted onto the algorithm</strong> it’s one of several <strong>candidate generation sources</strong> that feed into a much larger pipeline. To understand it properly we need four subsystems working together:</p><ol><li><strong>The Social Graph</strong> — who follows/is-connected-to whom, and edge “weights” (affinity)</li><li><strong>The Interaction/Event Pipeline</strong> — how a like/comment becomes a durable, Queryable fact</li><li><strong>Candidate Generation (Retrieval)</strong> — narrowing billions of posts down to a few thousand relevant ones per user</li><li><strong>Ranking (Scoring)</strong> — ML models that order those thousand candidates by predicted value</li></ol><p>Let’s build this system layer by layer.</p><h4>High-Level Architecture -</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JcBfwIIa-eRO-xMI7wFo_g.png" /><figcaption>High level architecture</figcaption></figure><p>lets walk through this architecture .</p><h4>The Social Graph: Who’s Connected to Whom -</h4><p><strong>Data Model -</strong></p><p>Instagram’s social graph isn’t a single “friends” relationship — it’s several overlapping directed graphs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/501/1*9566HvPZOzYJK1-tHvqJRA.png" /></figure><p>This is naturally a <strong>graph</strong>, but at Instagram’s scale (billions of nodes, hundreds of billions of edges) you don’t run this on a traditional graph database like Neo4j for online serving — you use a <strong>sharded, denormalized graph store</strong> (conceptually similar to Meta’s <strong>TAO</strong> — “The Associations and Objects” system) where:</p><ul><li><strong>Objects</strong> = users, posts, comments (immutable-ish entities with an ID)</li><li><strong>Associations</strong> = typed, directed edges with timestamps (user_likes_post, user_follows_user)</li></ul><p>TAO sits on top of MySQL shards with a massive caching layer in front (originally memcache-based), because graph traversal at read time (e.g., “give me all posts my 500 followees liked in the last 6 hours”) must resolve in <strong>single-digit milliseconds</strong>.</p><h4>Why a Graph Abstraction Specifically -</h4><p>The key operation your article is really asking about — <em>“a post my friend liked shows up for me”</em> — is a <strong>2-hop graph query</strong>:</p><p><strong>me — follows → friend — liked → post</strong></p><p>This is called <strong>Friend-of-Friend (FoF) propagation</strong>, and it’s one of the oldest and most powerful tricks in social recommendation, predating deep learning entirely (Facebook’s original “EdgeRank” from ~2010 was built almost entirely on this idea).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Nl1c6TeCdxTMzh58tXfIug.png" /></figure><p>Notice Reel #1 got liked by <strong>two</strong> of your friends (F1 and F2). This &quot;signal stacking&quot; matters a lot in ranking, which we&#39;ll formalize in Section 6.</p><h4>The Event Pipeline: From Tap to Durable Fact -</h4><p>When you double-tap a reel, here’s what happens <strong>before</strong> any recommendation logic even runs</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kMPEhtFPWcKLT9eO63Uw8g.png" /></figure><p>Key design decisions here, each of which is a real trade-off:</p><ol><li><strong>Asynchronous write path.</strong> The like is acknowledged to your device instantly (optimistic UI), while the actual fan-out and processing happens in the background. This is why sometimes a like “un-registers” after a refresh — the async write occasionally races or gets deduplicated.</li><li><strong>Append-only event log.</strong> Interactions are never mutated in place; they’re appended to an immutable log (this is the same pattern as Kafka’s log-structured storage, or event sourcing). This lets multiple downstream consumers (graph store, ML feature pipelines, analytics) all read the same stream independently.</li><li><strong>Lambda architecture (batch + streaming).</strong> Two parallel paths process the same data:</li></ol><ul><li><strong>Speed layer (streaming):</strong> Flink/Storm-style jobs compute rolling windows — “how many likes has this post gotten in the last 10 minutes” — needed for surfacing <em>trending</em> content within minutes.</li><li><strong>Batch layer:</strong> Nightly/hourly Spark jobs recompute more expensive aggregates (full embedding retraining, long-window statistics) that don’t need sub-second freshness.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1qJkdVL5ucxONSh7kDhZeg.png" /></figure><h4>Candidate Generation: From Billions to Thousands -</h4><p>This is the stage most people conflate with “the algorithm,” but it’s really the <strong>retrieval</strong> step — its entire job is to cheaply produce a <em>manageable</em> candidate pool (typically 1,000–5,000 posts) that the expensive ranking model will later score. There are usually 4–6 parallel <strong>retrieval sources</strong>, each specializing in a different signal type. Your “friend liked it” scenario is exactly one of these.</p><p><strong>Source A — Friend-Activity Retrieval (the one you’re asking about)</strong></p><p>Query pattern (conceptually, an approximation of what TAO-like systems execute):</p><pre>-- Pseudocode, not literal SQL against a graph store<br>SELECT post_id, COUNT(DISTINCT actor_id) as friend_engagement_count,<br>       ARRAY_AGG(actor_id) as which_friends<br>FROM interactions<br>WHERE actor_id IN (SELECT followee_id FROM follows WHERE follower_id = :me)<br>  AND action_type IN (&#39;like&#39;, &#39;comment&#39;, &#39;share&#39;)<br>  AND timestamp &gt; NOW() - INTERVAL &#39;72 hours&#39;<br>GROUP BY post_id<br>ORDER BY friend_engagement_count DESC<br>LIMIT 500</pre><p>At scale, this can’t literally be a live join across the whole graph every time you open the app — that would be too slow. Two engineering patterns solve this:</p><p><strong>Fan-out-on-write:-</strong> When friend A likes a post, the system immediately pushes a pointer to that post into a precomputed “candidate inbox” for every one of A’s followers. Fast reads, expensive/wasteful writes (huge fan-out for high-follower accounts).</p><p><strong>Fan-out-on-read:-</strong> Nothing is precomputed; when <em>you</em> open the app, the system does the 2-hop traversal live, pulling from your followers recent activity. Cheap writes, but read latency is higher and depends on how many people you follow.</p><p>Instagram (like Twitter/Facebook before it) uses a <strong>hybrid</strong> fan-out-on-write for typical users, fan-out-on-read (or a capped/sampled fan-out) for celebrity/high-degree accounts, to avoid a single popular like causing millions of writes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9qzi3_3V2yrsh1II6aiGnQ.png" /></figure><p><strong>Source B — Embedding-Based (ANN) Retrieval</strong></p><p>This is the deep-learning half. Every user and every piece of content gets mapped into the same <strong>dense vector space</strong> (typically 64–512 dimensions) such that “relevant” pairs are close together, via a <strong>two-tower neural network</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HKHAiCCk1mRQGJwplRF65Q.png" /></figure><p><strong>Why two towers and not one big model here?</strong> Because the <em>item</em> embeddings can be precomputed once for every post and stored in an <strong>Approximate Nearest Neighbor (ANN) index</strong> (HNSW, IVF-PQ, ScaNN, FAISS-style structures). At request time, you only need to compute <strong>your</strong> user embedding once, then do a fast ANN lookup — O(log N)-ish instead of comparing against every item.</p><p><strong>The math:</strong> the model is trained with a contrastive / softmax loss over positive and negative (user, item) pairs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/541/1*GmG6bPzqlaItRLax4KHugA.png" /></figure><p>Since summing over the entire catalog V (hundreds of millions of items) is intractable, training uses <strong>sampled softmax</strong> or <strong>in-batch negatives</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/434/1*An9BmJHG4J-BmKzwuDuCtQ.png" /></figure><p>where v+ is the positive (engaged) item and vi− are KK K sampled negatives (often other items in the same training batch — “in-batch negative sampling,” which is cheap because you get negatives for free from other users’ positives in the same minibatch).</p><p><strong>Source C — Collaborative Filtering Retrieval</strong></p><p>Classic “users who liked what you liked, also liked this.” Modeled via <strong>matrix factorization and </strong>we can factorize them like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/473/1*cUiDTEgtxLUe8N02j-UI_A.png" /></figure><p>learned by minimizing regularized squared error over <em>observed</em> entries only:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/1*zN8ux7LBkIOnuD8aKRLXDQ.png" /></figure><p>This is conceptually the ancestor of the two-tower neural model above — modern systems replaced the shallow bilinear factorization with deep networks, but the underlying idea (project users and items into a shared latent space) is the same.</p><p><strong>Source D — Trending / Popularity Retrieval -</strong></p><p>A simple velocity-based signal: content whose engagement rate is accelerating <em>right now</em>, regardless of your specific graph. Often modeled with something like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1004/1*BzJFUKaRwFMKsMovS3brzw.png" /></figure><p>This is what powers Explore/Reels-tab discovery of content from accounts you don’t even follow.</p><h4>Merging Candidate Sources -</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rlk3NnJktDJCb65ofajIow.png" /></figure><p>Each candidate typically carries a <strong>provenance tag</strong> — <em>why</em> it was retrieved (friend-liked, embedding-similar, trending, etc.) — because that provenance becomes an important <strong>feature</strong> in the ranking model, not just a debugging artifact.</p><h4>Ranking: The Expensive, Precise Stage -</h4><p>Retrieval answers “what’s plausibly relevant.” Ranking answers “in what exact order, and is it <em>actually</em> worth showing.” This is typically <strong>multi-stage</strong> because running a huge deep model on 2,500 candidates per user, times hundreds of millions of users, many times a day, is computationally enormous.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fl8VWoBnX4Il5VUUSiAl_g.png" /></figure><h4>The Core Prediction Task -</h4><p>The ranker doesn’t just predict “will they like it” — it predicts <strong>multiple actions simultaneously</strong> via a <strong>multi-task neural network</strong>, because “value” is genuinely multi-dimensional:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*noJVCGjGIDh-MUWHOQxVng.png" /></figure><p><strong>Each of these is typically a binary classification (or regression, for watch time) head sharing a common trunk of layers:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*izrcVzISfAk6DZMCAMhzOg.png" /></figure><p>The final score is a <strong>weighted combination</strong>, tuned to reflect product priorities (this weighting is itself a huge lever product/growth teams pull):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G3DX8AxQ4Dd4HADLT3GNVg.png" /></figure><h4>Where “Friend Liked This” Enters the Ranking Math -</h4><p>This is the crux of your article’s premise: the friend-signal isn’t just a retrieval trick — it re-appears as an explicit <strong>feature</strong> at ranking time, formalized in something close to the original <strong>EdgeRank</strong>-style formula (still conceptually alive inside modern systems, just now one input among thousands to a neural net rather than the whole algorithm):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R9K0EM-mkCtpMCYTiuFkgg.png" /></figure><p>Where:</p><ul><li><strong>Affinity(u, f)</strong> — a learned score of how much uu u actually interacts with friend ff f (DMs, profile visits, comment reciprocity) — <em>not</em> just the follow edge. This itself is often a small logistic regression or gradient-boosted tree over interaction-frequency features.</li><li><strong>Weight(action)</strong> — comments generally weighted higher than likes (higher intent), shares highest.</li><li><strong>Decay(t)</strong> — a time-decay function, typically exponential:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/377/1*BuoLqFmKCuV_vK0N09V8OA.png" /></figure><p>so a friend’s like from 2 hours ago counts more than one from 2 days ago.</p><p>Two friends liking the same post doesn’t just linearly add — it also acts as a strong <strong>feature interaction</strong> the neural ranker learns implicitly (e.g., “multiple independent friends engaging” correlates with genuinely higher quality/relevance, a weak form of crowd-sourced quality signal, similar in spirit to page-rank-style endorsement).</p><h4>Loss Function for Each Head -</h4><p>Each binary head (e.g., P(like)) is trained with standard <strong>binary cross-entropy</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/719/1*Y7dr5wfDib_Ha9MPEaRPPQ.png" /></figure><p>and the multi-task total loss is a weighted sum across heads:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/392/1*9N3RcKAXkKyEWTdmCdnONQ.png" /></figure><p>with αk ​ tuned per task (often via techniques like <strong>uncertainty weighting</strong> so tasks with noisier labels don’t dominate training).</p><h4>Re-Ranking: Diversity, Exploration, and Guardrails -</h4><p>A pure top-K-by-score feed would be extremely repetitive (e.g., ten reels from the same friend in a row, or all from one content category). The final re-ranking stage applies:</p><ol><li><strong>Diversity constraints</strong> — e.g., <strong>Maximal Marginal Relevance (MMR)</strong>-style penalization:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/862/1*AutmwBS9e7E43tzNDdMajQ.png" /></figure><p>This discourages showing near-duplicate content back-to-back even if both scored well.</p><ol><li><strong>Exploration / exploitation trade-off</strong> — the system deliberately injects some lower-confidence candidates to keep learning about your preferences and avoid <strong>filter bubbles feeding on themselves</strong>. This is a classic <strong>multi-armed bandit</strong> problem, often solved with <strong>Thompson Sampling</strong>:</li></ol><ul><li>Each candidate’s score is modeled as a distribution (not a point estimate), e.g., Beta(α, β) for a click-through rate.</li><li>You sample from each distribution and rank by the sampled value (not the mean), naturally balancing “confident good bets” with “under-explored, possibly great content.”</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xUPc7zPrGWnxNo7nvq4YyQ.png" /></figure><h4>Putting It All Together: End-to-End Sequence -</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0sHgNWd1ejIy2q-_ggc4UA.png" /></figure><h4>Storage Systems Cheat-Sheet -</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1009/1*00y-R68Ymj7S0nJDMgcsPQ.png" /></figure><p>Thanks for reading !!!! Here below some other blogs that you will find interesting</p><ul><li><a href="https://medium.com/@spande6894/system-design-for-ai-powered-search-recommendation-0f3f60f212a3">System Design for AI-Powered Search &amp; Recommendation</a></li><li><a href="https://medium.com/@spande6894/modern-browser-rendering-pipeline-from-html-to-pixels-266c4274b44a">Modern Browser Rendering Pipeline: From HTML to Pixels</a></li><li><a href="https://medium.com/@spande6894/progressive-web-apps-pwas-in-depth-service-workers-manifests-offline-first-design-765db45753bc">Progressive Web Apps (PWAs) in Depth: Service Workers, Manifests &amp; Offline-First Design</a></li><li><a href="https://medium.com/@spande6894/service-workers-in-2026-building-truly-offline-first-apps-that-feel-native-4ac9e700064f">Service Workers in 2026: Building Truly Offline-First Apps That Feel Native</a></li><li><a href="https://medium.com/@spande6894/how-live-streaming-works-a-deep-dive-into-the-system-design-behind-it-acfb1f651475">How Live Streaming Works? :-A Deep Dive into the System Design Behind It</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cd36a5f812d5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Service Workers in 2026: Building Truly Offline-First Apps That Feel Native]]></title>
            <link>https://medium.com/@spande6894/service-workers-in-2026-building-truly-offline-first-apps-that-feel-native-4ac9e700064f?source=rss-aea3d88bf956------2</link>
            <guid isPermaLink="false">https://medium.com/p/4ac9e700064f</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[workers]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[service-worker]]></category>
            <dc:creator><![CDATA[Saurabh Rajesh Pande]]></dc:creator>
            <pubDate>Fri, 17 Jul 2026 19:19:15 GMT</pubDate>
            <atom:updated>2026-07-17T19:19:15.926Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1ybdM4l_DwwC4JGMgCF8Gw.png" /><figcaption>cover image</figcaption></figure><p>Service Workers are the unsung heroes that make Progressive Web Apps (PWAs) truly powerful. They transform ordinary websites into reliable, installable, and native-feeling applications that work flawlessly offline.</p><h4>Why Service Workers Matter More Than Ever in 2026:-</h4><ul><li><strong>Offline Resilience</strong>: Users expect apps to work in airplanes, subways, or poor networks.</li><li><strong>Native-Like Experiences</strong>: Background processing, push notifications, and installability.</li><li><strong>Performance &amp; Cost Savings</strong>: Reduced server load through intelligent caching.</li><li><strong>Cross-Platform Reach</strong>: One codebase for web, desktop (via PWAs), and enhanced mobile.</li></ul><p>Major platforms (Spotify, Notion, Twitter/X, Starbucks) rely heavily on sophisticated Service Worker strategies.</p><h4>Service Worker Fundamentals &amp; Lifecycle:-</h4><p>A Service Worker is a JavaScript file that runs in the background, acting as a programmable proxy between the browser and the network.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YPg-QLBKBFBCjpYIC0mX-Q.png" /><figcaption>service worker lifecycle</figcaption></figure><p><strong>Lifecycle in Detail</strong>:</p><ul><li><strong>Registration</strong>: navigator.serviceWorker.register(‘/sw.js’)</li><li><strong>Install</strong>: Pre-cache assets (event.waitUntil())</li><li><strong>Activate</strong>: Clean old caches</li><li><strong>Fetch</strong>: Intercept network requests</li><li><strong>Update</strong>: New SW version detected → controlled takeover</li></ul><p><strong>Modern Registration (2026 Best Practice)</strong>:</p><pre>if (&#39;serviceWorker&#39; in navigator) {<br>  window.addEventListener(&#39;load&#39;, async () =&gt; {<br>    try {<br>      const registration = await navigator.serviceWorker.register(&#39;/sw.js&#39;, {<br>        scope: &#39;/&#39;  // Be careful with scope<br>      });<br>      console.log(&#39;SW registered with scope:&#39;, registration.scope);<br>    } catch (err) {<br>      console.error(&#39;SW registration failed:&#39;, err);<br>    }<br>  });<br>}</pre><h4>Caching Strategies for True Offline-First:-</h4><p><strong>Common Patterns</strong>:</p><ul><li><strong>Cache First</strong>: Serve from cache, fallback to network.</li><li><strong>Network First</strong>: Try network, fallback to cache.</li><li><strong>Stale While Revalidate</strong>: Serve cache immediately, update in background.</li><li><strong>Cache Only</strong>: For static assets.</li><li><strong>Network Only</strong>: For dynamic data.</li></ul><p>Advanced sw.js Implementation (2026):-</p><pre>const CACHE_NAME = &#39;app-v2.1&#39;;<br>const STATIC_ASSETS = [&#39;/&#39;, &#39;/styles.css&#39;, &#39;/app.js&#39;, &#39;/offline.html&#39;];<br><br>self.addEventListener(&#39;install&#39;, (event) =&gt; {<br>  event.waitUntil(<br>    caches.open(CACHE_NAME).then((cache) =&gt; cache.addAll(STATIC_ASSETS))<br>  );<br>});<br><br>self.addEventListener(&#39;fetch&#39;, (event) =&gt; {<br>  const url = new URL(event.request.url);<br>  <br>  // Skip non-GET or external requests<br>  if (event.request.method !== &#39;GET&#39; || url.origin !== location.origin) {<br>    return;<br>  }<br><br>  event.respondWith(<br>    (async () =&gt; {<br>      // Stale-While-Revalidate for most assets<br>      const cachedResponse = await caches.match(event.request);<br>      <br>      const fetchPromise = fetch(event.request).then(async (networkResponse) =&gt; {<br>        const cache = await caches.open(CACHE_NAME);<br>        cache.put(event.request, networkResponse.clone());<br>        return networkResponse;<br>      }).catch(() =&gt; caches.match(&#39;/offline.html&#39;));<br><br>      return cachedResponse || fetchPromise;<br>    })()<br>  );<br>});</pre><h4>Background Sync: Making Actions Work Offline:-</h4><p>Background Sync API lets you queue actions (form submissions, API calls) and replay them when connectivity returns.</p><p><strong>Implementation</strong>:-</p><pre>// In main app (client)<br>async function saveDataOffline(data) {<br>  const db = await openIDB(); // IndexedDB<br>  await db.put(&#39;offlineQueue&#39;, data);<br>  <br>  if (&#39;serviceWorker&#39; in navigator &amp;&amp; &#39;SyncManager&#39; in window) {<br>    const reg = await navigator.serviceWorker.ready;<br>    await reg.sync.register(&#39;sync-offline-data&#39;);<br>  }<br>}<br><br>// In sw.js<br>self.addEventListener(&#39;sync&#39;, async (event) =&gt; {<br>  if (event.tag === &#39;sync-offline-data&#39;) {<br>    event.waitUntil(syncOfflineQueue());<br>  }<br>});<br><br>async function syncOfflineQueue() {<br>  const db = await openIDB();<br>  const queue = await db.getAll(&#39;offlineQueue&#39;);<br>  <br>  for (const item of queue) {<br>    try {<br>      await fetch(&#39;/api/save&#39;, { method: &#39;POST&#39;, body: JSON.stringify(item) });<br>      await db.delete(&#39;offlineQueue&#39;, item.id);<br>    } catch (e) {<br>      // Keep in queue if still failing<br>    }<br>  }<br>}</pre><h4>Periodic Background Sync: Proactive Updates:-</h4><p>Requires user permission and is more restricted.</p><p><strong>Registration</strong>:</p><pre>navigator.serviceWorker.ready.then((registration) =&gt; {<br>  registration.periodicSync.register(&#39;content-update&#39;, {<br>    minInterval: 24 * 60 * 60 * 1000  // 24 hours<br>  });<br>});</pre><p><strong>In Service Worker</strong>:-</p><pre>self.addEventListener(&#39;periodicsync&#39;, (event) =&gt; {<br>  if (event.tag === &#39;content-update&#39;) {<br>    event.waitUntil(updateContentInBackground());<br>  }<br>});</pre><p>Use Cases: News apps refreshing articles, email clients checking for new messages, fitness apps syncing workouts.</p><h4>Push Notifications &amp; Advanced Capabilities:-</h4><ul><li><strong>Push API</strong> + <strong>Notifications API</strong> for re-engagement.</li><li><strong>File System Access API</strong> + Service Workers for local file handling.</li><li><strong>Badging API</strong> for unread counts.</li><li><strong>Web Share Target</strong> for deeper OS integration.</li></ul><h4>Security, Performance &amp; Production Considerations:-</h4><p>Security:-</p><ul><li>Service Workers only run over HTTPS.</li><li>Scope limitations prevent broad attacks.</li><li>Careful with sensitive data in caches (use Cache-Control: private or avoid caching).</li></ul><p><strong>Performance</strong>:-</p><ul><li>Keep Service Worker lean.</li><li>Use self.skipWaiting() + clients.claim() for faster updates.</li><li>Monitor cache sizes (storage quotas apply).</li></ul><p><strong>Testing</strong>:-</p><ul><li>Chrome DevTools Application tab.</li><li>Lighthouse PWA audits.</li><li>Network throttling.</li></ul><p><strong>Common Pitfalls</strong>:-</p><ul><li>Infinite update loops.</li><li>Caching too aggressively (stale data).</li><li>Ignoring iOS Safari limitations (improved but still behind).</li></ul><h4>Real-World Modern Examples (2026):-</h4><ul><li><strong>Spotify</strong>: Seamless offline playlists with background sync.</li><li><strong>Notion</strong>: Full document editing offline with sync on reconnect.</li><li><strong>Figma-like Tools</strong>: Real-time collaboration with offline mode.</li><li><strong>E-commerce PWAs</strong>: Cart persistence and checkout queuing.</li><li><strong>News Apps</strong> (e.g., modern NYT clones): Periodic sync + push.</li></ul><h4>Complete Production-Ready Blueprint:-</h4><p><strong>Recommended Folder Structure</strong>:</p><pre>/public<br>  /sw.js<br>  /manifest.json<br>  /offline.html<br>/src<br>  /register-sw.js<br>  /idb.js (IndexedDB helpers)</pre><p><strong>Full Strategy</strong>:-</p><ul><li>App Shell + Dynamic Content Caching</li><li>Background Sync for Mutations</li><li>Periodic Sync for Fresh Data</li><li>Graceful Degradation + Skeleton Screens</li></ul><p>Thanks for reading !!!!!!!</p><ul><li><a href="https://medium.com/@spande6894/system-design-for-ai-powered-search-recommendation-0f3f60f212a3">System Design for AI-Powered Search &amp; Recommendation</a></li><li><a href="https://medium.com/@spande6894/modern-browser-rendering-pipeline-from-html-to-pixels-266c4274b44a">Modern Browser Rendering Pipeline: From HTML to Pixels</a></li><li><a href="https://medium.com/@spande6894/progressive-web-apps-pwas-in-depth-service-workers-manifests-offline-first-design-765db45753bc">Progressive Web Apps (PWAs) in Depth: Service Workers, Manifests &amp; Offline-First Design</a></li><li><a href="https://medium.com/@spande6894/how-live-streaming-works-a-deep-dive-into-the-system-design-behind-it-acfb1f651475">How Live Streaming Works? :-A Deep Dive into the System Design Behind It</a></li><li><a href="https://medium.com/@spande6894/webassembly-wasm-and-the-future-of-high-performance-web-apps-de9c4f3e6c84">WebAssembly (Wasm) and the Future of High-Performance Web Apps</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4ac9e700064f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[System Design for AI-Powered Search & Recommendation]]></title>
            <link>https://medium.com/@spande6894/system-design-for-ai-powered-search-recommendation-0f3f60f212a3?source=rss-aea3d88bf956------2</link>
            <guid isPermaLink="false">https://medium.com/p/0f3f60f212a3</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[vector-search]]></category>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[vector-database]]></category>
            <dc:creator><![CDATA[Saurabh Rajesh Pande]]></dc:creator>
            <pubDate>Sat, 11 Jul 2026 15:20:05 GMT</pubDate>
            <atom:updated>2026-07-11T15:20:05.793Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SPcgHydD8q8AQadTWI5Qcg.png" /><figcaption>cover image</figcaption></figure><p>AI-powered search and recommendation systems have transformed how users discover content from Netflix suggestions to semantic Google-like search. At the heart of these systems are <strong>vector databases</strong>, <strong>embeddings</strong>, and <strong>hybrid search</strong> strategies.</p><p>This guide covers basic system design key concepts, mathematical foundations, practical code examples, popular tools (Pinecone, Weaviate), and real-world considerations. (for in depth guides you can refer official docs)</p><h4>Why Traditional Search Falls Short:-</h4><p>Keyword-based search (BM25, TF-IDF) struggles with:</p><ul><li>Semantic understanding (synonyms, intent).</li><li>Multimodal data (images, video, audio).</li><li>Personalization at scale.</li></ul><p><strong>Vector Search</strong> solves this by representing data and queries as high-dimensional vectors in embedding space.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*muEk0WpoHtZgHtd7V_Iqmw.png" /></figure><h4>Embeddings: The Foundation:-</h4><p>Embeddings are dense vector representations (typically 256–1536 dimensions) that capture semantic meaning.</p><p><strong>Popular Models</strong>:</p><ul><li>OpenAI text-embedding-3-large</li><li>Hugging Face Sentence-Transformers</li><li>Cohere, Voyage, etc.</li></ul><p><strong>Mathematical Representation</strong>: A document d is mapped to a vector —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/134/1*pxguAQ2uoR19M-1dDAwyvQ.png" /></figure><h4>Vector Similarity Metrics:-</h4><p>The most common is Cosine Similarity:-</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/473/1*VRSKew1fC93iU6D5HNxdsA.png" /><figcaption>cosine similarity formula</figcaption></figure><p>Other Metrics:-</p><p>Euclidean Distance: -</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/137/1*gegVvKzSGD5021aLxuB7UQ.png" /></figure><ul><li>Dot Product (for normalized vectors)</li><li>Hamming (for binary vectors)</li></ul><p>Code Example (Python):-</p><pre>import numpy as np<br><br>def cosine_similarity(a: np.ndarray, b: np.ndarray) -&gt; float:<br>    return np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b))<br><br># Example<br>query_emb = np.array([0.1, 0.2, 0.3])<br>doc_emb = np.array([0.15, 0.25, 0.28])<br><br>print(cosine_similarity(query_emb, doc_emb))  # ~0.99 (very similar)</pre><h4>Vector Databases: Pinecone vs Weaviate:-</h4><p><strong>Pinecone</strong>:</p><ul><li>Fully managed, serverless.</li><li>Excellent for production with high QPS.</li><li>Supports metadata filtering, namespaces, and pods/indexes.</li></ul><p><strong>Weaviate</strong>:-</p><ul><li>Open-source with great schema flexibility.</li><li>Strong hybrid search and modular architecture.</li><li>Good for self-hosted or complex object relationships.</li></ul><p><strong>Core Components of a Vector DB</strong>:-</p><ul><li><strong>Indexing</strong>: HNSW (Hierarchical Navigable Small World), IVF, etc. for approximate nearest neighbors (ANN).</li><li><strong>Storage</strong>: Efficient vector + metadata storage.</li><li><strong>Query Engine</strong>: Hybrid search, reranking, filtering.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nvqTFZZYylFP8ULr1UjiXw.png" /></figure><h4>Hybrid Search Architecture:-</h4><p>Best results combine vector (semantic) + keyword (exact) search.</p><p><strong>Weighted Hybrid Score</strong>:-</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/481/1*9hzgEKrusQQQBuUyR_-Cgg.png" /></figure><p>Implementation Example (Weaviate-style):-</p><pre># Pseudo-code for hybrid query<br>def hybrid_search(query_text: str, alpha: float = 0.7):<br>    query_vec = embed(query_text)<br>    keyword_results = bm25_search(query_text)  # Sparse<br>    vector_results = vector_db.query(<br>        vector=query_vec,<br>        limit=50,<br>        filter=metadata_filter<br>    )<br>    <br>    # Merge and rerank<br>    combined = merge_results(keyword_results, vector_results, alpha)<br>    return rerank(combined, query_text)</pre><p><strong>Pinecone Example (Python SDK)</strong>:-</p><pre>import pinecone<br><br>pinecone.init(api_key=&quot;your-key&quot;, environment=&quot;us-west1-gcp&quot;)<br>index = pinecone.Index(&quot;my-index&quot;)<br><br># Upsert<br>index.upsert(vectors=[(&quot;doc1&quot;, embedding, {&quot;category&quot;: &quot;tech&quot;})])<br><br># Query with metadata filter<br>results = index.query(<br>    vector=query_embedding,<br>    top_k=10,<br>    filter={&quot;category&quot;: {&quot;$eq&quot;: &quot;tech&quot;}},<br>    include_metadata=True<br>)</pre><h4>End-to-End System Design:-</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HLtxONxWe8DyraZqIjrOjQ.png" /></figure><h4>Key Services:-</h4><ul><li><strong>Embedding Service</strong>: Scalable, cached, with model versioning.</li><li><strong>Ingestion Pipeline</strong>: Batch + real-time (Kafka + Spark/Flink).</li><li><strong>Query Service</strong>: Low-latency (&lt;100ms p95).</li><li><strong>Monitoring</strong>: Latency, recall, relevance metrics.</li></ul><p><strong>Scaling Considerations</strong>:-</p><ul><li>Sharding vectors.</li><li>Approximate vs exact search trade-offs.</li><li>Cost optimization (quantization, tiered storage).</li></ul><h4>Advanced Techniques (2026):-</h4><ul><li><strong>Multi-Vector / Late Interaction</strong> (ColBERT-style).</li><li><strong>RAG (Retrieval-Augmented Generation)</strong>: Vector search + LLM.</li><li><strong>Product Quantization</strong> for memory efficiency.</li><li><strong>Graph + Vector</strong> hybrids for recommendations.</li><li><strong>Federated / Privacy-Preserving</strong> search.</li></ul><p><strong>LLM Reranking Example</strong> (simple cross-encoder):-</p><pre>from sentence_transformers import CrossEncoder<br><br>model = CrossEncoder(&#39;cross-encoder/ms-marco-MiniLM-L-6-v2&#39;)<br><br>def rerank(query: str, candidates: list):<br>    pairs = [[query, cand[&#39;text&#39;]] for cand in candidates]<br>    scores = model.predict(pairs)<br>    return sorted(zip(candidates, scores), key=lambda x: x[1], reverse=True)</pre><h4>Challenges &amp; Best Practices:-</h4><p><strong>Challenges</strong>:-</p><ul><li>Embedding model drift.</li><li>High dimensionality curse.</li><li>Cost of vector storage and queries.</li><li>Evaluation (recall@K, NDCG, human relevance).</li></ul><p><strong>Best Practices</strong>:-</p><ul><li>Start with hybrid search.</li><li>Implement A/B testing for ranking.</li><li>Monitor embedding quality over time.</li><li>Use quantization (INT8, binary) for scale.</li><li>Secure embeddings (avoid leaking sensitive data).</li></ul><p>Thanks for reading !!!!</p><ul><li><a href="https://medium.com/@spande6894/modern-browser-rendering-pipeline-from-html-to-pixels-266c4274b44a">Modern Browser Rendering Pipeline: From HTML to Pixels</a></li><li><a href="https://medium.com/@spande6894/virtual-dom-reconciliation-how-react-and-modern-frameworks-achieve-blazing-performance-be121fa0008d">Virtual DOM &amp; Reconciliation: How React (and Modern Frameworks) Achieve Blazing Performance</a></li><li><a href="https://medium.com/@spande6894/progressive-web-apps-pwas-in-depth-service-workers-manifests-offline-first-design-765db45753bc">Progressive Web Apps (PWAs) in Depth: Service Workers, Manifests &amp; Offline-First Design</a></li><li><a href="https://medium.com/@spande6894/how-live-streaming-works-a-deep-dive-into-the-system-design-behind-it-acfb1f651475">How Live Streaming Works? :-A Deep Dive into the System Design Behind It</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0f3f60f212a3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[WebAssembly (Wasm) and the Future of High-Performance Web Apps]]></title>
            <link>https://medium.com/@spande6894/webassembly-wasm-and-the-future-of-high-performance-web-apps-de9c4f3e6c84?source=rss-aea3d88bf956------2</link>
            <guid isPermaLink="false">https://medium.com/p/de9c4f3e6c84</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[webassembly]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Saurabh Rajesh Pande]]></dc:creator>
            <pubDate>Thu, 09 Jul 2026 18:24:46 GMT</pubDate>
            <atom:updated>2026-07-09T18:24:46.350Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oHfO-5DT1MmHfY8EBd4kZg.png" /><figcaption>cover image</figcaption></figure><p>For years, the web was limited by JavaScript’s single-threaded nature and performance constraints. <strong>WebAssembly (Wasm)</strong> changed that forever. It brings near-native speed to the browser, unlocking applications previously possible only in native desktop or mobile apps.</p><p>This deep dive explores what <strong>Wasm </strong>is, how it works, major use cases (gaming, in-browser video editing, ML inference), modern ecosystem (2026), and what the future holds.</p><h4>What is WebAssembly?:-</h4><p>WebAssembly is a <strong>binary instruction format</strong> for a stack-based virtual machine. It is designed as a portable compilation target for high-level languages like<strong> C, C++, Rust, Go</strong>, and more.</p><p><strong>Key Characteristics</strong>:-</p><ul><li><strong>Safe</strong>: Runs in a sandboxed environment with strict memory isolation.</li><li><strong>Fast</strong>: Near-native execution speed (often 1.5–3x faster than optimized JavaScript for compute-heavy tasks).</li><li><strong>Compact</strong>: Small binary size and efficient loading.</li><li><strong>Interoperable</strong>: Seamlessly works with JavaScript via the WebAssembly JavaScript API.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3cxU0gBDOtfalDzzkLZrBQ.png" /><figcaption>typical flow</figcaption></figure><h4>How WebAssembly Works:-</h4><ol><li><strong>Compilation</strong>: Source code → Wasm binary (ahead-of-time or just-in-time).</li><li><strong>Instantiation</strong>: Browser loads .wasm file and creates a module instance.</li><li><strong>Execution</strong>: Wasm runs in its own linear memory space, calling into JS when needed (and vice versa).</li><li><strong>Integration</strong>: Use WebAssembly.instantiateStreaming() for efficient loading.</li></ol><h4>Modern Improvements (2026):-</h4><ul><li><strong>WasmGC</strong> (Garbage Collection) — better support for languages with GC.</li><li><strong>Component Model</strong> — standardized way to compose modules.</li><li><strong>Wasm Threads</strong> + SharedArrayBuffer for parallelism.</li><li><strong>SIMD</strong> (Single Instruction Multiple Data) for vectorized operations.</li><li><strong>Tail Call Optimization</strong> and other language features.</li></ul><h4>Major Use Cases:-</h4><h4>Gaming</h4><p>Wasm powers high-performance browser games that rival native titles.</p><p><strong>Examples</strong>:-</p><ul><li><strong>Unity WebGL</strong> and <strong>Unreal Engine</strong> exports.</li><li><strong>Doom</strong>, <strong>Quake</strong>, and modern indie titles running smoothly.</li><li><strong>Google Stadia</strong> (former) and cloud gaming hybrids.</li></ul><p><strong>Why Wasm Wins</strong>:-</p><ul><li>Heavy physics, AI, and rendering logic in C++/Rust.</li><li>Access to WebGL/WebGPU for graphics.</li><li>Near 60–120 FPS performance.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*68ULTz0np-49iHWE31koYg.png" /></figure><h4>In-Browser Video Editing -</h4><p>Professional-grade editing without server uploads.</p><p><strong>Examples</strong>:-</p><ul><li>Tools like <strong>CapCut Web</strong>, <strong>Descript</strong>, and open-source projects using FFmpeg.wasm.</li><li>Real-time filters, trimming, effects, and exports.</li></ul><p><strong>Technical Advantages</strong>:-</p><ul><li>Port of <strong>FFmpeg</strong> (via Emscripten) for decoding/encoding.</li><li>Web Workers for background processing.</li><li>WebCodecs API for hardware-accelerated encoding.</li><li>Massive reduction in upload bandwidth and privacy benefits.</li></ul><p><strong>Performance Tip</strong>: Combine Wasm with WebGPU for GPU-accelerated effects.</p><h4>Machine Learning Inference-</h4><p>Running AI models directly in the browser.</p><p><strong>Examples</strong>:-</p><ul><li><strong>TensorFlow.js</strong> + Wasm backend.</li><li><strong>ONNX Runtime Web</strong>, <strong>Transformers.js</strong>, <strong>Whisper Web</strong>.</li><li>Image classification, object detection, NLP, and generative AI (stable diffusion variants).</li></ul><p><strong>Why It Matters</strong>:-</p><ul><li>Privacy (data never leaves the device).</li><li>Low latency (no network round-trips).</li><li>Offline capability (perfect for PWAs).</li><li>Edge AI for IoT/web hybrids.</li></ul><p>2026 Landscape: WebNN (Web Neural Network API) + Wasm for accelerated inference on CPU/GPU/NPU.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L22BwMYLoUh9iVyNAbPVsw.png" /></figure><h4>Other Emerging Use Cases:-</h4><ul><li><strong>CAD / 3D Modeling</strong>: AutoCAD web, Blender-like tools.</li><li><strong>Scientific Computing</strong>: Simulations, data visualization (e.g., Observable + Wasm).</li><li><strong>Cryptography &amp; Security</strong>: High-performance encryption libraries.</li><li><strong>Emulators</strong>: Retro gaming, old software preservation.</li><li><strong>Databases</strong>: SQLite.wasm, DuckDB.wasm for client-side analytics.</li><li><strong>Audio Processing</strong>: Real-time effects, DAWs in browser.</li></ul><h4>The Ecosystem &amp; Tooling (2026):-</h4><ul><li><strong>Compilers</strong>: Emscripten (C/C++), wasm-pack (Rust), TinyGo.</li><li><strong>Runtimes</strong>: Wasmtime, WasmEdge (edge/server), browser engines.</li><li><strong>Frameworks</strong>: Blazor (C#), Leptos/Yew (Rust), Sycamore.</li><li><strong>Integration</strong>: wasm-bindgen, WASI (WebAssembly System Interface) for broader capabilities.</li><li><strong>Debugging</strong>: Chrome DevTools + source maps, wasm-gdb.</li></ul><p><strong>Performance Comparison</strong> (typical benchmarks):-</p><ul><li>JavaScript: Baseline.</li><li>Wasm: 1.5–4x faster for compute-bound tasks.</li><li>With SIMD + Threads: Even higher gains.</li></ul><h4>Challenges &amp; Limitations:-</h4><ul><li><strong>Cold Start</strong>: Initial download and compilation time (mitigated by caching and streaming).</li><li><strong>Debugging</strong>: Steeper curve than pure JS.</li><li><strong>Memory Management</strong>: Linear memory model requires care (though GC helps).</li><li><strong>Ecosystem Maturity</strong>: Still growing for some languages.</li><li><strong>Browser Support</strong>: Excellent in modern browsers, but consider polyfills/fallbacks.</li></ul><h4>Best Practices for Wasm in Production:-</h4><ul><li><strong>Keep JS Thin</strong>: Use Wasm for heavy computation only.</li><li><strong>Modularize</strong>: Split large modules; load on demand.</li><li><strong>Profile Relentlessly</strong>: Use browser profilers and console.time.</li><li><strong>Optimize Binaries</strong>: Strip debug info, use -O3, consider binaryen.</li><li><strong>Combine with Modern Web APIs</strong>: Web Workers, WebGPU, WebCodecs, Offscreen Canvas.</li><li><strong>Progressive Enhancement</strong>: Graceful fallback to JS implementations.</li></ul><h4>The Future of Wasm:-</h4><ul><li>Tighter integration with WebGPU for graphics/ML.</li><li>Expanded WASI for more system-like capabilities.</li><li>Better multi-threading and shared memory.</li><li>AI-accelerated compilation and optimization.</li><li>Server-side Wasm (edge computing, serverless) blurring web/backend boundaries.</li></ul><p><strong>Wasm </strong>is not replacing <strong>JavaScript </strong>— it’s complementing it, enabling a new class of ambitious web applications.</p><p>Thanks for reading!!</p><ul><li><a href="https://medium.com/@spande6894/modern-browser-rendering-pipeline-from-html-to-pixels-266c4274b44a">Modern Browser Rendering Pipeline: From HTML to Pixels</a></li><li><a href="https://medium.com/@spande6894/progressive-web-apps-pwas-in-depth-service-workers-manifests-offline-first-design-765db45753bc">Progressive Web Apps (PWAs) in Depth: Service Workers, Manifests &amp; Offline-First Design</a></li><li><a href="https://medium.com/@spande6894/how-live-streaming-works-a-deep-dive-into-the-system-design-behind-it-acfb1f651475">How Live Streaming Works? :-A Deep Dive into the System Design Behind It</a></li><li><a href="https://medium.com/@spande6894/behind-the-swipe-reel-shorts-scrolling-and-engineering-magic-of-infinite-scroll-0ea5039b007e">Behind the Swipe (reel/shorts scrolling) and Engineering Magic of Infinite Scroll</a></li><li><a href="https://medium.com/@spande6894/virtual-dom-reconciliation-how-react-and-modern-frameworks-achieve-blazing-performance-be121fa0008d">Virtual DOM &amp; Reconciliation: How React (and Modern Frameworks) Achieve Blazing Performance</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=de9c4f3e6c84" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Modern Browser Rendering Pipeline: From HTML to Pixels]]></title>
            <link>https://medium.com/@spande6894/modern-browser-rendering-pipeline-from-html-to-pixels-266c4274b44a?source=rss-aea3d88bf956------2</link>
            <guid isPermaLink="false">https://medium.com/p/266c4274b44a</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[html]]></category>
            <dc:creator><![CDATA[Saurabh Rajesh Pande]]></dc:creator>
            <pubDate>Sun, 05 Jul 2026 18:42:00 GMT</pubDate>
            <atom:updated>2026-07-05T18:42:00.351Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c-5zmrxGj8-Qjc7xfnd8DA.png" /><figcaption>Cover image</figcaption></figure><p>Understanding how browsers turn HTML, CSS, and JavaScript into pixels on your screen is one of the most valuable skills for web developers in 2026. Every millisecond of delay in this pipeline affects user experience, Core Web Vitals, SEO, and conversion rates.</p><p>This article explores the <strong>Critical Rendering Path (CRP)</strong>, the stages of the modern browser rendering pipeline (Parse → Style → Layout → Paint → Composite), and actionable performance optimizations.</p><h4>The Big Picture: What Happens When You Load a Page?:-</h4><p>When you navigate to a URL, the browser goes through a sophisticated multi-stage pipeline to render content. The goal: deliver the first meaningful paint as fast as possible while maintaining smooth 60fps interactions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Uo5UjyiEhxRBXSsJaO0ayQ.png" /><figcaption>Rendering flow</figcaption></figure><p><strong>Key Metrics</strong>:-</p><ul><li><strong>Time to First Byte (TTFB)</strong></li><li><strong>First Contentful Paint (FCP)</strong></li><li><strong>Largest Contentful Paint (LCP)</strong></li><li><strong>Cumulative Layout Shift (CLS)</strong></li><li><strong>Interaction to Next Paint (INP)</strong></li></ul><h4>Step 1: Parsing HTML &amp; Building the DOM:-</h4><ul><li>Browser fetches HTML → starts <strong>incremental parsing</strong>.</li><li>Constructs <strong>DOM Tree</strong> (tree of Node objects).</li><li>Encounters &lt;script&gt; tags (especially without async/defer) → blocks parsing.</li></ul><p><strong>Performance Tip</strong>: Place scripts at the end or use async/defer. Preload critical resources with &lt;link rel=”preload”&gt;.</p><h4>Step 2: CSS &amp; CSSOM Construction:-</h4><ul><li>CSS is parsed into <strong>CSS Object Model (CSSOM)</strong>.</li><li>CSS is render-blocking by default (browser waits for it before painting).</li><li>Media queries and complex selectors increase computation time.</li></ul><p><strong>Modern Optimization</strong>:-</p><ul><li>Split critical vs. non-critical CSS.</li><li>Use media=”print” or onload tricks for non-critical stylesheets.</li><li>Inline critical CSS for above-the-fold content.</li></ul><h4>Step 4: Render Tree Construction:-</h4><p>Combines DOM + CSSOM → <strong>Render Tree</strong> (only visible nodes).</p><ul><li>Ignores display: none elements.</li><li>Includes pseudo-elements (::before, ::after).</li></ul><h4>Step 5: Layout (Reflow):-</h4><p>Calculates exact position and size of every visible element.</p><p><strong>Expensive Operations</strong> (trigger reflows):</p><ul><li>Reading/writing offsetWidth, clientHeight, etc.</li><li>Changing layout-affecting styles (width, height, margin, padding, position, display, etc.).</li><li>Adding/removing elements.</li></ul><p><strong>2026 Tip</strong>: Use transform and opacity for animations (they only trigger compositing).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1tgm6Vi121cJobbg1u6snA.png" /></figure><h4>Step 6: Paint:-</h4><p>Fills pixels: backgrounds, text, borders, shadows, etc.</p><ul><li>Happens in <strong>paint layers</strong>.</li><li>Expensive for complex shadows, gradients, or large areas.</li></ul><p><strong>Performance Tip</strong>: Minimize paint areas. Use will-change: transform judiciously.</p><h4>Step 7: Compositing:-</h4><p>Modern browsers use GPU acceleration here. Layers are composited together.</p><p><strong>Compositing Advantages</strong>:</p><ul><li>Fast for animations (translate, scale, rotate, opacity).</li><li>Hardware-accelerated.</li></ul><p><strong>Layer Promotion</strong> (creates new composite layer):</p><ul><li>transform: translateZ(0) or will-change: transform</li><li>opacity &lt; 1</li><li>filter, backdrop-filter</li><li>Video elements, canvas, etc.</li></ul><p><strong>Warning</strong>: Too many layers increase memory usage and can hurt performance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ok_LU-up6OFQegynR5Xsig.png" /></figure><h4>JavaScript Impact on the Pipeline:-</h4><p>JavaScript can block parsing, trigger style recalculations, layouts (reflows), and paints.</p><ul><li><strong>Forced Synchronous Layouts</strong> (reading layout properties after style changes) are particularly bad.</li><li>Long tasks block the main thread → poor INP scores.</li></ul><p><strong>Best Practices</strong>:</p><ul><li>Use requestAnimationFrame for visual updates.</li><li>Offload heavy work to Web Workers.</li><li>Debounce/throttle expensive handlers.</li><li>Adopt modern frameworks with fine-grained reactivity (e.g., Solid) or compiler optimizations (React Compiler) to minimize updates.</li></ul><h4>Critical Rendering Path Optimization:-</h4><p>To achieve fast <strong>Largest Contentful Paint (LCP)</strong>:</p><ol><li><strong>Minimize TTFB</strong> → Optimize server, use CDN, cache aggressively.</li><li><strong>Reduce blocking resources</strong> → Inline critical CSS/JS, defer non-critical.</li><li><strong>Optimize images</strong> → Responsive images, modern formats (WebP/AVIF), lazy loading.</li><li><strong>Font optimization</strong> → font-display: swap, self-host or use preload.</li><li><strong>Prioritize visible content</strong> → Above-the-fold optimization.</li></ol><p><strong>Advanced Techniques (2026)</strong>:</p><ul><li><strong>Speculation Rules API</strong> for prerendering likely next pages.</li><li><strong>Container Queries</strong> and modern CSS for more efficient styling.</li><li><strong>View Transitions API</strong> for smooth navigation.</li><li><strong>@layer</strong> for better cascade control.</li></ul><h4>Common Performance Pitfalls &amp; Fixes:-</h4><ul><li><strong>Layout Thrashing</strong>: Batch reads and writes.</li><li><strong>Memory Leaks</strong> from detached DOM nodes or heavy listeners.</li><li><strong>Over-eager animations</strong> → Use prefers-reduced-motion.</li><li><strong>Unoptimized third-party scripts</strong> → Lazy-load or self-host where possible.</li><li><strong>Large JavaScript bundles</strong> → Code splitting, tree shaking, module federation.</li></ul><p><strong>Tools You Must Use</strong>:-</p><ul><li>Chrome DevTools (Performance, Lighthouse, Layers panel)</li><li>Lighthouse CI</li><li>WebPageTest</li><li>Core Web Vitals in Search Console</li></ul><h4>Real-World Examples:-</h4><ul><li><strong>High-Performance Sites</strong>: Google, YouTube, and many PWAs achieve sub-1s LCP through aggressive CRP optimization.</li><li><strong>E-commerce</strong>: Lazy loading below-fold content + skeleton screens.</li><li><strong>News Sites</strong>: Streaming HTML with partial hydration.</li></ul><p>Thanks for reading ! If you like this article then you should check out these below articles also .</p><ul><li><a href="https://medium.com/@spande6894/progressive-web-apps-pwas-in-depth-service-workers-manifests-offline-first-design-765db45753bc">Progressive Web Apps (PWAs) in Depth: Service Workers, Manifests &amp; Offline-First Design</a></li><li><a href="https://medium.com/@spande6894/how-live-streaming-works-a-deep-dive-into-the-system-design-behind-it-acfb1f651475">How Live Streaming Works? :-A Deep Dive into the System Design Behind It</a></li><li><a href="https://medium.com/@spande6894/behind-the-swipe-reel-shorts-scrolling-and-engineering-magic-of-infinite-scroll-0ea5039b007e">Behind the Swipe (reel/shorts scrolling) and Engineering Magic of Infinite Scroll</a></li><li><a href="https://medium.com/@spande6894/how-offline-web-applications-work-exploring-client-side-interactivity-technologies-and-9e0e9cd7498e">How Offline Web Applications Work- Exploring Client-Side Interactivity, Technologies, and…</a></li><li><a href="https://medium.com/@spande6894/virtual-dom-reconciliation-how-react-and-modern-frameworks-achieve-blazing-performance-be121fa0008d">Virtual DOM &amp; Reconciliation: How React (and Modern Frameworks) Achieve Blazing Performance</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=266c4274b44a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Virtual DOM & Reconciliation: How React (and Modern Frameworks) Achieve Blazing Performance]]></title>
            <link>https://medium.com/@spande6894/virtual-dom-reconciliation-how-react-and-modern-frameworks-achieve-blazing-performance-be121fa0008d?source=rss-aea3d88bf956------2</link>
            <guid isPermaLink="false">https://medium.com/p/be121fa0008d</guid>
            <category><![CDATA[virtual-dom]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[front-end-development]]></category>
            <dc:creator><![CDATA[Saurabh Rajesh Pande]]></dc:creator>
            <pubDate>Mon, 29 Jun 2026 18:57:35 GMT</pubDate>
            <atom:updated>2026-06-29T18:57:35.465Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OLz_jRUkWTztYjWEKZ8e_A.png" /></figure><h4>The Problem: Why the Real DOM is Slow:-</h4><p>he browser’s DOM is a tree of objects. Every change (add/remove/update) triggers:</p><ul><li>Layout recalculations (reflow)</li><li>Repaints</li><li>Style recalculations</li></ul><p>Direct manipulation at scale (e.g., frequent list updates) causes jank and poor performance.</p><p><strong>Virtual DOM Solution</strong>: Maintain a lightweight JavaScript representation of the UI. Compute minimal changes, then batch-apply them to the real DOM.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/366/1*t7vFdKuRSqMo-B9Eu-hHKw.png" /><figcaption>flow of virtual DOM</figcaption></figure><h4>Virtual DOM Basics:-</h4><p>The Virtual DOM is a plain JavaScript object tree mirroring the real DOM structure.</p><pre><br>const element = {<br>  type: &#39;div&#39;,<br>  props: {<br>    className: &#39;container&#39;,<br>    children: [<br>      { type: &#39;h1&#39;, props: { children: &#39;Hello&#39; } },<br>      { type: &#39;p&#39;, props: { children: &#39;World&#39; } }<br>    ]<br>  }<br>};</pre><p>React creates this tree on every render (for components that need updating).</p><h4>Reconciliation &amp; Diffing Algorithm:-</h4><p>Reconciliation is React’s process of comparing the previous Virtual DOM tree with the new one to compute the minimal set of changes.</p><p><strong>Classic Diffing Heuristics</strong> (pre-Fiber and still foundational):</p><ul><li><strong>Two elements of different types</strong> → Replace the entire subtree.</li><li><strong>Elements of the same type</strong> → Update changed attributes and recurse on children.</li><li><strong>Lists</strong> → Use key prop for stable identity (avoids full re-renders on reorder/insert/delete).</li></ul><p><strong>Key Algorithm Steps</strong>:-</p><ol><li>Root comparison.</li><li>If types match → diff props/attributes.</li><li>Recurse on children (with list key optimization).</li><li>Generate mutation instructions (insert, delete, update, move).</li></ol><p><strong>Limitations of Simple Reconciliation</strong>:-</p><ul><li>O(n) children comparison can be wasteful for large/deep trees.</li><li>No prioritization — everything blocks the main thread.</li></ul><h4>Fiber Architecture( React’s Game Changer) :-</h4><p>Introduced in React 16, <strong>Fiber</strong> is a complete rewrite of the reconciliation engine. It makes React <strong>incremental, prioritizable, and interruptible</strong>.</p><p><strong>Key Innovations in Fiber</strong>:-</p><ul><li><strong>Fibers as Units of Work</strong>: Each Fiber represents a unit of rendering work (component, DOM node, etc.). It’s a data structure holding state, props, effects, and pointers to child/sibling/return fibers.</li><li><strong>Double Buffering</strong>: Current tree (committed) vs. Work-in-Progress (WIP) tree.</li><li><strong>Scheduler</strong>: Cooperative multitasking — breaks rendering into small chunks that yield to the browser for input/events.</li><li><strong>Priority Levels</strong>: Lane-based prioritization (user interactions &gt; transitions &gt; background work).</li><li><strong>Concurrent Features</strong>: Time Slicing, Suspense, Transitions (startTransition).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rqwEWsA4VtCC4cDsh7nQpQ.png" /><figcaption>Fiber flow of working</figcaption></figure><p><strong>How Reconciliation Works in Fiber</strong>:-</p><ul><li><strong>Render Phase</strong> (asynchronous, interruptible): Build the WIP tree by diffing.</li><li><strong>Commit Phase</strong> (synchronous): Apply changes atomically to the real DOM.</li></ul><p>This enables <strong>Concurrent Mode</strong> features like:-</p><ul><li>Non-blocking UI updates.</li><li>Better perceived performance (high-priority work first).</li></ul><h4>Diffing in Depth (Fiber’s Reconciliation):-</h4><ul><li><strong>Single-Child Optimization</strong>: Fast path for simple trees.</li><li><strong>Key-Based List Reconciliation</strong>:</li><li>Map old keys to fibers.</li><li>Match new list items.</li><li>Handle insertions, deletions, moves efficiently.</li><li><strong>Bailout Optimization</strong>: React.memo, PureComponent, or shouldComponentUpdate skips entire subtrees.</li><li><strong>Lazy &amp; Suspense</strong>: Code-splitting and async boundaries integrated into the fiber tree.</li></ul><p><strong>Modern Enhancements (React 18+ / 2026)</strong>:-</p><ul><li><strong>Automatic Batching</strong>: More updates batched by default.</li><li><strong>React Compiler</strong> (experimental/official in recent versions): Optimizes re-renders automatically by analyzing dependencies.</li><li><strong>Offscreen API</strong>: For better tab visibility and prerendering.</li></ul><h4>Comparison with Modern Frameworks:-</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/522/1*4IZopdYwGeqyfGRv2li9jA.png" /><figcaption>Comparion of modern frameworks</figcaption></figure><p>React’s strength remains its balance of developer experience and scalable performance through Fiber.</p><h4>Performance Optimizations &amp; Best Practices:-</h4><ul><li>Use React.memo, useMemo, useCallback judiciously.</li><li>Proper key props in lists.</li><li>Avoid anonymous functions in render.</li><li>Code splitting with React.lazy + Suspense.</li><li>Profile with React DevTools Profiler.</li><li>Measure before optimizing (Premature optimization is the root of all evil).</li></ul><p><strong>Common Pitfalls</strong>:-</p><ul><li>Overusing useMemo (adds overhead).</li><li>Deep object mutations bypassing detection.</li><li>Blocking the main thread with heavy computations (move to Web Workers).</li></ul><h4>Under the Hood: A Simplified Reconciliation Walkthrough</h4><p>Consider updating a list:-</p><pre>// Before<br>&lt;ul&gt;<br>  &lt;li key=&quot;a&quot;&gt;A&lt;/li&gt;<br>  &lt;li key=&quot;b&quot;&gt;B&lt;/li&gt;<br>&lt;/ul&gt;<br><br>// After (insert C between)<br>&lt;ul&gt;<br>  &lt;li key=&quot;a&quot;&gt;A&lt;/li&gt;<br>  &lt;li key=&quot;c&quot;&gt;C&lt;/li&gt;<br>  &lt;li key=&quot;b&quot;&gt;B&lt;/li&gt;<br>&lt;/ul&gt;</pre><p>Fiber matches keys → plans minimal operations: insert “C” node.</p><p>The <strong>Virtual DOM</strong> provides a clean abstraction, while <strong>Fiber’s reconciliation</strong> delivers the performance magic through smart diffing, prioritization, and concurrency. React (and the broader ecosystem) continues evolving toward compiler-level optimizations and finer-grained reactivity.</p><p>Understanding these internals helps you write better, faster apps — and debug performance issues effectively.</p><p>Thanks for reading !!!!!!!!!!!!</p><ul><li><a href="https://medium.com/@spande6894/how-live-streaming-works-a-deep-dive-into-the-system-design-behind-it-acfb1f651475">How Live Streaming Works? :-A Deep Dive into the System Design Behind It</a></li><li><a href="https://medium.com/@spande6894/behind-the-swipe-reel-shorts-scrolling-and-engineering-magic-of-infinite-scroll-0ea5039b007e">Behind the Swipe (reel/shorts scrolling) and Engineering Magic of Infinite Scroll</a></li><li><a href="https://medium.com/@spande6894/how-offline-web-applications-work-exploring-client-side-interactivity-technologies-and-9e0e9cd7498e">How Offline Web Applications Work- Exploring Client-Side Interactivity, Technologies, and…</a></li><li><a href="https://medium.com/@spande6894/content-delivery-networks-cdns-deep-dive-how-they-make-the-internet-fast-4ab0931a7b5e">Content Delivery Networks (CDNs) Deep Dive: How They Make the Internet Fast</a></li><li><a href="https://medium.com/@spande6894/progressive-web-apps-pwas-in-depth-service-workers-manifests-offline-first-design-765db45753bc">Progressive Web Apps (PWAs) in Depth: Service Workers, Manifests &amp; Offline-First Design</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=be121fa0008d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Progressive Web Apps (PWAs) in Depth: Service Workers, Manifests & Offline-First Design]]></title>
            <link>https://medium.com/@spande6894/progressive-web-apps-pwas-in-depth-service-workers-manifests-offline-first-design-765db45753bc?source=rss-aea3d88bf956------2</link>
            <guid isPermaLink="false">https://medium.com/p/765db45753bc</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[progressive-web-app]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[web-app-development]]></category>
            <category><![CDATA[pwa]]></category>
            <dc:creator><![CDATA[Saurabh Rajesh Pande]]></dc:creator>
            <pubDate>Sun, 28 Jun 2026 17:26:56 GMT</pubDate>
            <atom:updated>2026-06-28T17:26:56.737Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ejzk0FSF2emzKos1CvzhTg.png" /></figure><p>If you want to know more about offline web applications working , then you should check out this article to get more understanding .</p><p><a href="https://medium.com/@spande6894/how-offline-web-applications-work-exploring-client-side-interactivity-technologies-and-9e0e9cd7498e">How Offline Web Applications Work- Exploring Client-Side Interactivity, Technologies, and…</a></p><p>Now let’s continue PWA part .</p><h4>Why PWAs Matter in 2026</h4><p>PWAs deliver: -</p><ul><li><strong>Native-like experiences</strong> without app store friction.</li><li><strong>Offline capability</strong> and instant loading.</li><li><strong>Push notifications</strong>, background sync, and home screen installation.</li><li><strong>Cross-platform reach</strong> with a single codebase.</li></ul><p>Companies like <strong>Twitter (now X)</strong>, <strong>Spotify</strong>, <strong>Starbucks</strong>, <strong>Pinterest</strong>, and many e-commerce giants use PWAs to boost engagement and reduce bounce rates dramatically.</p><h4>Core Building Blocks of a PWA:-</h4><p>A PWA requires three pillars:</p><ol><li><strong>HTTPS</strong> (secure context)</li><li><strong>Web App Manifest</strong> (JSON file for installability)</li><li><strong>Service Worker</strong> (JavaScript for offline, caching, background tasks)</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TjUnlVuEnU1rid33bOpWvw.png" /></figure><h4>Web App Manifest: Making Your App Installable :-</h4><p>The manifest.json tells the browser how your app should behave when installed.</p><p><strong>Example manifest.json</strong> (modern 2026 best practices):-</p><pre>{<br>  &quot;name&quot;: &quot;My Offline PWA&quot;,<br>  &quot;short_name&quot;: &quot;MyPWA&quot;,<br>  &quot;description&quot;: &quot;A powerful offline-first application&quot;,<br>  &quot;start_url&quot;: &quot;/?source=pwa&quot;,<br>  &quot;display&quot;: &quot;standalone&quot;,<br>  &quot;background_color&quot;: &quot;#ffffff&quot;,<br>  &quot;theme_color&quot;: &quot;#000000&quot;,<br>  &quot;orientation&quot;: &quot;portrait-primary&quot;,<br>  &quot;icons&quot;: [<br>    {<br>      &quot;src&quot;: &quot;/icons/icon-192x192.png&quot;,<br>      &quot;sizes&quot;: &quot;192x192&quot;,<br>      &quot;type&quot;: &quot;image/png&quot;,<br>      &quot;purpose&quot;: &quot;any maskable&quot;<br>    },<br>    {<br>      &quot;src&quot;: &quot;/icons/icon-512x512.png&quot;,<br>      &quot;sizes&quot;: &quot;512x512&quot;,<br>      &quot;type&quot;: &quot;image/png&quot;,<br>      &quot;purpose&quot;: &quot;any maskable&quot;<br>    }<br>  ],<br>  &quot;shortcuts&quot;: [<br>    {<br>      &quot;name&quot;: &quot;New Task&quot;,<br>      &quot;url&quot;: &quot;/new&quot;,<br>      &quot;icons&quot;: [{ &quot;src&quot;: &quot;/icons/new.png&quot;, &quot;sizes&quot;: &quot;96x96&quot; }]<br>    }<br>  ]<br>}</pre><h4><strong>Key Properties (2026 updates)</strong>:-</h4><ul><li>purpose: “maskable” for adaptive icons on Android/iOS.</li><li>Shortcuts for quick actions.</li><li>display_override for advanced modes.</li><li>File handling and protocol handlers for deeper OS integration.</li></ul><p>Link it in your HTML: <strong>&lt;link rel=”manifest” href=”/manifest.json”&gt;</strong></p><h4>Service Workers: The Engine of PWAs:-</h4><p>Service Workers are programmable proxies that sit between your app and the network.</p><p><strong>Lifecycle</strong>:</p><ol><li><strong>Register</strong> → 2. <strong>Install</strong> → 3. <strong>Activate</strong> → 4. <strong>Fetch</strong> / <strong>Sync</strong> / <strong>Push</strong></li></ol><p><strong>Basic Registration</strong>:-</p><pre>// In your main JS file<br>if (&#39;serviceWorker&#39; in navigator) {<br>  window.addEventListener(&#39;load&#39;, () =&gt; {<br>    navigator.serviceWorker.register(&#39;/sw.js&#39;)<br>      .then(reg =&gt; console.log(&#39;SW registered&#39;, reg))<br>      .catch(err =&gt; console.log(&#39;SW registration failed&#39;, err));<br>  });<br>}</pre><p>Core sw.js Example (Cache-First Strategy):-</p><pre>const CACHE_NAME = &#39;my-pwa-v1&#39;;<br>const urlsToCache = [<br>  &#39;/&#39;,<br>  &#39;/styles.css&#39;,<br>  &#39;/app.js&#39;,<br>  &#39;/offline.html&#39;,<br>  &#39;/icons/icon-192x192.png&#39;<br>];<br><br>self.addEventListener(&#39;install&#39;, event =&gt; {<br>  event.waitUntil(<br>    caches.open(CACHE_NAME)<br>      .then(cache =&gt; cache.addAll(urlsToCache))<br>  );<br>});<br><br>self.addEventListener(&#39;fetch&#39;, event =&gt; {<br>  event.respondWith(<br>    caches.match(event.request)<br>      .then(response =&gt; {<br>        // Return cached version or fetch from network<br>        return response || fetch(event.request)<br>          .then(networkResponse =&gt; {<br>            // Cache successful responses<br>            if (networkResponse &amp;&amp; networkResponse.status === 200) {<br>              const responseClone = networkResponse.clone();<br>              caches.open(CACHE_NAME).then(cache =&gt; {<br>                cache.put(event.request, responseClone);<br>              });<br>            }<br>            return networkResponse;<br>          });<br>      })<br>      .catch(() =&gt; {<br>        // Offline fallback<br>        return caches.match(&#39;/offline.html&#39;);<br>      })<br>  );<br>});</pre><h4>Modern Strategies (2026):-</h4><ul><li><strong>Stale-While-Revalidate</strong>: Serve cache immediately, update in background.</li><li><strong>Network-First</strong> for dynamic content.</li><li><strong>Cache-Only</strong> for static assets.</li><li><strong>Background Sync</strong>: Queue actions (e.g., form submissions) for when connectivity returns.</li><li><strong>Periodic Background Sync</strong> (with permission) for data refresh.</li></ul><h4>Offline-First Design Principles:-</h4><ul><li><strong>App Shell Model</strong>: Cache HTML skeleton + critical JS/CSS. Load dynamic content later.</li><li><strong>Graceful Degradation</strong>: Show meaningful offline UI (e.g., cached data + “You’re offline” banner).</li><li><strong>Sync When Online</strong>: Use BackgroundSync API.</li><li><strong>IndexedDB</strong> for structured offline data storage (better than localStorage for large/complex data).</li></ul><p><strong>Implementation Guide Snippet</strong> (Offline Data with IndexedDB + Sync):-</p><pre>// In main app<br>async function saveOffline(data) {<br>  await idbPromise.put(&#39;offlineQueue&#39;, data);<br>  if (&#39;serviceWorker&#39; in navigator &amp;&amp; &#39;SyncManager&#39; in window) {<br>    navigator.serviceWorker.ready.then(reg =&gt; {<br>      reg.sync.register(&#39;sync-offline-data&#39;);<br>    });<br>  }<br>}<br><br>// In sw.js<br>self.addEventListener(&#39;sync&#39;, event =&gt; {<br>  if (event.tag === &#39;sync-offline-data&#39;) {<br>    event.waitUntil(syncOfflineData());<br>  }<br>});</pre><h4>Modern Examples (2026):-</h4><ul><li><strong>Spotify PWA</strong>: Excellent offline playlists with seamless sync.</li><li><strong>Notion / Linear-style tools</strong>: Full productivity apps working offline.</li><li><strong>E-commerce PWAs</strong> (e.g., many Shopify stores): Cart persistence and checkout offline.</li><li><strong>News Apps</strong>: Cached articles + background updates.</li><li><strong>Games &amp; Interactive Tools</strong>: Using WebAssembly + Service Workers for complex offline experiences.</li></ul><p><strong>iOS &amp; Android Support</strong>: Near-parity in 2026, with improved installation prompts and background capabilities.</p><h4>Advanced Topics &amp; Best Practices:-</h4><ul><li><strong>Security</strong>: Service Workers run in secure contexts only. Be careful with caching sensitive data.</li><li><strong>Performance Auditing</strong>: Use Lighthouse (in Chrome DevTools) — aim for 90+ PWA score.</li><li><strong>Update Strategies</strong>: Handle Service Worker updates gracefully (skipWaiting + clients.claim).</li><li><strong>Analytics</strong>: Track install rates, offline usage, and engagement.</li><li><strong>Edge Cases</strong>: Large caches, storage quotas, iOS limitations (e.g., no push in some scenarios historically, improved now).</li></ul><p><strong>Common Pitfalls</strong>:-</p><ul><li>Over-caching dynamic content.</li><li>Ignoring update flows (users stuck on old versions).</li><li>Poor offline UX leading to frustration.</li></ul><h4>Step-by-Step Implementation Guide:-</h4><ul><li><strong>HTTPS</strong> — Mandatory.</li><li><strong>Create Manifest</strong> — Test with Lighthouse.</li><li><strong>Register Service Worker</strong> — Scope carefully.</li><li><strong>Implement Caching Strategy</strong> — Start cache-first for assets.</li><li><strong>Add Offline Fallbacks</strong> — Custom offline page + data.</li><li><strong>Enable Background Features</strong> — Sync, Push (with VAPID keys).</li><li><strong>Test Thoroughly</strong> — DevTools (Application tab), network throttling, Lighthouse.</li><li><strong>Monitor &amp; Iterate</strong> — Real-user metrics.</li></ul><p>Thanks for reading!</p><ul><li><a href="https://medium.com/@spande6894/how-live-streaming-works-a-deep-dive-into-the-system-design-behind-it-acfb1f651475">How Live Streaming Works? :-A Deep Dive into the System Design Behind It</a></li><li><a href="https://medium.com/@spande6894/behind-the-swipe-reel-shorts-scrolling-and-engineering-magic-of-infinite-scroll-0ea5039b007e">Behind the Swipe (reel/shorts scrolling) and Engineering Magic of Infinite Scroll</a></li><li><a href="https://medium.com/@spande6894/content-delivery-networks-cdns-deep-dive-how-they-make-the-internet-fast-4ab0931a7b5e">Content Delivery Networks (CDNs) Deep Dive: How They Make the Internet Fast</a></li><li><a href="https://medium.com/@spande6894/live-streaming-at-scale-challenges-optimizations-failure-cases-ed175a69a1f2">Live Streaming at Scale: Challenges, Optimizations &amp; Failure Cases</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=765db45753bc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Live Streaming at Scale: Challenges, Optimizations & Failure Cases]]></title>
            <link>https://medium.com/@spande6894/live-streaming-at-scale-challenges-optimizations-failure-cases-ed175a69a1f2?source=rss-aea3d88bf956------2</link>
            <guid isPermaLink="false">https://medium.com/p/ed175a69a1f2</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[high-level-design]]></category>
            <category><![CDATA[architecture]]></category>
            <category><![CDATA[live-streaming]]></category>
            <category><![CDATA[youtube]]></category>
            <dc:creator><![CDATA[Saurabh Rajesh Pande]]></dc:creator>
            <pubDate>Sat, 20 Jun 2026 19:01:07 GMT</pubDate>
            <atom:updated>2026-06-20T19:01:07.098Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HwysD9kNH_Cr0Z5R9Sjd4g.png" /></figure><p>Live streaming at scale is one of the hardest problems in systems engineering. Platforms like <strong>Twitch</strong>, <strong>YouTube Live</strong>, and <strong>Netflix Live</strong> handle millions of concurrent viewers, ultra-low latency requirements, unpredictable spikes, and massive bandwidth costs — all while maintaining smooth playback.</p><p>This deep dive builds directly on your top-performing post, focusing on production-grade challenges and battle-tested solutions.</p><p>Before we dive in if you want to know more about Live streaming working you can check this .</p><p><a href="https://medium.com/@spande6894/how-live-streaming-works-a-deep-dive-into-the-system-design-behind-it-acfb1f651475">How Live Streaming Works? :-A Deep Dive into the System Design Behind It</a></p><p>Now let’s continue</p><h4>High-Level Architecture for Live Streaming at Scale -</h4><figure><img alt="High-Level Architecture for Live Streaming at Scale" src="https://cdn-images-1.medium.com/max/1024/1*bhpOlCJ9wtouhMKJC-SyPQ.png" /><figcaption>High-Level Architecture for Live Streaming at Scale</figcaption></figure><h4><strong>Key Differences from VOD -</strong></h4><ul><li>No pre-processing time — everything is real-time.</li><li>Higher emphasis on latency (target: 2–10 seconds end-to-end).</li><li>Dynamic scaling for sudden spikes (e.g., viral moments or sports events).</li></ul><h4>Ingestion Layer -</h4><p>Broadcasters push streams using protocols like:</p><ul><li><strong>RTMP</strong> (classic, reliable but higher latency)</li><li><strong>SRT</strong> (Secure Reliable Transport — better for lossy networks)</li><li><strong>WebRTC</strong> (ultra-low latency for interactive use cases)</li></ul><p><strong>Challenges</strong>:-</p><ul><li>Handling millions of inbound streams (Twitch has thousands of concurrent broadcasters).</li><li>Jitter, packet loss, and unstable upstream connections.</li></ul><p><strong>Optimizations</strong>:-</p><ul><li>Geographically distributed ingest PoPs (closest to broadcaster).</li><li>Twitch’s <strong>Intelligest </strong>system: Intelligent routing to optimal origin data centers based on capacity and network health.</li><li>Redundant ingest points with automatic failover.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HXXXMM_2Y4US0g2RH-F9yA.png" /></figure><h4>Transcoding &amp; Packaging Pipeline -</h4><p>Raw streams must be converted into multiple quality variants in real time.</p><p><strong>Key Steps</strong>:-</p><ul><li>Decode → Scale resolutions → Re-encode (H.264, H.265, AV1) at different bitrates.</li><li>Segment into short chunks (2–6 seconds for standard HLS; sub-second for low-latency).</li><li>Generate manifests (.m3u8 / .mpd).</li></ul><p><strong>Challenges</strong>:-</p><ul><li>Compute-intensive (especially 4K or multi-bitrate).</li><li>Maintaining synchronization across variants.</li></ul><p><strong>Optimizations</strong>:-</p><ul><li><strong>Per-scene / Per-title encoding</strong> adapted for live.</li><li>GPU/ASIC acceleration.</li><li><strong>Simulcast</strong> (multiple independent encodes) or layered encoding (SVC).</li><li>Edge transcoding in some advanced setups (Twitch/YouTube push some processing closer to edge).</li></ul><h4>Adaptive Bitrate Streaming (HLS/DASH) for Live -</h4><p>Same protocols as VOD, but with shorter segments for lower latency.</p><ul><li>Client ABR algorithms monitor bandwidth and switch qualities seamlessly.</li><li><strong>Low-Latency HLS (LL-HLS)</strong> and <strong>Low-Latency DASH</strong> reduce glass-to-glass delay significantly.</li></ul><p><strong>Latency Reduction Techniques</strong>:-</p><ul><li>Smaller segment sizes (down to 1–2 seconds).</li><li>Chunked transfer encoding (deliver partial segments).</li><li><strong>HTTP/3 + QUIC</strong> for faster connections and better loss recovery.</li><li>Predictive prefetching of next segments.</li></ul><p>Typical end-to-end latency:-</p><ul><li>Standard HLS: 10–30s</li><li>Optimized LL-HLS: 3–8s</li><li>WebRTC: &lt;1–2s (best for interactivity)</li></ul><h4>Multi-CDN Distribution (Critical for Scale) -</h4><p>Single CDN is a single point of failure at massive scale.</p><p><strong>Multi-CDN Strategy</strong>:</p><ul><li>Active-Active or Primary + Failover.</li><li>DNS-based steering (weighted, geo, performance-based).</li><li>Client-side manifest manipulation or Content Steering (HLS).</li><li><a href="https://developer.mozilla.org/en-US/docs/Glossary/Real_User_Monitoring">Real-user monitoring (RUM)</a> + third-party orchestration (e.g., <strong>NS1, </strong><a href="https://github.com/citrix/cedexis.github.com"><strong>Cedexis</strong></a>-like systems).</li></ul><p><strong>Benefits</strong>:</p><ul><li>Best performance per region/user.</li><li>Resilience against outages.</li><li>Cost arbitrage (route to cheaper/better-performing provider dynamically).</li></ul><figure><img alt="Netflix Live Origin and Twitch’s private backbone + partner CDNs exemplify hybrid multi-CDN approaches." src="https://cdn-images-1.medium.com/max/1024/1*dJgshmua1wpDrJ7qy3eovQ.png" /><figcaption><strong>Netflix Live Origin</strong> and Twitch’s private backbone + partner CDNs exemplify hybrid multi-CDN approaches.</figcaption></figure><h4>Latency Reduction Deep Dive -</h4><ul><li><strong>Geographic distribution</strong> of ingest, transcode, and edge.</li><li><strong>Origin Shield</strong> / hierarchical caching to protect core infrastructure.</li><li>Protocol optimizations (QUIC, HTTP/3).</li><li><strong>Edge computing</strong> for dynamic manifest generation and personalization.</li><li>Trade-off: Lower latency often means less buffering → higher rebuffering risk during network fluctuations.</li></ul><h4>Error Handling &amp; Fault Tolerance -</h4><p><strong>Common Failure Cases</strong>: -</p><ul><li>Broadcaster disconnects → Graceful fallback or auto-reconnect.</li><li>Transcoder failure → Redundant transcoding pipelines with hot standby.</li><li>CDN outage → Instant traffic shift via multi-CDN steering.</li><li>Thundering herd on origin during failover (cold cache problem).</li><li>Regional network congestion or DDoS.</li></ul><p><strong>Best Practices</strong>: -</p><ul><li><strong>Circuit breakers</strong> and health checks at every layer.</li><li>Redundant everything (multiple ingest points, multi-region transcoding).</li><li><strong>Stale-while-revalidate</strong> for manifests.</li><li>Detailed observability: Real-time dashboards for latency, error rates, buffer health, <a href="https://en.wikipedia.org/wiki/Quality_of_experience"><strong>QoE metrics</strong></a>.</li><li>Chaos engineering (Netflix-style) to test failure scenarios.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tWQqh1hCtAVgM5nkpHjN1g.png" /></figure><h4>Cost Optimization -</h4><p>Live streaming bandwidth is extremely expensive.</p><p><strong>Strategies</strong>:-</p><ul><li><strong>Multi-CDN arbitrage</strong> — route to lowest-cost provider per region/performance.</li><li>Efficient codecs (AV1 saves significant bandwidth).</li><li>Proactive caching / pre-positioning where possible.</li><li>Tiered storage and compute (spot instances for non-critical transcoding).</li><li>Origin offload via edge computing and shielding.</li><li>Analytics-driven decisions: Turn off high-bitrate variants in low-engagement regions.</li><li>Twitch and YouTube use private global networks + ISP partnerships to reduce public internet costs.</li></ul><p><a href="https://openconnect.netflix.com/en/"><strong>Netflix Open Connect</strong></a> model (appliances in ISP networks) is the gold standard for video delivery efficiency.</p><h4>Monitoring, Observability &amp; Scaling -</h4><ul><li>Real-time metrics: Bitrate switches, rebuffering ratio, startup latency, error rates.</li><li>Tools: Prometheus + Grafana, custom QoE scoring, client-side beacons.</li><li>Auto-scaling of transcoding fleets (Kubernetes + custom autoscalers based on concurrent streams).</li><li>A/B testing of ABR algorithms, segment durations, and routing policies.</li></ul><h4>Real-World Failure Cases &amp; Lessons -</h4><ul><li><strong>Major sports events</strong> cause flash crowds — multi-CDN + predictive scaling saves the day.</li><li>CDN-wide outages → Successful platforms recover in minutes via failover.</li><li>Encoder desync → Leads to playback artifacts; solved by frame-accurate synchronization.</li><li>Cost spikes → Optimized multi-CDN and codec choices prevent bill shock.</li></ul><p>Thanks for reading! If you are interested in this series you need to see these also —</p><ul><li><a href="https://medium.com/@spande6894/content-delivery-networks-cdns-deep-dive-how-they-make-the-internet-fast-4ab0931a7b5e">Content Delivery Networks (CDNs) Deep Dive: How They Make the Internet Fast</a></li><li><a href="https://medium.com/@spande6894/the-architecture-behind-tiktok-instagram-reels-recommendation-engine-dc932f33600c">The Architecture Behind TikTok/Instagram Reels Recommendation Engine</a></li><li><a href="https://medium.com/@spande6894/how-video-on-demand-vod-platforms-work-system-design-of-netflix-youtube-aa2ac663c1d3">How Video-on-Demand (VOD) Platforms Work: System Design of Netflix/YouTube</a></li><li><a href="https://medium.com/@spande6894/behind-the-swipe-reel-shorts-scrolling-and-engineering-magic-of-infinite-scroll-0ea5039b007e">Behind the Swipe (reel/shorts scrolling) and Engineering Magic of Infinite Scroll</a></li><li><a href="https://medium.com/@spande6894/how-offline-web-applications-work-exploring-client-side-interactivity-technologies-and-9e0e9cd7498e">How Offline Web Applications Work- Exploring Client-Side Interactivity, Technologies, and…</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ed175a69a1f2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Content Delivery Networks (CDNs) Deep Dive: How They Make the Internet Fast]]></title>
            <link>https://medium.com/@spande6894/content-delivery-networks-cdns-deep-dive-how-they-make-the-internet-fast-4ab0931a7b5e?source=rss-aea3d88bf956------2</link>
            <guid isPermaLink="false">https://medium.com/p/4ab0931a7b5e</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[internet]]></category>
            <category><![CDATA[high-level-design]]></category>
            <category><![CDATA[cdn]]></category>
            <category><![CDATA[low-level-design]]></category>
            <dc:creator><![CDATA[Saurabh Rajesh Pande]]></dc:creator>
            <pubDate>Fri, 19 Jun 2026 18:42:00 GMT</pubDate>
            <atom:updated>2026-06-19T18:42:00.740Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1COHzgWi9Ta3FlJ-Xzpg1g.png" /></figure><h4>What is a CDN and Why Do We Need It?</h4><p>A <strong>Content Delivery Network (CDN)</strong> is a geographically distributed network of proxy servers and data centers designed to deliver internet content (web pages, images, videos, APIs, etc.) with high availability and performance.</p><p><strong>Core Problems It Solves</strong>:-</p><ul><li><strong>Latency</strong>: Data traveling long distances (e.g., from a US server to India) suffers from speed-of-light delays + hops.</li><li><strong>Bandwidth Costs &amp; Congestion</strong>: Origin servers get overwhelmed.</li><li><strong>Global Scale</strong>: Handling millions of concurrent users.</li><li><strong>Reliability &amp; Security</strong>: Protection against failures and attacks.</li></ul><p><strong>Key Benefits</strong>:-</p><ul><li>Reduced latency (often 50–80% improvement)</li><li>Lower origin server load (cache hit rates &gt;90% for static content)</li><li>Higher availability and DDoS resilience</li><li>Cost savings on bandwidth</li></ul><h4>High-Level CDN Architecture</h4><figure><img alt="High level CDN architecture" src="https://cdn-images-1.medium.com/max/1024/1*deZqsxMKh0z2d3ZPruxgqg.png" /></figure><p><strong>Key Components</strong>:</p><ul><li><strong>Points of Presence (PoPs)</strong>: Hundreds to thousands of edge locations worldwide.</li><li><strong>Edge Servers</strong>: Cache and serve content close to users.</li><li><strong>Origin Server</strong>: Your main server or cloud storage (S3, GCS, etc.).</li><li><strong>Anycast Routing</strong>: Routes users to the nearest/topologically best PoP via BGP.</li><li><strong>Origin Shield</strong>: Intermediate caching layer protecting the true origin.</li></ul><h4>How CDNs Work: Request Flow</h4><ol><li>User requests content (e.g., <a href="https://example.com/image.jpg)."><strong>https://example.com/image.jpg</strong>).</a></li><li>DNS resolves to CDN’s anycast IP → routes to nearest edge.</li><li>Edge checks cache (based on cache key: URL + headers + query params).</li><li><strong>Cache Hit</strong>: Serve instantly.</li><li><strong>Cache Miss</strong>: Fetch from origin (or shield), cache it, then serve.</li><li>Response headers (Cache-Control, Expires, ETag) dictate future behavior.</li></ol><figure><img alt="CDN Request Flow" src="https://cdn-images-1.medium.com/max/1024/1*DO_GZzvUoYoh1Swq2gN9Vw.png" /></figure><h4>Edge Computing in CDNs</h4><p>Modern CDNs go beyond simple caching with <strong>Edge Computing</strong> — running code at the edge for dynamic logic.</p><p><strong>Examples</strong>:-</p><ul><li><a href="https://www.cloudflare.com/products/workers/">Cloudflare Workers,</a> Fastly <strong>Compute@Edge</strong>, <a href="https://aws.amazon.com/lambda/edge/">AWS <strong>Lambda@Edge</strong></a>.</li><li>Use cases: A/B testing, personalization, image optimization (resize, WebP conversion), authentication, API routing, server-side rendering.</li></ul><p><strong>Advantages</strong>:-</p><ul><li>Ultra-low latency computation (runs before/after cache).</li><li>Reduces origin round-trips dramatically.</li><li>Enables “edge-first” architectures.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iwiB2mqDbWfuj6UBHpJvtg.png" /></figure><h4>Caching Strategies (The Heart of CDNs)</h4><p><strong>Core Caching Mechanisms</strong>:-</p><ul><li><strong>Pull (On-Demand)</strong>: Edge fetches on miss (most common).</li><li><strong>Push</strong>: Pre-populate popular content (used by Netflix Open Connect).</li></ul><p><strong>Cache Key Construction</strong>:-</p><ul><li>Usually: Host + Path + Query String + Selected Headers (e.g., Accept-Language, Cookie subsets).</li><li>Normalization (ignore irrelevant query params).</li></ul><p><strong>Advanced Strategies</strong>:-</p><ul><li><strong>Tiered Caching</strong>: Multiple layers (edge → regional shield → origin).</li><li><strong>Stale-While-Revalidate</strong>: Serve stale content while refreshing in background.</li><li><strong>Cache-Control Directives</strong>: public, private, no-cache, max-age, s-maxage, stale-while-revalidate.</li><li><strong>ETag &amp; If-None-Match</strong>: Efficient revalidation.</li><li><strong>Eviction Policies</strong>: LRU, LFU, size-based, TTL priority.</li></ul><p><strong>Hit Rate Optimization</strong>:-</p><ul><li>Aggressive caching for static assets (JS/CSS/images).</li><li>Versioned URLs/fingerprints for cache busting.</li><li>Predictive prefetching for popular content.</li></ul><h4>Purging &amp; Cache Invalidation</h4><p>Cache invalidation is notoriously hard (“two hard problems in CS: cache invalidation…”).</p><p><strong>Common Methods</strong>:</p><ul><li><strong>TTL-Based (Time-to-Live)</strong>: Automatic expiration (e.g., 1 hour for images, 5 min for API responses).</li><li><strong>URL/Path Purge</strong>: Explicit removal via API/dashboard (e.g., /images/*).</li><li><strong>Tag/Surrogate-Key Purge</strong>: Group content with tags (Cloudflare, Akamai, Fastly support this).</li><li><strong>Versioned Assets</strong>: Change filename on update (app.v2.js) — no purge needed.</li><li><strong>Soft Purge</strong>: Mark as stale but continue serving while revalidating.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A59kwI46Ba2IEdnXgW1GvQ.png" /></figure><p><strong>Best Practices</strong>:-</p><ul><li>Combine TTL + selective purging.</li><li>Use cache tags for related content.</li><li>Add jitter to TTLs to prevent thundering herd.</li><li>Monitor cache hit/miss ratios and purge effectiveness.</li></ul><h4>Security Features: DDoS Protection &amp; More</h4><p>CDNs are excellent DDoS mitigators due to their scale.</p><p><strong>How CDNs Stop DDoS</strong>:-</p><ul><li><strong>Traffic Absorption</strong>: Massive global capacity (Cloudflare: 500+ Tbps) spreads attack volume.</li><li><strong>Global Distribution</strong>: No single point of failure.</li><li><strong>Scrubbing Centers</strong>: Filter malicious traffic at edge (rate limiting, signature-based detection, behavioral analysis).</li><li><strong>Anycast + Anycast Scrubbing</strong>: Routes attack traffic away from origin.</li><li><strong>Web Application Firewall (WAF)</strong>: Blocks SQLi, XSS, OWASP Top 10 at edge.</li><li><strong>Bot Management</strong>: CAPTCHA, JS challenges, behavioral detection.</li><li><strong>Origin Protection</strong>: Hide real origin IP (via proxy or Argo Tunnel).</li></ul><p><strong>Netflix Open Connect Specifics</strong>:-</p><ul><li>Appliances placed deep in ISP networks.</li><li>Proactive pushing of content.</li><li>Extremely efficient for large video files.</li></ul><p><strong>Comparison Table</strong>:</p><figure><img alt="Comparison table" src="https://cdn-images-1.medium.com/max/661/1*Ceuos009BsxUHMHsOn1ijw.png" /></figure><h4>Advanced Topics &amp; Optimizations</h4><ul><li><strong>Multi-CDN Strategy</strong>: Use multiple providers for resilience (e.g., primary + failover).</li><li><strong>Video-Specific Optimizations</strong>: Adaptive bitrate manifests, chunked delivery, QUIC/HTTP/3.</li><li><strong>Observability</strong>: Real-time analytics on cache hits, latency, errors (prometheus + Grafana integrations).</li><li><strong>Sustainability</strong>: Newer codecs (AV1) + efficient routing reduce energy use.</li><li><strong>Challenges</strong>: Cache stampedes, cold starts, consistency for dynamic content, regulatory compliance (GDPR data locality).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QeBsY0vlcv_OqFW0YHIk7w.png" /></figure><h4>Real-World Impact &amp; Case Studies</h4><ul><li><strong>Netflix</strong>: Open Connect delivers petabytes daily with minimal latency by embedding appliances in ISPs.</li><li><strong>Cloudflare</strong>: Powers millions of sites with free tier + advanced security.</li><li><strong>E-commerce</strong>: Black Friday traffic handled seamlessly via edge caching + autoscaling.</li><li><strong>Gaming</strong>: Fast patch delivery and low-latency asset loading.</li></ul><p><strong>Metrics to Track</strong>:-</p><ul><li>Cache Hit Ratio (target &gt;85–95%)</li><li>Time to First Byte (TTFB)</li><li>Error rates &amp; availability</li><li>Bandwidth savings</li></ul><p>Thanks you reading! If you love to read like these types of articles/blogs here are mine previous blogs you can see also</p><ul><li><a href="https://medium.com/@spande6894/how-video-on-demand-vod-platforms-work-system-design-of-netflix-youtube-aa2ac663c1d3">How Video-on-Demand (VOD) Platforms Work: System Design of Netflix/YouTube</a></li><li><a href="https://medium.com/@spande6894/the-architecture-behind-tiktok-instagram-reels-recommendation-engine-dc932f33600c">The Architecture Behind TikTok/Instagram Reels Recommendation Engine</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4ab0931a7b5e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>