<?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 Adarsh Tyagi on Medium]]></title>
        <description><![CDATA[Stories by Adarsh Tyagi on Medium]]></description>
        <link>https://medium.com/@adarshtyagi?source=rss-75c5e32da7ef------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*WL-lwPtT8FQFeMx3iJ0EwA.jpeg</url>
            <title>Stories by Adarsh Tyagi on Medium</title>
            <link>https://medium.com/@adarshtyagi?source=rss-75c5e32da7ef------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 20:45:29 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@adarshtyagi/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[Proximity Search for System Design Interviews]]></title>
            <link>https://medium.com/@adarshtyagi/proximity-search-for-system-design-interviews-b73416bcb9d9?source=rss-75c5e32da7ef------2</link>
            <guid isPermaLink="false">https://medium.com/p/b73416bcb9d9</guid>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[uber]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[proximity-searches]]></category>
            <category><![CDATA[maps]]></category>
            <dc:creator><![CDATA[Adarsh Tyagi]]></dc:creator>
            <pubDate>Tue, 03 Nov 2026 17:09:47 GMT</pubDate>
            <atom:updated>2026-11-03T17:17:45.399Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JjVKFVrM4YL7HVaXAlGs8A.png" /></figure><p>Open Uber and you see cars near you within a second. Open Zomato and you get a list of restaurants that deliver to your street. Behind both is the same question:</p><blockquote><em>“Given where I am, what is near me?”</em></blockquote><p>This is proximity search. It comes up a lot in system design interviews: Uber, Zomato, Swiggy, Blinkit, Yelp, Tinder, “Nearby Friends”. You don’t have to be a geometry expert to do well. You need one mental model, a few indexing techniques, and a clear sense of when to use each.</p><h3>The One Idea to Remember</h3><p>Every proximity system follows the same three steps:</p><pre>Bucket  →  Filter  →  Rank</pre><ol><li><strong>Bucket</strong>: Use a spatial index to quickly grab <em>possible</em> nearby objects (candidates).</li><li><strong>Filter</strong>: Calculate the exact distance and throw away the ones that are too far.</li><li><strong>Rank</strong>: Sort what’s left by ETA, rating, price, or other business rules.</li></ol><p><strong>Analogy</strong>: You lost your keys at home. You don’t search the whole city. You search your house (bucket), then check each room carefully (filter), then start with the room where you usually leave them (rank).</p><h4>Why not just compute distance to everything?</h4><p>Say Bengaluru has 1 million active drivers. Computing the distance to all of them on every request costs O(n). With thousands of requests per second, that won&#39;t scale.</p><p>So we divide the map into cells and only look at the cells near the user:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e5Joc6TrR4LEOan1_c0IHw.png" /></figure><p>That means checking about 105 drivers instead of 1,000,000. The rest of this guide covers different ways to draw these cells.</p><h3>Indexing Techniques (Finding Candidates)</h3><h4>Fixed Grid: graph paper over the city</h4><p>Split the map into equal squares. Each square holds a list of the objects inside it.</p><pre>cell_B2 → {driver7, driver18, driver91}</pre><p><strong>Search</strong>: Find the user’s cell, then read that cell and its 8 neighbours.</p><p><strong>Why neighbours?</strong> Two drivers can be 10 meters apart but sit on opposite sides of a cell boundary:</p><pre>+---------------+---------------+<br>|            D1 | D2            |<br>+---------------+---------------+</pre><p>If you search only the user’s cell, you miss D2. Always search the neighbouring cells.</p><p>Cell size trade-off:</p><ul><li>Big cells: fewer lookups, but many useless candidates.</li><li>Small cells: precise, but many lookups.</li></ul><p><strong>The weakness:</strong> Every cell is the same size. A cell over Connaught Place might have 5,000 drivers while a cell over a farm has zero. The grid can’t adapt to density.</p><blockquote><em>💡 Remember: </em>Grid = graph paper. Simple, but not adaptive.</blockquote><h4>GeoHash: a ZIP code for every spot on Earth</h4><p>GeoHash turns a (latitude, longitude) pair into a short string like ttnfv2.</p><p><strong>Analogy:</strong> Think of an address that gets more specific as you read it:</p><pre>India → Delhi → South Delhi → Hauz Khas → Street 5<br>t   →  tt   →    ttn      →   ttnf    → ttnfv2</pre><p>Each extra character zooms into a smaller rectangle. Nearby places usually share a prefix.</p><p><strong>How it works ? :</strong> Keep splitting the world in half, alternating between longitude and latitude, and write down 0 or 1 for which half the point falls in. Interleave those bits and encode them as Base32. You don’t need to go further than that.</p><p><strong>Precision cheat sheet:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ukdD9xaC5FLfK5ryiG2bEA.png" /></figure><p>Storage (e.g., in Redis):</p><pre>geohash:ttnfv2  → {driver1, driver9, driver44}<br>driver:driver1  → {lat, lng, status, updatedAt}</pre><p>When a driver moves: Recompute the GeoHash. If it changed, remove the driver from the old cell and add them to the new one.</p><p>⚠️ <strong>The classic trap:</strong> Nearby points don’t always share a prefix. Two points on either side of a cell edge can have completely different hashes. As with the grid, you have to search the user’s cell plus its 8 neighbours.</p><p><strong>Why to like it ? :</strong> It’s a plain string, so it works with any database that supports prefix or range queries, it’s easy to cache, and it’s easy to shard. Redis even has built-in GEOADD / GEOSEARCH, which use GeoHash under the hood.</p><blockquote><em>💡 Remember: </em>Same prefix usually means close. Different prefix does NOT mean far.</blockquote><h4>Quadtree: crowded areas split into four</h4><p>A quadtree starts with the whole map as one box. When a box holds too many objects (say, more than 100), it splits into four (NW, NE, SW, SE). Busy areas keep splitting; empty areas stay as large boxes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hd8DEnoXMxIy3_pP98DuvQ.png" /></figure><p><strong>Analogy:</strong> Think of a map book. A village gets one page. A busy market gets ten detailed pages. The quadtree hands out pages based on how crowded an area is.</p><p><strong>Search:</strong> Start at the root. Skip any box that doesn’t overlap your search area, along with everything inside it. Go deeper only into boxes that overlap.</p><p><strong>Best for:</strong> Mostly static data with uneven density, like restaurants, shops, and points of interest (Yelp, Zomato, Blinkit). The tree is usually built in memory and rebuilt periodically.</p><p><strong>Weakness:</strong> Fast-moving objects such as drivers force constant delete-and-reinsert, and that churn gets expensive.</p><blockquote><em>💡 Remember: </em>Quad = four. Crowded box breaks into four.</blockquote><h4>R-tree: rectangles inside rectangles</h4><p>Grids, GeoHash, and quadtrees divide the map. An R-tree takes the opposite approach and groups the data. Nearby objects are wrapped in a small bounding rectangle, those rectangles are wrapped in bigger ones, and so on.</p><p><strong>Analogy:</strong> Packing for a move. Small items go into small boxes, small boxes into big boxes. To find your charger, you skip every box labelled “Kitchen.”</p><p><strong>Its key strength:</strong> It can index shapes, not just points. That includes delivery zones, city boundaries, and roads, so it can answer questions like:</p><ul><li>“Which delivery zones contain this customer?” (point-in-polygon)</li><li>“Which restaurants are within 5 km?”</li></ul><blockquote><em>💡 Remember: </em>R-tree = Rectangles. Pick it when your data is shapes or lives in a database.</blockquote><h4>S2: Google’s way of mapping a round Earth</h4><p>Grids and GeoHash treat the Earth as flat, which causes distortion near the poles and odd edge cases at the date line. S2, from Google, models the Earth as a sphere.</p><p><strong>How it works ? :</strong> Put the Earth inside a cube, project the cube’s 6 faces onto the sphere, and keep splitting each face into 4 smaller cells. Each cell gets a 64-bit ID, ordered along a Hilbert curve so that nearby cells usually get nearby IDs. Nearby areas then become simple numeric range scans in a database.</p><p>Its superpower is region covering. S2 can approximate any circle or polygon with a mix of large and small cells. That makes it ideal for oddly shaped delivery zones or geofences.</p><p><strong>Used by:</strong> Google Maps, and historically Uber and Tinder.</p><blockquote><em>💡 Remember: </em>S2 = Sphere split using a cube. Best for shapes and global scale.</blockquote><h4>H3: Uber’s hexagons</h4><p>H3, from Uber, divides the Earth into hexagons.</p><p><strong>Why hexagons?</strong> A square’s neighbours sit at two different distances: side neighbours are close, diagonal ones are farther. A hexagon’s 6 neighbours are all the same distance from its centre. That makes “expand outward in rings” clean and uniform.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J9QvUpYDB0tAaMPYrV-XTw.png" /></figure><p><strong>Search:</strong></p><pre>riderCell      = latLngToCell(lat, lng, resolution)<br>candidateCells = gridDisk(riderCell, k)   // centre + k rings</pre><p><strong>Not enough drivers?</strong> Increase k and search the next ring.</p><p><strong>Hierarchy:</strong> Every cell has a parent and children, so you can switch zoom levels easily:</p><pre>Resolution 6 → city-wide demand<br>Resolution 8 → neighbourhood demand (surge pricing)<br>Resolution 9 → nearby-driver lookup</pre><p><strong>Best for:</strong> Ride-hailing, delivery fleets, supply/demand heatmaps, and surge pricing.</p><blockquote><em>💡 Remember: </em>H3 = Hexagons, Hierarchy, Heatmaps.</blockquote><h3>Filtering and Ranking (Getting the Right Answer)</h3><h4>Haversine: the honest distance</h4><p>Spatial cells are approximate. A cell can contain objects outside your search radius. Haversine computes the true straight-line distance between two points on a curved Earth.</p><p><strong>Why not plain Euclidean distance (</strong><strong>√(x² + y²))?</strong> Latitude and longitude are angles on a sphere, not points on flat paper. One degree of longitude covers about 111 km at the equator and about 0 km at the poles.</p><pre>GeoHash returns 100 drivers → Haversine → 27 within 3 km</pre><p><strong>Rule:</strong> Run Haversine on candidates only, never on all million objects.</p><blockquote><em>💡 Remember: </em>Box first, circle second.<em> The index gives you a rough box, and Haversine trims it to the real circle.</em></blockquote><h4>Top-K: keep only the winners</h4><p>You have 500 nearby drivers but need to show 10. A full sort costs O(n log n). A heap of size K costs O(n log k) and keeps only the best ones.</p><p>The bigger benefit is that ETA calls are expensive. Shortlist to the top 20 by Haversine, then call the routing service only for those 20.</p><blockquote><em>💡 Remember: </em>Keep the winners, ignore the full ranking.</blockquote><h4>Road Routing (Dijkstra / A*): nearest isn’t fastest</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*keTJfwhuCXJq1GV1ASYFVw.png" /></figure><p>The driver is 500 m away in a straight line but 6 km by road. Spatial indexes know nothing about roads.</p><ul><li>Dijkstra finds the shortest path in a road graph (intersections are nodes, roads are edges, travel time is the edge weight). It’s accurate but spreads out in every direction.</li><li>A* is Dijkstra plus a hint: It prioritises roads heading toward the destination, so it explores far fewer nodes.</li></ul><blockquote><em>💡 Remember: </em>Haversine = as the bird flies. A* = as the car drives.</blockquote><h3>Which One When ?</h3><p>Static vs moving data, the biggest decision driver:</p><ol><li>Restaurants (rarely move) → Quadtree, R-tree, PostGIS</li><li>Drivers (update every ~4s) → GeoHash / H3 buckets in Redis</li></ol><h3>How to Approach Any Proximity Problem</h3><p>Use this 5-step framework for Uber, Zomato, Nearby Friends, Tinder, or anything similar.</p><h4>Step 1: Ask the two questions that matter most</h4><ul><li>Do the objects move? (drivers and friends do; restaurants don’t)</li><li>What’s the read/write ratio? (Uber is write-heavy from location pings; Yelp is read-heavy)</li></ul><h4>Step 2: Do quick math</h4><ul><li>Uber: 1M drivers sending a ping every 4s is about 250K writes/sec. You need an in-memory store like Redis, not a SQL database.</li><li>Yelp: 200M businesses that rarely change. An in-memory quadtree is fine.</li></ul><h4>Step 3: Pick the index based on Step 1</h4><ul><li>Moving: GeoHash/H3 cells in Redis, sharded by cell or region.</li><li>Static: Quadtree, or PostGIS with read replicas and caching.</li></ul><h4>Step 4: Draw the query pipeline</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wtMLZrv8jTEeddR7piaSqg.png" /></figure><h4>Step 5: Handle the edge cases (this is where you stand out)</h4><ul><li>Boundaries: always search neighbouring cells.</li><li>Stale data: store updatedAt and ignore drivers who haven&#39;t pinged in 30s, or use a Redis TTL.</li><li>Hot spots: airports and stadiums overload a single cell, so split hot cells or use finer resolution there.</li><li>Too few results: expand the radius (GeoHash prefix shorter, H3 k larger).</li></ul><h3>Quick Summary</h3><p>Draw a Grid over the city. Give every spot a GeoHash address. When an area gets crowded, split it with a Quadtree. Pack shapes into R-tree rectangles. For the whole round Earth, use S2. For moving cars and heatmaps, use H3. Check the real distance with Haversine, keep the Top-K, and let A* work out the road.</p><p><em>If this helped, give it a clap and share it with someone.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b73416bcb9d9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ZooKeeper For System Design]]></title>
            <link>https://medium.com/@adarshtyagi/zookeeper-for-system-design-b9717a7b04cc?source=rss-75c5e32da7ef------2</link>
            <guid isPermaLink="false">https://medium.com/p/b9717a7b04cc</guid>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[zookeeper]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <dc:creator><![CDATA[Adarsh Tyagi]]></dc:creator>
            <pubDate>Fri, 30 Oct 2026 19:43:57 GMT</pubDate>
            <atom:updated>2026-10-30T19:52:56.930Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/921/0*UiOPQbDha-PkC0sO" /></figure><p>Picture a big office with no manager. Fifty employees need to decide who approves expenses, who is on leave today, and which version of the company policy is current. If everyone just shouts their opinion, you get chaos. Two people approve the same expense, someone follows an old policy, and nobody notices when a colleague quietly goes home.</p><p>Distributed systems have this problem all the time. Many machines need to agree on things like:</p><ul><li>Who is the leader right now?</li><li>Which servers are alive?</li><li>Who holds the lock on this resource?</li><li>What is the latest configuration?</li></ul><p>Getting these answers right is hard. Machines crash, networks slow down, and messages arrive late.</p><p>Apache ZooKeeper handles this. Think of it as the office’s shared noticeboard, run by a strict committee. Everyone reads from it and everyone trusts it, and changes only go up when the committee agrees.</p><blockquote><strong><em>One-line definition: </em></strong>ZooKeeper<em> is a distributed coordination service. It stores small pieces of shared information and helps machines agree on who does what.</em></blockquote><p>It is not a database, cache, or message queue. It stores <em>who owns the data</em>, not the data itself.</p><p><strong>Before starting the ZooKeeper Guide, here are few points:</strong></p><p>Your app server only talks to ZooKeeper to coordinate with the other servers. That means things like checking who the leader is, reading a config value, taking a lock, or registering “I’m alive.”</p><p>ZooKeeper is a separate set of machines (usually 3 or 5) running the Apache ZooKeeper software, a Java program you download and run. You don’t write the server code. You only install and configure it, the same way you would run MySQL or Redis.</p><pre>┌────────────  Your Application ────────────┐      ┌──── ZooKeeper Ensemble   ────┐<br>│  App Server 1   App Server 2   App Server 3 │ ◄──► │  ZK-1   ZK-2   ZK-3        │<br>│  (your code + ZooKeeper client library)   │      │  (Apache ZooKeeper software) │<br>└───────────────────────────────────────────┘      └─────────────────────────────┘</pre><p>When we will say “Candidate”, it means <strong>candidate is one instance of your application</strong> that wants to become the leader, meaning one of your own app servers or processes.</p><h3>The Architecture: A Committee With a Chairperson</h3><p>A ZooKeeper cluster is called an ensemble, usually made up of 3 or 5 servers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qGuYiJDZuFeQeQ_p_xDQVA.png" /></figure><p>Every server keeps a full copy of the data in memory.</p><ul><li><strong>Leader</strong>: orders and coordinates every write. <em>Analogy: the chairperson who calls the votes.</em></li><li><strong>Follower</strong>: serves reads and votes on writes. <em>Analogy: voting committee members.</em></li><li><strong>Observer</strong>: serves reads but does not vote. <em>Analogy: a reporter with a copy of the minutes.</em></li><li><strong>Client</strong>: your application, connected to one server. <em>Analogy: an employee reading the noticeboard.</em></li></ul><p>Observers add read capacity without slowing down writes, because they don’t vote. That makes them useful for scaling reads or for serving another region.</p><h3>Quorum: Why Majority Rules</h3><p>ZooKeeper only makes a decision when a majority (a <em>quorum</em>) of voting servers agrees.</p><pre>quorum = (N / 2) + 1     (rounded down)<br>Servers | Quorum | Failures tolerated<br>3    |   2    |   1<br>4    |   3    |   1<br>5    |   3    |   2<br>7    |   4    |   3</pre><p><strong><em>Why odd numbers?</em></strong> Look at 3 and 4: both survive only one failure. The fourth server costs money and adds no safety.</p><h4>How majority prevents split brain</h4><p>Imagine a network cable is cut and your 5-node cluster splits into a group of 3 and a group of 2.</p><ul><li>The group of 3 still has a majority, so it keeps working.</li><li>The group of 2 has no majority, so it stops accepting writes.</li></ul><p>Two majorities always overlap by at least one member, so two groups can never both believe they’re in charge. It works like a parliament: two separate groups can’t each hold more than half the seats.</p><p>Production rule of thumb: use 3 nodes for normal workloads and 5 if you need to survive 2 failures. Spread them across availability zones.</p><h3>The Data Model: A Tiny File System</h3><p>ZooKeeper stores data as a tree, like folders on your laptop. Each node is called a znode.</p><pre>/<br>├── config<br>│   └── payment-service<br>├── services<br>│   └── payment-service<br>│       ├── instance-1<br>│       └── instance-2<br>├── election<br>│   ├── candidate-0000000007<br>│   └── candidate-0000000008<br>└── locks<br>└── invoice-123</pre><p>Unlike a normal folder, a znode can hold both a small piece of data and child znodes. Keep the data tiny. ZooKeeper has a size limit (1 MB by default), but real usage is usually a few bytes to a few KB.</p><h4>The four znode types</h4><p>1. <strong>Persistent</strong>: stays until someone deletes it. <em>Analogy: a sign painted on the wall.</em> Used for config and metadata.</p><p>2. <strong>Ephemeral</strong>: deleted automatically when its owner’s session ends. <em>Analogy: a “Meeting in progress” sign that falls off when you leave the room.</em> Used for live servers and lock ownership.</p><p>3. <strong>Sequential</strong>: ZooKeeper appends a counter that always increases (for example -0000000007). <em>Analogy: a token from a deli counter queue.</em> Used for ordering and fairness.</p><p>4. <strong>Ephemeral + Sequential</strong>: both of the above. <em>Analogy: your deli token that is torn up if you leave the shop.</em> Used for locks and leader election.</p><h3>The API: Deliberately Small</h3><pre>create   delete   exists   getData   setData   getChildren   sync   multi</pre><p>There are only a few operations, and you build everything else from them, the way you build anything from LEGO bricks.</p><h3>Sessions: The Heartbeat That Ties It All Together</h3><p>When a client connects, it gets a session. The client keeps sending heartbeats to show it’s still alive.</p><p>Here’s an analogy. A session is like a hotel room key card with an expiry timer. As long as you keep checking in at the front desk, the card stays active. If you stop checking in, the card expires and housekeeping clears out your room, which here means your ephemeral znodes.</p><h4>Disconnected vs. Expired</h4><p>Disconnected: the network blipped, but the session <em>may</em> still be alive. Ephemeral nodes are still there. Your app should pause risky work and not assume it still holds the lock.</p><p>Reconnected: you got back before the timeout. Ephemeral nodes are still there. Resume.</p><p>Expired: the server stopped hearing from you for too long. Ephemeral nodes are deleted. Start a new session and rejoin from scratch.</p><p>The tricky part is that the server decides when your session expires, not you. A disconnected client might only find out it expired <em>after</em> it reconnects.</p><p><strong>Choosing a timeout</strong></p><p>Short timeout → fast failure detection, but more false alarms. Long timeout → fewer false alarms, but slower recovery</p><h3>Watches: The Doorbell, Not the Package</h3><p>A watch asks ZooKeeper to <em>“tell me when this changes.”</em></p><pre>getData(&quot;/config/payment&quot;, watch=true)</pre><p><strong>Analogy</strong>: a watch is a doorbell. It tells you someone came by. It doesn’t tell you what they delivered. You still have to open the door and look.</p><p><strong><em>Key rules:</em></strong></p><ol><li>Classic watches fire once. After they fire, you must register a new watch.</li><li>Changes can be merged. If 3 updates happen quickly, you might get only one notification. A watch is not an event log.</li><li>Always re-read after a notification.</li></ol><pre>Notification → Read current state → Act → Set a new watch</pre><h4>The herd effect</h4><p>Suppose 10,000 clients all watch the same znode. When it changes, all 10,000 wake up and hit ZooKeeper at once.</p><p><strong>Analogy</strong>: one fire alarm sends the whole building rushing to the same staircase.</p><p><strong>The fix:</strong> each client watches only the node directly before it in line. That way only one client wakes up at a time. You’ll see this pattern again in locks and elections.</p><h3>How a Write Works</h3><pre>Client ──write──► Follower ──forward──► Leader<br>                                          │<br>                   assigns zxid (transaction ID), sends proposal<br>                                          │<br>                         ┌────────────────┴───────────────┐<br>                  Follower ACK                     Follower ACK<br>                         └────────────────┬───────────────┘<br>                                  Majority reached<br>                                          │<br>                                 Leader sends COMMIT<br>                                          │<br>                                Client receives success</pre><ol><li>A client sends a write to any server.</li><li>That server forwards it to the leader.</li><li>The leader stamps it with a zxid, a transaction ID that always increases.</li><li>Followers save it to disk and acknowledge it.</li><li>Once a majority acknowledges, the leader commits it.</li><li>The client gets a success response.</li></ol><h4>ZAB (ZooKeeper Atomic Broadcast)</h4><p>The protocol behind this is called ZAB.</p><ul><li>One leader at a time.</li><li>A total order of all writes, using the zxid.</li><li>Safe recovery when the leader dies. A new leader is elected from the servers with the most up-to-date history, and it syncs followers before accepting new writes.</li></ul><p>The zxid has two parts, (epoch, counter). The epoch increases with every new leader, the way term numbers increase for each new president, so writes from an old leader can&#39;t be confused with new ones.</p><h3>Consistency</h3><h4>Writes are linearizable ✅</h4><p>All writes happen in one global order, and every server applies them in that same order.</p><h4>Reads can be stale ⚠️</h4><p>Reads are served locally by whichever server you’re connected to. That makes them fast, but that server might be slightly behind the others.</p><p>Analogy: writes are announced from the main stage. Reads come from the person next to you, who may not have heard the latest announcement yet.</p><h4>What ZooKeeper does guarantee</h4><ul><li>Your own view never goes backward. If you switch servers, you won’t see older data than you’ve already seen.</li><li>Your writes are applied in the order you sent them.</li><li>Updates are atomic. They either fully succeed or fully fail.</li><li>Committed writes are never lost or rolled back.</li></ul><h4>Need a fresh read?</h4><p>Call sync() before reading. It makes your server catch up with the leader first.</p><h3>Leader Election</h3><p><strong>Problem</strong>: exactly one scheduler must run, with automatic failover if it dies.</p><p><strong>Steps</strong>:</p><ol><li>Each candidate creates an ephemeral sequential node: /election/candidate-0000000007</li><li>It lists all children and sorts them.</li><li>The smallest number becomes the leader.</li><li>Everyone else watches only the node directly before theirs.</li><li>When that node disappears, the candidate checks again whether it’s now the smallest.</li></ol><pre>candidate-07  ← LEADER<br>candidate-08  ← watches 07<br>candidate-09  ← watches 08<br>candidate-10  ← watches 09</pre><p>If 07 crashes, its ephemeral node disappears, only 08 is notified, and 08 becomes the leader.</p><p><strong>Analogy</strong>: a line at a ticket counter. You only watch the person in front of you. When they leave, you step up. You don’t need to watch the whole line.</p><p>Why this design works:</p><ul><li>Ephemeral: a crashed leader cleans itself up automatically.</li><li>Sequential: clear, fair ordering.</li><li>Watch the predecessor: avoids the herd effect.</li></ul><h3>Distributed Locks</h3><p>Use a distributed lock when <strong>several servers could do the same work at the same time, and only one should. </strong>This uses the same algorithm as leader election, applied to a resource.</p><ol><li>Create /locks/invoice-123/lock-0000000021 (ephemeral sequential).</li><li>If yours is the smallest, you hold the lock.</li><li>If not, watch your predecessor and wait.</li><li>To release the lock, delete your node. If you crash, it gets deleted automatically.</li></ol><p><strong>Important</strong>: a watch notification does not mean you got the lock. It only means “go check again.”</p><h4>The hidden danger: zombie lock holders</h4><pre>1. Client A holds the lock.<br>2. A freezes for 60s (long GC pause).<br>3. A&#39;s session expires, so its lock node is deleted.<br>4. Client B gets the lock.<br>5. A wakes up, still thinks it holds the lock, and writes to the DB.<br>6. 💥 A and B both write. Data is corrupted.</pre><p>ZooKeeper did its job correctly. The problem is that your database has no idea A is stale.</p><h4>Fencing Tokens: The Fix for Zombies</h4><p>A fencing token is a number that only goes up and is handed out with each lock. The sequence number from ZooKeeper works perfectly.</p><pre>Client A gets token 21<br>Client B gets token 22</pre><p>Every write to the protected resource includes the token. The resource rejects any token lower than the highest one it has seen.</p><pre>if token &lt; highestSeen: reject<br>else: accept, highestSeen = token</pre><p>When zombie A shows up with token 21 after B has already written with 22, it gets rejected.</p><p><strong>Analogy</strong>: a hotel re-programs the door lock for each new guest. The previous guest’s old key card simply stops working.</p><h3>Service Discovery</h3><p>Each live instance registers itself with an ephemeral node:</p><pre>/services/payment-service/instance-1   → {&quot;host&quot;:&quot;10.0.1.14&quot;,&quot;port&quot;:8080}<br>/services/payment-service/instance-2   → {&quot;host&quot;:&quot;10.0.1.15&quot;,&quot;port&quot;:8080}</pre><p>Consumers call getChildren() with a watch. When an instance dies, its node disappears, the watch fires, and consumers refresh their list.</p><p><strong>Analogy</strong>: a staff sign-in board where names are wiped off automatically when someone leaves the building.</p><p>An active session only means the process can reach ZooKeeper, not that it’s healthy. A process can hold its session while its HTTP handler is broken. Combine this with real health checks.</p><h3>Failure Scenarios Cheat Sheet</h3><ul><li>One follower fails: nothing visible, as long as a majority is up. It catches up when it returns.</li><li>The leader fails: writes pause briefly, a new leader is elected, writes resume.</li><li>Majority lost: no writes accepted. ZooKeeper gives up availability to stay correct.</li><li>Client’s connection drops: the client reconnects to another server with the same session.</li><li>Client’s session expires: ephemeral nodes are deleted, locks and leadership are lost, the client must rejoin.</li><li>A write response is lost: the result is unknown, so reconcile before retrying.</li></ul><h3>Scaling: Reads Scale Out, Writes Don’t</h3><ul><li>Reads are local, so adding followers or observers increases read capacity.</li><li>Writes all go through one leader and need a majority, so adding voters makes writes slower, not faster.</li></ul><p>ZooKeeper is built for read-heavy, small-data coordination. Watch out for large znodes, huge child lists, too many watches, and slow disks for the transaction log.</p><h3>ZooKeeper and CAP</h3><p>During a network partition, the minority side stops accepting writes. That makes ZooKeeper a CP system: it favors consistency over availability.</p><h3>When to Use It, and When Not To</h3><p>✅ Use ZooKeeper for: leader election, distributed locks (with fencing), service discovery, cluster membership, small shared config, and failover metadata.</p><p>❌ Don’t use it as: a database, a cache, a message queue, an event log, a store for large files, or a replacement for health checks.</p><p><strong><em>“ZooKeeper gives reliable coordination, but it’s one more stateful cluster we have to operate.”</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b9717a7b04cc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Guide to Kafka and RabbitMQ]]></title>
            <link>https://medium.com/@adarshtyagi/a-guide-to-kafka-and-rabbitmq-9e116ebb937b?source=rss-75c5e32da7ef------2</link>
            <guid isPermaLink="false">https://medium.com/p/9e116ebb937b</guid>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[rabbitmq]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <dc:creator><![CDATA[Adarsh Tyagi]]></dc:creator>
            <pubDate>Sat, 17 Oct 2026 15:27:34 GMT</pubDate>
            <atom:updated>2026-10-17T15:29:56.434Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/850/0*Qb7fPZhihgMdkXfL.jpg" /></figure><p>I am sure we all have heard about Pub/Sub model while reading or designing distributed systems. Kafka and RabbitMQ are two most popular ones in this field. Let’s understand each one of these and also learn when to use which one.</p><h3>Why Messaging Systems Exist ?</h3><p>An order service that calls Payment, Inventory, Email, Analytics and Delivery synchronously has four problems:</p><ul><li>Slow requests, because latency is the sum of every downstream call.</li><li>Failure coupling: if Email is down, order creation fails.</li><li>The order service must know every consumer.</li><li>Traffic spikes hit every service at once.</li></ul><p>A broker in the middle fixes this: the producer publishes and moves on; consumers process independently. This is decoupling, and it gives you buffering, fan-out and failure isolation.</p><blockquote><strong><em>Analogy:</em></strong><em> a restaurant. The customer (producer) gives an order to the waiter, who pins it on the kitchen board (broker). The customer doesn’t walk into the kitchen or wait for a specific chef (consumer); any free chef picks it up.</em></blockquote><h4>Event vs command:</h4><ul><li><strong>Event</strong>: a fact that already happened (OrderCreated). Many consumers.</li><li><strong>Command</strong>: a request to do something (SendEmail). One logical handler.</li></ul><h4>Queue vs log, the single most important idea in this guide:</h4><ul><li><strong>Queue (RabbitMQ)</strong>: a message is removed once consumed and acknowledged.</li><li><strong>Log (Kafka)</strong>: an append-only history. Reading does not delete. Each reader keeps its own bookmark and can rewind.</li></ul><blockquote><strong><em>Analogy:</em></strong><em> a queue is a post office box: once you collect the letter, it’s gone. A log is a newspaper archive: everyone reads at their own pace, keeps their own bookmark, and can go back to old editions.</em></blockquote><h3>Kafka Essentials</h3><h4>Architecture</h4><pre>Producer → Topic &quot;orders&quot;<br>    ├─ Partition 0 [E0 E1 E2 ...]  → Consumer group A<br>    ├─ Partition 1 [E0 E1 ...]     → Consumer group B<br>    └─ Partition 2 [E0 E1 E2 ...]</pre><ul><li><strong>Topic</strong>: a named stream. Partition: an ordered, append-only log; the unit of parallelism and storage.</li><li><strong>Offset</strong>: a record’s position within one partition (meaningless across partitions).</li><li><strong>Key</strong>: hashed to pick the partition (hash(key) % partitions).</li></ul><blockquote><strong><em>Analogy:</em></strong><em> a highway. A topic is the highway, partitions are its lanes, and an offset is the position of a car in its lane. Cars stay in order </em>within<em> a lane, but there’s no order across lanes. The key is the rule “all cars for order-123 use lane 2,” so they never overtake each other.</em></blockquote><blockquote><strong><em>Ordering rule:</em></strong><em> Kafka guarantees order </em>only within a partition<em>. If events for one entity must stay ordered, use that entity’s ID (</em><em>orderId, </em><em>accountId) as the key.</em></blockquote><p><strong>Hot partitions:</strong> a skewed key (e.g. 80% of users in one country) overloads one partition. Fix with a higher-cardinality key, key + bucket salting, or isolating huge tenants.</p><h4>Consumer groups</h4><ul><li>Each partition goes to at most one consumer per group.</li><li>Max useful parallelism in a group = number of partitions. Extra consumers sit idle.</li><li>Different groups each get the full stream (pub/sub). Same group splits the work (queue-like).</li></ul><pre>orders (4 partitions)<br>    ├─ payment-service group:   3 consumers share the 4 partitions<br>    ├─ analytics group:         reads everything independently<br>    └─ fraud group:             reads everything independently</pre><blockquote><strong><em>Analogy:</em></strong><em> each team subscribes to the same newspaper (a group gets every edition). Inside one team, members split the sections between them (partitions). Six readers for four sections means two have nothing to read.</em></blockquote><h4>Durability: the “never lose it” config</h4><p>Each partition has a leader and followers. Producers write to the leader.</p><p>acks=0Fire and forget. Fastest, may lose data.</p><p>acks=1Leader wrote it. Lost if the leader dies before followers copy.</p><p>acks=allAll in-sync replicas (ISR) have it. Strongest.</p><blockquote><strong><em>Analogy:</em></strong><em> signing a contract. </em><em>acks=0 is mailing it and hoping. </em><em>acks=1 is the boss signing, with no copies made yet. </em><em>acks=all is the boss </em>and<em> the required witnesses (in-sync replicas) all signing before you call it done.</em></blockquote><h4>Delivery semantics</h4><p><strong>At-most-once:</strong> Commit offset, then processCrash = message lost</p><p><strong>At-least-once:</strong> Process, then commit offsetCrash = message reprocessed (duplicates)</p><p><strong>Exactly-once:</strong> Kafka transactionsOnly covers Kafka-to-Kafka</p><ul><li>Idempotent producer de-duplicates <em>producer retries</em> inside Kafka. It does not stop your app publishing the same business event twice.</li><li>Kafka transactions atomically write output records plus consumed offsets. They do <em>not</em> make an external DB, email or payment API exactly-once.</li></ul><blockquote><strong><em>Analogy:</em></strong><em> commit-then-process is </em>closing the book before reading the page<em>: a crash loses that page. Process-then-commit is </em>reading, then bookmarking<em>: a crash before the bookmark means you re-read the page. Re-reading is safer, as long as re-reading is harmless (idempotent).</em></blockquote><blockquote><em>Practical “exactly-once”: at-least-once delivery + idempotent consumers (unique </em><em>eventId, DB unique constraint).</em></blockquote><h4>Kafka Cluster Metadata and KRaft</h4><p>Modern Kafka uses KRaft, a Raft-based metadata quorum, to manage Brokers, Topics, Partitions, Replica assignments, Access-control metadata, Leader information.</p><p>Kafka 4.0 and later no longer support ZooKeeper (I will add new blog for ZooKeeper) mode. A production deployment commonly uses three or five dedicated controllers:</p><ul><li>Three controllers tolerate one controller failure.</li><li>Five controllers tolerate two.</li></ul><p>Brokers store topic data. Controllers manage cluster metadata.</p><h3>RabbitMQ Essentials</h3><h4>Message flow</h4><pre>Producer → Exchange → (bindings) → Queue → Consumer</pre><p>Producers publish to exchanges, never directly to queues. Exchanges route to queues using bindings and a routing key.</p><blockquote><strong><em>Analogy:</em></strong><em> a post office. The sender (producer) writes an address (routing key) on a parcel. The sorting center (exchange) applies its sorting rules (bindings) and drops the parcel into one or more delivery boxes (queues), where recipients (consumers) pick it up.</em></blockquote><p><strong>Also know:</strong> channels are lightweight and multiplexed over one TCP connection (don’t open a connection per message). A <strong>TCP connection</strong> is the actual network link between your app and RabbitMQ. Opening one is slow and costly (handshake, authentication, memory on the server). A <strong>channel</strong> is a lightweight virtual lane <em>inside</em> that one connection. Your app opens one connection and creates many channels on it to publish and consume in parallel.</p><blockquote><strong><em>Analogy:</em></strong><em> the connection is a phone line to the company, and channels are separate conversations happening on that line. You don’t install a new phone line for every sentence. You install one and talk over it as much as you need.</em></blockquote><p><strong>Rule:</strong> open a few long-lived connections at startup and reuse channels. Never open a new connection per message.</p><h4>Competing consumers</h4><p>Several workers on one queue means each message goes to exactly one worker. This is the classic task-queue pattern (image resize, emails, report generation). Add workers to scale.</p><blockquote><strong><em>Analogy:</em></strong><em> one order board, many chefs. Whoever is free takes the next ticket, and each ticket is cooked once.</em></blockquote><h4>Reliability: three layers</h4><ul><li><strong>Manual consumer ack:</strong> broker redelivers if the consumer dies before acking, so you get at-least-once and duplicates are possible. Auto-ack can lose messages.</li><li><strong>Publisher confirms:</strong> the broker tells the producer it took responsibility. Persistent flag alone is <em>not</em> a guarantee.</li><li><strong>nack:</strong> requeue=true returns it to the queue; requeue=false discards or dead-letters it.</li><li><strong>Poison message:</strong> a permanently bad message that loops forever. Prevent it with retry limits, delayed retries and a DLQ.</li></ul><h4>Queue types</h4><ul><li><strong>Classic:</strong> not replicated. Fine for transient or low-value work.</li><li><strong>Streams:</strong> append-only replicated log with retention and replay (a Kafka-like model inside RabbitMQ). Use for large backlogs, big fan-out and replay.</li></ul><h4>Ordering</h4><p>Queues are FIFO in theory, but multiple consumers, requeues and priorities break effective order. For strict order use Single Active Consumer, or partition by business key across several queues.</p><h3>Kafka vs RabbitMQ</h3><p><strong>Choose Kafka when</strong>: you need replay, several independent consumers of one history, very high throughput, stream processing or CDC.</p><p><strong>Choose RabbitMQ when</strong>: you need a work queue, per-message ack/reject, flexible routing, TTLs, priorities or request/reply, and messages are short-lived.</p><p>Use both only when roles are distinct, e.g. Kafka carries business events, and a planner turns them into RabbitMQ delivery tasks (email/SMS/push queues).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9e116ebb937b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Caching Patterns in System Design]]></title>
            <link>https://medium.com/@adarshtyagi/caching-patterns-in-system-design-995bfb8da292?source=rss-75c5e32da7ef------2</link>
            <guid isPermaLink="false">https://medium.com/p/995bfb8da292</guid>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[caching-strategies]]></category>
            <category><![CDATA[cache]]></category>
            <category><![CDATA[caching]]></category>
            <dc:creator><![CDATA[Adarsh Tyagi]]></dc:creator>
            <pubDate>Fri, 02 Oct 2026 18:51:20 GMT</pubDate>
            <atom:updated>2026-10-02T18:51:20.299Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/567/0*GzgIVFhQzGyfRHeC.png" /></figure><p>Caching is one of the most effective ways to improve the performance and scalability of a software system. It reduces response time, lowers database load and helps applications handle more traffic. In this article, we will discuss about caching patterns or cache strategies considering that we already know some basics of caching, cache hit/miss rate, cache eviction and invalidation.</p><h3>1. Cache-aside pattern</h3><p>Cache-aside, also called <strong>lazy loading</strong>, is the most commonly used caching pattern. The application communicates directly with both the cache and the database.</p><h4>Read flow</h4><pre>1. Application checks the cache.<br>2. If the value exists, return it.<br>3. If the value is missing, read it from the database.<br>4. Store the value in the cache.<br>5. Return the value.</pre><h4>Write flow</h4><pre>1. Update the database.<br>2. Delete the cached value.<br>3. Allow the next read to rebuild the cache.</pre><h4>When to use it ?</h4><p>Cache-aside is the best general-purpose default when reads greatly exceed writes and some temporary staleness is acceptable.</p><h3>2. Read-through caching</h3><p>In read-through caching, the application asks the cache for data. If the data is missing, the cache loads it from the database. The difference from cache-aside is responsibility:</p><ul><li>In cache-aside, the application loads missing data.</li><li>In read-through, the cache layer loads missing data.</li></ul><h4>Read flow</h4><pre>1. Application requests data from the cache.<br>2. Cache checks for the value.<br>3. On a hit, the cache returns the value.<br>4. On a miss, the cache loads it from the database.<br>5. Cache stores and returns the value.</pre><h3>3. Write-through caching</h3><p>In write-through caching, the application writes to the cache, and the cache synchronously writes the same data to the database. The write is considered successful only after the database update succeeds.</p><h4>Write flow</h4><pre>1. Application sends a write to the cache.<br>2. Cache updates the database.<br>3. Cache stores the updated value.<br>4. Success is returned to the application.</pre><h4>When to use it ?</h4><p>Data that must be immediately available after an update and systems where cache freshness is more important than write speed.</p><h3>4. Write-behind caching</h3><p>Write-behind caching is also called <strong>write-back caching</strong>. The application writes to the cache first. The database is updated asynchronously later.</p><h4>Write flow</h4><pre>1. Application writes to the cache.<br>2. Cache immediately confirms the write.<br>3. A background process collects pending changes.<br>4. Changes are eventually written to the database.</pre><h4>When to use it ?</h4><p>Systems where temporary data loss is acceptable.</p><h3>5. Write-around caching</h3><p>In write-around caching, writes go directly to the database and bypass the cache.</p><h4>Write flow</h4><pre>1. Application writes directly to the database.<br>2. Existing cached data is deleted or allowed to expire.<br>3. The next read loads the updated value into the cache.</pre><h3>6. Refresh-ahead caching</h3><p>Refresh-ahead caching updates popular cache entries shortly before they expire. Instead of waiting for a user request to discover that the value has expired, the system refreshes it proactively.</p><h4>When to use it ?</h4><p>For known high-traffic objects. Refresh-ahead should normally be limited to proven popular keys.</p><h3>Summary</h3><p>There is no single caching pattern that is best for every system. Cache-aside is usually the safest starting point. Write-through is useful when cached data must be immediately current. Write-behind provides faster writes but introduces durability risks. Write-around prevents write-heavy data from polluting the cache. Refresh-ahead help keep popular data available with predictable latency.</p><p>The most important caching question is not:</p><blockquote><em>Which caching technology should we use?</em></blockquote><p>It is:</p><blockquote><em>How does the data become stale, how will it be refreshed, and what happens when the entire cache disappears?</em></blockquote><p>A strong caching design explains performance, consistency, invalidation, failures and business correctness — not just where Redis/Memcache is placed in the architecture.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=995bfb8da292" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Authentication Really Works?]]></title>
            <link>https://medium.com/@adarshtyagi/how-authentication-really-works-4e393200e9f0?source=rss-75c5e32da7ef------2</link>
            <guid isPermaLink="false">https://medium.com/p/4e393200e9f0</guid>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[security]]></category>
            <dc:creator><![CDATA[Adarsh Tyagi]]></dc:creator>
            <pubDate>Sat, 05 Sep 2026 18:34:25 GMT</pubDate>
            <atom:updated>2026-09-05T18:34:25.794Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FIF-f3H48MA7RW__.png" /></figure><p>Almost every application has a Login button. You enter your email and password, click Login, and a second later you’re inside. It feels simple. But behind that button a backend is doing much more than that. Let’s understabd how authentication really works and how can we build production ready authentication system.</p><h3>Authentication vs Authorization</h3><p>Before talking about JWTs, OAuth, cookies, or sessions, we need to separate two concepts i.e. Authentication and Authorization. Authentication answers “who are you?” and authorization answers “what you are allowed to do?”. The backend system needs a trustworthy mechanism for proving identity. The simplest example is: <strong><em>Email + Password</em></strong></p><p>But this immediately creates another problem. How should we store the password? Suppose our database contains:</p><pre>id    email                 password<br>------------------------------------------<br>1     alice@example.com     hello123<br>2     bob@example.com       password456</pre><p>If an attacker steals this database, every user’s password becomes immediately available. Even worse, people frequently reuse passwords across multiple websites. A leaked password from your application might also compromise someone’s email, social media, or banking account. So passwords should not normally be stored directly. We store a <strong>password hash</strong>.</p><h3>What Is Password Hashing?</h3><p>A hashing function converts input into another value. The important property is that password hashing is designed to be <strong>one-way</strong>. We can calculate: <em>password → hash</em></p><p>but we should not practically be able to calculate: hash → password</p><p>For password storage, common algorithms include: argon2id, bcrypt, scrypt etc.</p><h3>If Hashing Is One-Way, How Does Login Work?</h3><p>This initially sounds contradictory. If the server can’t recover the password, how can it determine whether the password entered during login is correct?</p><p>The answer is: The server doesn’t recover the original password. It hashes the candidate password again and compares the results.</p><p>There’s another problem. Suppose Alice and Bob both chooses the same password then both users would have the same stored hash. So we introduce a random <strong>salt</strong>. Each user can have different random salt value which makes the hashing of same passwords different. Modern password-hashing libraries such as bcrypt and Argon2 typically encode the salt and algorithm parameters into the stored password-hash representation, so application developers usually don’t manually manage a separate salt column in database.</p><h3>Login Worked. Now What?</h3><p>Suppose the user logs in successfully. They then make requests:</p><pre>GET /profile<br>GET /orders<br>POST /checkout<br>GET /notifications</pre><p>Should they send their password with every request? <strong>Absolutely not.</strong></p><p>Instead, after successful authentication, the server creates some form of authenticated session or credential. Two major approaches are: <strong>Session-based authentication</strong> and <strong>Token-based authentication.</strong></p><h3>Session-Based Authentication</h3><p>During login the server will validate the credentials and then create a session for that user and store the session at server side. Server might create a session_id for a user_id and then store it and sends back this session id to browser. The browser stores it and in future request the browser will send this session_id along with that request. The at the backend the server will look for this session at the session store and it knows who is this user.</p><p>A small application might initially keep sessions in backend memory. But imagine multiple backend servers. User logs into Server A. If the session exists only in Server A’s memory and the next request reaches Server B, Server B may know nothing about it. Production systems therefore commonly use shared session storage like Redis. Redis can store: <strong><em>session_id → user/session information</em></strong> and all backend instances can access it.</p><p>Every authenticated request may require access to the session store and this leads us to tokens.</p><h3>JWT Authentication</h3><p>JWT stands for: <strong>JSON Web Token. </strong>A JWT typically looks like: <strong><em>xxxxx.yyyyy.zzzzz</em></strong></p><p>It consists of: <strong><em>HEADER.PAYLOAD.SIGNATURE</em></strong></p><p>Conceptually,</p><p>Header:</p><pre>{<br>  &quot;alg&quot;: &quot;RS256&quot;,<br>  &quot;typ&quot;: &quot;JWT&quot;<br>}</pre><p>Payload:</p><pre>{<br>  &quot;sub&quot;: &quot;42&quot;,<br>  &quot;role&quot;: &quot;USER&quot;,<br>  &quot;exp&quot;: 1760000000<br>}</pre><p>And finally a cryptographic signature. The signature is created using the header and payload along with a secret key.</p><p>Signature:</p><pre>sign(<br>    header + payload,<br>    secret/private key<br>)</pre><p>The authentication server signs the token. An API can later verify that signature.</p><p>Now after getting this token in login step, the user will send this token in Authorization header of every request along with “<strong><em>Bearer</em></strong>” keyword. The API can often verify the token without looking up a traditional session for every request. That’s why JWT access tokens are often described as <strong>stateless</strong>.</p><p>This JWT token is Base64 decoded, so anyone can easily extract the data from this token and inspect the payload. The signature does not necessarily hide the contents. Instead, it protects <strong>integrity</strong>. If an attacker changes the role from “user” to “admin”, then the original signature no longer matches. The signature was generated with old payload and the secret key but since the payload is changed so the signature will not match the new payload. Hence, the server rejects the modified token. Therefore: Don’t put passwords, private keys, or other sensitive secrets inside ordinary JWT payloads.</p><h3>The Problem With Long-Lived JWTs</h3><p>Suppose we issue an access token valid for 30 days. An attacker steals it on Day 1. They could potentially impersonate the user for a long time. Instead, production systems often use two credentials: <strong><em>Access Token + Refresh Token</em></strong></p><p>Access token is our normal JWT token that consist the payload and signature and this should be short lived (10–15 minutes). The exact duration depends on the application’s security and usability requirements.</p><p>A refresh token exists to obtain new access tokens. When the access token expires:</p><pre>Client<br>   |<br>   | refresh token<br>   v<br>Auth Server<br>   |<br>   | validate<br>   v<br>New Access Token</pre><p>The refresh token lasts longer and therefore requires stronger protection.</p><p>The client needs access to the refresh credential in some form because it must present it when refreshing authentication. For browser applications, one common pattern is storing it in a:</p><pre>Secure<br>HttpOnly<br>SameSite<br>Cookie</pre><p>Example:</p><pre>Set-Cookie: refresh_token=XYZ;<br>HttpOnly;<br>Secure;<br>SameSite=Lax;</pre><p><strong>HttpOnly</strong>: Browser JavaScript cannot directly read the cookie. This helps protect it from token theft through many XSS attacks.</p><p><strong>Secure</strong>: The browser sends it only over HTTPS.</p><p><strong>SameSite</strong>: Controls when the browser sends the cookie in cross-site situations and is an important CSRF defense.</p><p>A useful production pattern is:</p><pre>Client → actual random refresh token</pre><pre>Server → hash of refresh token</pre><p>When refreshing:</p><pre>Client sends token<br>       ↓<br>Server hashes token<br>       ↓<br>Compare with stored hash</pre><p>The database does not need the raw token. This resembles password verification.</p><h3>Refresh Token Rotation</h3><p>Suppose the user initially receives: R1 and they use R1 to refresh. The server returns:</p><pre>Access Token A2<br>Refresh Token R2</pre><p>R1 becomes invalid. Next:</p><pre>R2 → A3 + R3</pre><p>So: R1 → R2 → R3 and this is called <strong>refresh token rotation</strong>. Now imagine an attacker stole R1. The legitimate user already exchanged it for R2. Attacker sends R1. The server sees: “This refresh token was already used”</p><p>That may indicate token theft. The system can revoke the session or entire token family and require authentication again. This is called <strong>refresh token reuse detection</strong>.</p><h3>Cookies vs LocalStorage</h3><p>A common question is: <em>Why not just put everything in localStorage?</em></p><p>Because JavaScript can access localStorage:</p><pre>localStorage.getItem(&quot;token&quot;)</pre><p>If an attacker successfully executes malicious JavaScript through an XSS (cross site scripting) vulnerability, they may steal the token. HttpOnly cookies cannot be read directly through JavaScript.</p><h3>What is XSS and CSRF ?</h3><p>XSS means: <strong>Cross-Site Scripting. </strong>Suppose an attacker manages to inject malicious JavaScript into your application. If authentication credentials are readable from JavaScript, malicious code may steal them. So we use HttpOnly cookies to protect from XSS attacks.</p><p>CSRF means: <strong>Cross-Site Request Forgery. </strong>Suppose you’re logged into “bank.com” and your browser has stored the session_id in cookies. Now you visit some malicious site let’s say “hack.com”. The malicious website tries to cause your browser to make a POST request using bank’s backend API. The browser may automatically attach bank.com’s cookies to requests going to bank.com. The bank sees a valid session cookie and might incorrectly assume that this user intentinally made this request. That is the core CSRF problem. We can protect aginst CSRF attacks by:</p><ul><li>Using <strong>CSRF tokens</strong> with every state-changing request (POST/PUT/DELETE).</li><li>Setting cookies with <strong>SameSite=Lax or </strong><strong>Strict</strong>, plus Secure and HttpOnly.</li><li>Validating <strong>Origin/</strong><strong>Referer headers</strong> for sensitive requests.</li></ul><h3>OAuth 2.0 and OpenID Connect</h3><p>OAuth 2.0 and OpenID Connect are often mentioned together. The easiest way to understand them is this:</p><blockquote>OAuth 2.0 → what can this app access ?</blockquote><blockquote>OpenID Connect → who is the user ?</blockquote><p>OAuth 2.0 is mainly an <strong>authorization framework</strong>. Imagine you install a photo-printing app and it asks:</p><blockquote><em>“Can I access your Google Photos?”</em></blockquote><p>You should not give that app your Google password. Instead, the app redirects you to Google. The important idea is that the application never needs your Google password. Google gives the app an <strong>access token</strong> instead. That token may allow only specific actions, such as: “Read Photos” but not “Read Gmail” or “Change Password”. Those permissions are usually controlled using <strong>scopes</strong>.</p><p>Now your application may also want to know: “who actually logged in ?”</p><p>That is what OpenID Connect solves. OIDC is an <strong>authentication layer built on top of OAuth 2.0</strong>.</p><p>When using OIDC, the identity provider may return an additional token called an ID Token. The ID token contains information about the authenticated user.</p><p>Access Token is used to call APIs.</p><p>Example:</p><pre>GET /calendar/events<br>Authorization: Bearer ACCESS_TOKEN</pre><p>It answers: “What is this client allowed to access?”</p><p>ID Token is used by the application to learn about the authenticated user.</p><p>It answers: “Who logged in?”</p><h3>Authorization Code Flow</h3><p>Instead of sending tokens directly through the browser URL, the identity provider sends a temporary authorization code.</p><pre>User<br>  |<br>  | Login with Google<br>  v<br>Google<br>  |<br>  | Authenticate user<br>  v<br>Authorization Code<br>  |<br>  v<br>Your Backend<br>  |<br>  | Exchange code<br>  v<br>Google<br>  |<br>  +---- Access Token<br>  +---- ID Token<br>  +---- Refresh Token (sometimes)</pre><p>The code is short-lived and is exchanged securely for tokens.</p><h3>Summary</h3><p>Production authentication isn’t about choosing JWT or sessions. It’s about building a chain of trust — from the user’s first credential all the way to every authenticated request — and protecting every link in that chain.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4e393200e9f0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Client to Server: Understanding Proxies, API Gateways and Load Balancers]]></title>
            <link>https://medium.com/@adarshtyagi/client-to-server-understanding-proxies-api-gateways-and-load-balancers-3acfcda51090?source=rss-75c5e32da7ef------2</link>
            <guid isPermaLink="false">https://medium.com/p/3acfcda51090</guid>
            <category><![CDATA[load-balancer]]></category>
            <category><![CDATA[api-gateway]]></category>
            <category><![CDATA[design-systems]]></category>
            <category><![CDATA[proxy-server]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <dc:creator><![CDATA[Adarsh Tyagi]]></dc:creator>
            <pubDate>Mon, 31 Aug 2026 15:07:14 GMT</pubDate>
            <atom:updated>2026-08-31T15:17:35.373Z</atom:updated>
            <content:encoded><![CDATA[<p>When you type: <a href="https://example.com/abc/1120">https://example.com/monkey/1120</a> and press enter, it looks like your browser simply sends a request to a server and gets a response. In a small application, that might be actually true. But production systems never works this way.</p><p>Modern applications have millions of users, hundreds of backend servers, multiple microservices, authentication requirements, rate limits, security policies and servers spread across multiple regions.</p><p>The actual request path might look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/318/1*-e1Y58_JTAnt4WLuKoVNWQ.png" /></figure><p>And somewhere on client’s side, there might even be a forward proxy. They sounds similar because they all sit between a client and servers and overlaps with each other little bit but they solve different problems. Let’s understand them one by one.</p><h3>What is Proxy ?</h3><p>Proxy or Forward Proxy is simply a middleman between a client and another server. Instead of your computer directly contacting a website, your computer sends the request to the proxy and then proxy makes the request on your behalf. Suppose you wants to access <a href="https://abc.com/">https://abc.com</a> then without proxy your request will directly reach to website’s server. But suppose in your company’s device there is a proxy so that request will go to abc.com via this proxy.</p><p>These are used for hiding or controlling client IP exposure, controllig employee internet access, blocking websites or enforcing organizational security policies. The key idea is that forward proxy represents the client or hides the client.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/193/1*OlRiPtyTTY0ryPksm5DcrQ.png" /></figure><h3>What is Reverse Proxy ?</h3><p>This is also a middleman but this time it sits on the server side. The client does not necessarily know which backend server handled the request. It simply talks to the <a href="https://example.com/">https://example.com</a>. The reverse proxy receives the request and forwards it internally.</p><p>Suppose your spring boot application runs on 10.0.1.25:8000 and you don’t want users accessing this . Instead user will hit <a href="https://api.example.com/">https://api.example.com</a> and that will call the nginx:443 and then nginx will forward this client’s request to spring boot server. So here user only knows about api.example.com. They don’t need to know where the application actually runs. A reverse proxy provides SSL/TLS termination, caching, request routing or security filtering. The key idea here is that reverse proxy hides the servers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/311/1*pQSqLOM38PxqXribg01u9A.png" /></figure><h3>What is an API Gateway ?</h3><p>Now imagin our application grows into microservices. We have different services like user service, order service, payment service etc. Without gateway, clients might need to know where every service lives and that quickly becomes diffcult to manage. Instead we introduce an API Gateway. The client now needs to know only <a href="https://gateway.com/">https://gateway.com</a> and this host determines which service should handle each request. For example request with /users/* path will go to user service and /payment/* will go to payment service. But routing is just a part of story.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*F-GqMyXJ5_zFEhZpDlu-2w.png" /></figure><p>This is where gateways and reverse proxies can feel confusing. Both can forward requests. But an API gateway is focused specifically on managing APIs. Before forwarding the request, API gateway might ask “Is JWT valid?”, “Is this user allowed?”, “is rate limit ok?”. So API gateway commonly handles the authentication, authorization, rate limiting, request validation, routing, logging, caching, and monitoring.</p><p>Basically think if reverse proxy as “where should this request go?” 😄, and API gateway as “who is calling? Are they allowed? have they exceeded their limit? Is the request valid? and then where should it go ?” 😫.</p><p>It performs reverse proxy behaviour with API management capabilities.</p><h3>What is Load Balancer ?</h3><p>Suppose your application becomes popular. Initially you had one server and everything works but then traffic increases and one server can not handle everything. So you create multiple servers.</p><p>Now there is another problem. Which server should receive each request ? That is the job of load balancer. Instead of clients choosing servers, everyone connects to a load balancer and then it distributes the traffic.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/555/1*0K8SPurPfEd6xC7JQzv6uQ.png" /></figure><p>There is another major reason we use load balancers. What is a server dies ? The balancer also performs the health checks. This improves availability and reliability. Load balancer uses different algorithms to choose a server, for example round robin, least connections, traffic weight based routing.</p><h3>L4 vs L7 Load Balancers</h3><p>Load balancers can operate at different networking layers (OSI model) i.e. Layer 4 (Transport layer), and Layer 7 (Application layer). L4 load balancer operates mainly using networking information such as: source IP, destination IP, port and protocol. L4 load balancers are fast and useful when you need very high throughput, latency needs to be low and you do not care about the data of request (url and headers). Examples can be gaming servers, streaming systems, databases.</p><p>L7 load balancer understands the application protocol most commonly HTTP/HTTPS. It can inspects things such as URL, HTTP method, Host, headers, cookies and query parameters.</p><h4>Why don’t we always use L7?</h4><p>Because sometimes we don’t need application level intelligence. Imagine millions of TCP connections coming into a system. If we all need is “send this to a healthy server.” then parsing HTTP information is useless and provide no benefit. L4 keeps the job simple and makes the routing much faster than L7.</p><h4>Reverse Proxy vs Load Balancer</h4><p>A load balancer is often also acting as a reverse proxy. A client does not know about those backend servers. Therefore the load balancer is sitting in front of and representing them which is reverse proxy behavior.</p><h3>Mental Model</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/688/1*HU4UjdhXVeIfU6IcKm0Ziw.png" /></figure><p>When these concepts start sounding similar, ask one questions:</p><p>“What problem is this component primarily solving?”</p><h4>Forward Proxy</h4><blockquote>client → proxy → internet</blockquote><blockquote>Question it answers: “How should this client access the outside world?”</blockquote><blockquote>Represents the client</blockquote><h4>Reverse Proxy</h4><blockquote>internet → reverse proxy → backend</blockquote><blockquote>Question it answers: “How should external traffic reach my backend?”</blockquote><blockquote>Represents the servers</blockquote><h4>API Gateway</h4><blockquote>client → api gateway → APIs</blockquote><blockquote>Questions it answers: “Who can call my APIs, what policies apply, and which service should receive the request?”</blockquote><blockquote>Manages the APIs</blockquote><h4>Load Balancer</h4><blockquote>client → load balancer → server instances</blockquote><blockquote>Question it answers: “which healthy server should handle this traffic?”</blockquote><blockquote>Distributes traffic.</blockquote><h3>Summary</h3><p>Forward proxy protects and represents the client. Reverse proxy protects and represents backend servers. API gateway manages access to APIs. Load Balancer distributes traffic across servers. L4 balances network connections, while L7 understands application requests.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3acfcda51090" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Design Ad Click Aggregator]]></title>
            <link>https://medium.com/@adarshtyagi/design-ad-click-aggregator-0d0ee086f72a?source=rss-75c5e32da7ef------2</link>
            <guid isPermaLink="false">https://medium.com/p/0d0ee086f72a</guid>
            <category><![CDATA[ad-click-aggregator]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[design-systems]]></category>
            <dc:creator><![CDATA[Adarsh Tyagi]]></dc:creator>
            <pubDate>Sat, 20 Jun 2026 20:11:02 GMT</pubDate>
            <atom:updated>2026-06-20T20:11:02.604Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*ZF3_qo9R5IuGPUD-.jpg" /></figure><p>While using Instagram or Facebook, you’ve probably seen ads. Platforms like Google and Meta not only serve these ads but also need to track when users click on them to measure campaign performance and billing. How do they do that? That’s where an <strong>ad click aggregator service</strong> comes into play. It collects and consolidates click events from various sources, providing a unified view for analytics, reporting, and attribution. Let’s see how we can design this service.</p><h3>Requirements</h3><p>Functional requirements of the system can be</p><ol><li>User click on ad and should be redirected to the advertiser’s site.</li><li>Advertiser can query ad click metrics over time.</li></ol><p>Now, let’s list down the non-functional requirements</p><ol><li>System should be scalable to support large number of clicks per second.</li><li>Query should be of low latency for advertisers.</li><li>System should be fault tolerant and aggregated data should be correct.</li><li>Idempotency means multiple same click should be count as single click only.</li></ol><h3>Capacity Estimations</h3><p>Let’s assume we have 10 million active ads and assuming 10 times clicks per day.</p><p><strong><em>10*10 million = 100 million clicks per day = 10k clicks per second (approx.)</em></strong></p><h3>Entities and APIs</h3><p>For these types of systems we just have input and output entity. Input here will be clicks from users and output will be metrics data for advertisers. This system is not user facing so we do not have such list of APIs or detailed entities. But we can have one simple endpoint which will record the user’s click.</p><ol><li><strong><em>POST /click</em></strong> → Record the user’s ad click event.</li></ol><h3>High Level Design</h3><p>Let’s start with first functional requirements i.e. when user clicks on ads user should be redirected to advertiser’s site. We will assume that ads are already placed on our product page. We just needs to handle the redirection part. The solution for this can be like when user click on ad, will send the request to our server. Then our server can track the click and response with advertiser’s website via 302 redirect status.</p><p>Now how the advertisers can query the ad clicks metrics. Starting point can be like we record each ad click event in the database and then query that database only when advertiser wants to see the metrics. But this solution is not scalable for large systems and we are simple overloading our database. What if we already compute the aggregated data and then store it in another database so that we do not have to run the aggregation logic at query time. When user click, store the raw event in database and then in batches process raw events and aggregate them in separate database already optimized for queries. For this we will need write heavy database like Cassandra and use Apache spark for batch processing. So the process will be user clicks on ad, store the raw event in database and then periodically trigger the cron job that reads the click event and aggregate them and then store them in write optimised database. This is good but we are processing events in batches periodically which introduces delay in data pipeline and this is not almost realtime for our advertisers. They will be seeing couple of minutes of old data always. We can add Kafka here. Every event we can write here and then stream processor (spark streaming) will read the event and aggregate them in real time.</p><h3>Design Deep Dive</h3><h4>Scalability</h4><p>Now we need to design the system to handle 10k clicks per second. Clicks processor service can be scaled horizontally. Kafka is distributed and can handle large number of events. Stream processor can also be scaled horizontally by adding more tasks and jobs. Now for aggregated data we can use OLAP (Online Analytical Processing) like Snowflake or BigQuery and this can handle the scaling automatically.</p><h4>How to not lose any data ?</h4><p>We are already using Kafka stream to store the click event data and by default, these streams are distributed and fault tolerant. Kafka replicates the data across multiple brokers and availability zones. Also we can have retention period of 7 days by default. Also we have small aggregation window for data here and even if something goes down we will not lose much data (just couple of minutes) and this can also be retrieved back from our raw event database. Now we need to make sure that our aggregated data is correct because our billing depends on this. For this we can have periodic data reconciliation. We can run a periodic batch job that reads all the raw click events and re-aggregates them. Then we can compare the results of batch job to the results of stream processor.</p><h4>Idempotency</h4><p>We need a way to enforce ad click idempotency. If a user clicks on an ad multiple times, we only count it as one click. We can have unique ID with each ad instance shown to user. So every time an ad is rendered to a user, it gets new unique ID. Now this ID will act as idempotency key. When the user clicks on the ad, the browser sends the ID along with the click data. When a click comes in, we check if the ID exists in a cache. If it does, then it’s a duplicate and we ignore it. If it doesn’t, then we put the click in the stream and add ID to the cache.</p><h3>Architecture Diagram</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LYXliu85XI-K-_JmRpk6Gw.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0d0ee086f72a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Design BookMyShow]]></title>
            <link>https://medium.com/@adarshtyagi/design-bookmyshow-43edca5cb2c2?source=rss-75c5e32da7ef------2</link>
            <guid isPermaLink="false">https://medium.com/p/43edca5cb2c2</guid>
            <category><![CDATA[bookmyshow]]></category>
            <category><![CDATA[online-booking-system]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <dc:creator><![CDATA[Adarsh Tyagi]]></dc:creator>
            <pubDate>Sat, 18 Apr 2026 11:36:24 GMT</pubDate>
            <atom:updated>2026-04-18T11:36:24.444Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9L3bcDwhj9CET7M1.jpg" /></figure><p>Ticket booking platforms like BookMyShow handle millions of concurrent users rushing to grab seats the moment a blockbuster release goes live. Behind that seamless experience lies a carefully engineered system that balances high availability, low latency, and race-condition-free seat reservation at scale. In this blog, we’ll break down the architecture decisions that make such systems work under pressure.</p><h3>Requirements</h3><p>Starting with the functional requirements of the system</p><ol><li>User should be able to search for events/shows.</li><li>User should be able to view an event details like venue, date, artist etc.</li><li>User should be able to book the tickets for an event.</li></ol><p>Now, let’s list down the non-functional requirements</p><ol><li>System should be highly available for searching and viewing th events.</li><li>System should be highly consistent when it comes to ticket booking.</li><li>System should be scalable and have low latency specially for searching and viewing events details.</li></ol><h3>Capacity Estimations</h3><p>For such type of services we can assume approx. 10 million DAU. These services are read heavy as users browse the events more as compared to ticket booking. Let’s assume for 5 search or detail viewing request from each user daily</p><p><strong><em>total requests = 50 million/day = 600 requests/second (approx)</em></strong></p><p>Peak traffic comes during second half of the day and at that time this number can be upto 4–5 times more. So 2000–2500 requests/day is the number that our system should be able to handle.</p><h3>Entities and APIs</h3><p>Core entities in this system are <strong>User, Event, Booking, Ticket, Venue</strong> (physical location for an event).</p><p>APIs are the following</p><ol><li><strong><em>GET /events/&lt;event_id&gt;</em></strong> → To fetch the details for an event.</li><li><strong><em>GET /events/search/keyword={keyword}&amp;start={date}&amp;end={date}&amp;pageSize={page_size}&amp;page={page_number}</em></strong> → To fetch the events searched by user</li><li><strong><em>POST /booking/&lt;event_id&gt;</em></strong> → To book the user’s ticket for an event.</li></ol><h3>High Level Design</h3><p>Let’s start with completing our functional requirements one by one</p><h4>View Event</h4><p>User should be able to view the details of a specific event like name, date, artists, venue, seat mapping etc. We can simply have a event service behind the API gateway and load balancer which can fetch all these details from the database based on event id. In database, we can have tables for events, performaers, venue and when user will request for a specific event, the service will use these database tables to fetch the required details.</p><h4>Search Events</h4><p>We also need to allow the users to search for events based on keywords, venue, artists, date etc. We can have a search service which can recieve all the search queries from users and this service will be connected with the database and query it based on the filters recieved from user. This can be slow to search for results like this but we will optimize it later.</p><h4>Book Tickets</h4><p>The main challenge for this functionality if to avoid the two or more users trying to book the same seat in the same event. This requires the strong consistency, so we need a database with transactions. We can use database like PostgreSQL with new tables like bookings and tickets. Also we can create a new service like booking service to tackle this functionality and connect it with an external service for handling payments. Once this external service completes the payment transaction then it can notify back the original booking service. But this will come only after handling the booking consistency which we will see in deep dive section.</p><h3>Design Deep Dive</h3><h4>How to handle the booking consistency?</h4><p>In system like this we can see that there is a timer which tracks the time until you complete the purchase. This is a method to reserve the tickets for a user so that no other user can book the same ticket meanwhile you are completing your payment. But we need to make sure that the ticket is locked/reserved for the user while they are checking out and how can we do that? We need a system with temporary reservation that can expire automatically like if user not able to book the ticket in given time then the reserved seat should get available for others automatically.</p><p>We can implement a distributed lock with TTL (time to live) using Redis. Redis gives automatic key expiration and lock acquisition and release is also extremely fast (because of in-memory DB). When user selects a ticket, acquire a lock in redis with a defined TTL. If user completed the purchase then this ticket will be updated in database as booked and lock will get released from redis from our application code. If TTL expires then the redis will release the lock on its own. Key-value pair in redis will be ticket_id with user_id so that we can confirm that the user who booked the ticket is the same who reserved it. Also we need to show the updated seats status to other users when one user reserved the seat, so for that we can update the database with the status reserved when user selects the seat and timer starts and if booking completes then update the status to booked else to available considering the redis as our source of truth.</p><p>What if the TTL expires while transaction is going on? Simple answer is to extend the TTL once the transaction is initiated.</p><h4>How to optimize events searching?</h4><p>Querying the database for events based on filters can be slow and also a heavy load on database during peak hours. Obviosuly we can create indexes and optimize the sql query but still that won’t be enough. So we can use full text search engine like ElasticSearch. ElasticSearch can be a powerful tool here to optimize the search and handle heavy traffic. It is based on inverted index <a href="https://www.geeksforgeeks.org/machine-learning/understanding-tf-idf-term-frequency-inverse-document-frequency/">(TF-IDF)</a> which allows it to quickly locate and retrive the data by mapping unique words to documents or records stored. But for this we need to sync elasticsearch with our database carefully.</p><h4>How to handle millions of users simultaneously?</h4><p>We know that our system is read heavy so there will be peak hours where number of users searching or viewing event details will be in millions so to handle this we can simply follow the rule book and implement caching, loading balancing and horizontal scaling of servers. For popular events or common search terms, we can simply cache the results with TTL.</p><h3>Architecture Diagram</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/937/1*fO_au5DMDO6_TguHiwhsLg.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=43edca5cb2c2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Design YouTube]]></title>
            <link>https://medium.com/@adarshtyagi/design-youtube-47605c9780be?source=rss-75c5e32da7ef------2</link>
            <guid isPermaLink="false">https://medium.com/p/47605c9780be</guid>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[streaming-video]]></category>
            <category><![CDATA[design-systems]]></category>
            <category><![CDATA[youtube]]></category>
            <dc:creator><![CDATA[Adarsh Tyagi]]></dc:creator>
            <pubDate>Sun, 29 Mar 2026 15:19:29 GMT</pubDate>
            <atom:updated>2026-03-29T15:19:29.185Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bNJ63lDtPGswCA7M.jpg" /></figure><p>In the past decade, platforms like YouTube have completely redefined how we consume, create, and share content online — boasting 2.7 billion monthly active users and over 1 billion hours of video watched daily. What started as a simple video-sharing site has evolved into a global ecosystem generating $40 billion+ in projected ad revenue. In this blog we will see how we can design such services and what challenges we need to tackle.</p><h3>Requirements</h3><p>As usual starting with the functional requirements of the system</p><ol><li>User should be able to upload the videos.</li><li>User can watch the videos.</li></ol><p>Now, our non functional requirements can be</p><ol><li>System should be highly available.</li><li>System should be able to handle the video streaming in any network quality.</li><li>System should be highly scalable assuming the youtube’s user base.</li><li>System needs to support uploading and streaming large videos efficiently.</li></ol><h3>Capacity Estimations</h3><p>For youtube like service, let’s assume daily active users (DAU) as 10 million. If 10% users (1 million) uploads 1 video per day and taking the average size of each video as 300 MB then the total storage needed per day</p><p>1 million * 300 MB = 300 TB (approx)</p><h3>Entities and APIs</h3><p>The core entities for this system will be User, Video and Metadata. The two core APIs required for this system are</p><ol><li>POST /upload → Upload the user’s video along with video’s metadata.</li><li>GET /videos/{video_id} → Fetch the video and its metadata</li></ol><h3>High Level Design</h3><p>In this system design, we will handle two most important features i.e., video upload and its streaming.</p><h4>Video Upload</h4><p>For uploading feature, we need to take care of two things. First is where to store the video metadata and second is where to store the actual video. Considering 1 million videos upload a day means 1 million records in database for videos. So surely we will need to shard our database for video metadata. So for this we can use <a href="https://cassandra.apache.org/_/index.html">cassandra</a> database, which supports the scalability and auto-shards via consistent hashing. Here we can use videoId as our shard key.</p><p>Now, for storing the actual video we can use blob storage services like Amazon S3. For every upload request, we can create a pre-signed URL for the user and then user can directly upload the video on S3 using that URL. We also need to store the video in different formats to support the different client devices and network bandwidth. After user uploads the video in S3, then we can have a service which can do the task of converting the video in different formats. But there is an issue in this approach, at the time of streaming the user will not download the complete video at their end and then stream, rather user will keep fetching the parts of video and stream them and in this approach we are not taking care of video segments.</p><p>Another method can be like we can split the video in multiple segments (few seconds in length) and then format each segment and store them.</p><h4>Videos Stream</h4><p>For this, user request will go to our service and then fetches the video metadata along with the URL necessary to watch the video. In S3 we can have a manifest file which stores the different video formats information. So in video metadata user will get the URL to this manifest file and then client will choose the video format based on device and network bandwidth. After deciding this, user will fetch the segment in selected format and start streaming and at the backend side will keep fetching the next video segments. In this method, if at any time user network slows down then the low quality format will get fetch and keep streaming the video without any hassle.</p><h3>Design Deep Dive</h3><h4>How to handle video processing for different formats efficiently ?</h4><p>For smooth video streaming, as discussed we will keep the video in segments in different formats. But how can we process and store these segments efficiently ?</p><p>We can have a pipeline process for this and the output of that pipeline will be segments of video and manifest file as discussed earlier. In this pipeline, first we will split the video and create segments of a particular size and then convert those segments into different formats (different device supported file type and bitrate). Then create the manifest file having reference to different format segments and at the end mark the video as download completed. Now to make this pipeline efficient, what we can do is to process the multiple segments parallely on different workers as these segments will be independent of each other.</p><h4>How to support resumable upload ?</h4><p>Client can divide the file into chunks and create a unique hash for each chunk. Now client will send this chunk info to the backend and will get save in video metadata. Client will start uploading each chunk to S3 and after uploading that chunk the S3 will return a tag for that chunk and then client will forward that tag to backend and then backend will verifies that from S3 and mark that chunk as uploaded. When the upload stops and then resume then client can check which chunks are already uploaded from the backend and then continue to upload the remaining chunks.</p><h4>How to scale the upload and stream service ?</h4><p>Starting with the first step, we will replicate the video metadata database to support large number of queries from users. Next to handle the popular video problem, we will keep the cache in front of metadata database to reduce the latency and load from DB. Also to handle the streaming issues efficiently, we can use <a href="https://developer.mozilla.org/en-US/docs/Glossary/CDN">CDN</a>. CDN will cache the popular videos and also can serve the users geographically near to it efficiently.</p><h3>Architecture Diagram</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EaDw9kNvqby7f3h2ePWRxg.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=47605c9780be" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Design Google Drive]]></title>
            <link>https://medium.com/@adarshtyagi/design-google-drive-71b834eb00e1?source=rss-75c5e32da7ef------2</link>
            <guid isPermaLink="false">https://medium.com/p/71b834eb00e1</guid>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[cloud-storage-services]]></category>
            <dc:creator><![CDATA[Adarsh Tyagi]]></dc:creator>
            <pubDate>Sun, 15 Mar 2026 18:15:40 GMT</pubDate>
            <atom:updated>2026-03-15T18:15:40.486Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/850/0*imE5mx1ojgmcMdEy.jpg" /></figure><p>We use cloud storage services daily to store our data, keep backups and share with other users. Cloud storage services like Google Drive, Dropbox, and iCloud let users store, access, and share files over the internet instead of keeping everything on a single local disk. In this blog, we will see how we can design such services. Similar to our previous blogs we will start with requirements, system entities, APIs, estimations, high level design and then deep dive the design to resolve any issues and optimise the system.</p><h3>Requirements</h3><p>Starting with functional requirements</p><ol><li>User can upload a file from any device.</li><li>User can download the files to any device.</li><li>User can share his/her files with other users.</li><li>Files should get sync across all devices of users.</li></ol><p>Now let’s see the non-functional requirements</p><ol><li>System should be highly available.</li><li>Maximum file size that system should support is 10GB.</li><li>System should be secure and reliable, files should not get lost or corrupt.</li><li>System should have low latency and eventual consistency.</li></ol><h3>Capacity Estimations</h3><p>Let’s assume the total user base of 50 million and 10 million daily active users. Assuming each user gets 10 GB of free space, so total storage requirements</p><p><strong><em>50 million * 10 GB = 500 PB</em></strong></p><p>Considering each user uploads 2 files per day on an average, so</p><p><strong><em>queries per second (QPS) = (10 million * 2) / 86400 = 240</em></strong></p><h3>Entities and APIs</h3><p>We will have simple 3 core entities for this system i.e. User, File and File Metadata. APIs for the system will be as following</p><ol><li><strong>POST /files</strong> → Upload a file</li><li><strong>GET /files/{file_id}</strong> → Download a file</li><li><strong>POST /files/{file_id}/share</strong> → Share the file with other users</li></ol><h3>High Level Design</h3><h4>Upload</h4><p>Let’s start with the most important feature of this system and that is allowing users to upload their file and save them.</p><p>To upload the files, we will need to take care of two things. First is to save the file content and other is to save the file metadata. Starting with file metadata, I think the most simple choice is to store this metadata in SQL database. The metadata will incude details like file id, user, size, type and SQL can take care of these things easily. But now where do we store the actual file content? First solution we can think of is to upload the file to our backend server, but the issue is that it will become a single point of failure, if server goes down, user will lose the files and also this solution is not scalable as the user base or file size grow.</p><p>Better approach will be to use the blog storage services like Amazon S3 or google cloud storage. Instead of storing files on our backend servers, we can use these services. These services are more reliable and also scalable. If our server goes down, we will not lose access to the files. To optimize this solution, what we can do is allow user to directly upload the file to the blob storage by using the presigned URLs. Once the file gets uploaded, blob storage service can send the notification to our backend so we can update and save the metadata.</p><h4>Download</h4><p>Now, second feature is to allow users to download their files. To handle this, we can allow users to download the files directly from blob storage and for this we can again use presigned URLs. This can also save the bandwidth in our backend. Again to optimize this feature, we can use CDN (content delivery networks). Using CDN, we can cache the file close to the user location and reduces the latency. The only challenge here will be to strategise what file to cache and for how long and for this to handle we can cache frequently accessed files.</p><h4>File Sharing</h4><p>Next we will handle the file sharing among users. Now to allow user to access the shared file of other user, we can create a shared users list in file metadata. Now when user will try to access the file, we will check whether that user is in shared users list of file metadata or not. But the issue here will be when user will open the application. So, when user will open the site or application, they would expect to see the shared file and to render those file will be expensive in terms of time as we would need to scan through the shared users list of each file and you can imagine how expensive that would be.</p><p>But we can solve this by normalizing the data. We can create a new database table that will map the user id to file id. This way when user will open the application, we can simply fetch the file ids by scaning this table based on user id and we can take advatnage of indexing based on user id.</p><h4>Data Sync</h4><p>Next feature that we all know is to sync the files across the devices. We will keep the copy of particular file on each client device and also in remote storage (cloud). So we will sync firstly from local to remote. When user will update the file on their device we will update the changes in remote storage. To do this we can use system event to track the changes locally and when it detect the change it can update the file on remote and for this it can use the upload API. Now in this, conflicts can occur when two users will try to update the file at the same time and to handle we can use the last write win strategy i.e. most recent change handled by the server will be stored.</p><p>Now next thing is to sync the local from remote servers i.e. each client will need to know when there will be change in remote server. For this we can use the websockets or server side events to update the client side for any changes occuring on remote server. For any change, the remote server can push the change event on client device and in case the websocket connection drops, we can use the polling as fallback option. In polling, the client device can perodically ask the remote server for any changes.</p><h3>Design Deep Dive</h3><h4>Upload Large Files</h4><p>Uploading the large file (in GB) will take large amount of time also, obviously based on user network. So we will need some method to let the user know how much has been uploaded and if they decide to resume their upload, we can allow them to do so. Also, uploading large files is scary because if at any point of time the network drops the user will have start the upload from scratch. So to handle this we can use chunking method. In chunking we will break the file in small parts or chunks and then upload them either one at a time or parallel depending on user’s network. Chunking needs to be done at client side only because if we will make our chunking step at our backend then this solution will not make sense because to chunk at our backend side we will need the file and to get the file we need to upload that to our server and again we are back to square one. So we will do the chunking at client side and break the file into pieces of 5–10 MB each. With chunks we can easily show the upload progress to the user. <br>Now we will store the status of chunk uploads and track which chunk has been uploaded and which haven’t. When user will resume the upload and start again, we can easily check which chunks needs to be uploaded. Now when any chunk will get uploaded, a request can be sent to the server with chunk status and a tag which can be used by backend server to verify this upload to S3 and then update the metadata.</p><h4>Optimize the upload the download</h4><p>Our chunking method will definitely optimize the upload when we will upload the chunks parallely. And similarly our CDN method will improve the downloading part but to more optimise the upload and download, we can use compression techniques. Before uploading we can compress the file on client side and then store the file as it is in S3 and then at downloading side, client can decompress the data after retrieving it from storage.</p><h4>Data Security</h4><p>It is very important part of the system, to keep the user data secure. First step we will definitely use is HTTPs to transfer the file securely from client to server. But on top of this we can also store the file in encrypted form in blob storage. So in case an external entity gets the access of the blob storage, they will not be able to see the actual content. Amazon S3 has this feature to store the file in encrypted form.</p><h3>Architecture Diagram</h3><p>Now let’s see the final desing architecture</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/878/1*L5ktsqP7NhaDfaRceYFYWg.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=71b834eb00e1" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>