<?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 GauravSingh9356 on Medium]]></title>
        <description><![CDATA[Stories by GauravSingh9356 on Medium]]></description>
        <link>https://medium.com/@gauravsingh9356?source=rss-bea6446d2d53------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Fn-eiWUmBwBw2V4Ht6QbDw.png</url>
            <title>Stories by GauravSingh9356 on Medium</title>
            <link>https://medium.com/@gauravsingh9356?source=rss-bea6446d2d53------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 08:30:16 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@gauravsingh9356/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[Design Dropbox / Google Drive: Scalable End-to-End System Design]]></title>
            <link>https://gauravsingh9356.medium.com/design-dropbox-google-drive-scalable-end-to-end-system-design-7981e51e0499?source=rss-bea6446d2d53------2</link>
            <guid isPermaLink="false">https://medium.com/p/7981e51e0499</guid>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[GauravSingh9356]]></dc:creator>
            <pubDate>Sat, 07 Nov 2026 16:39:28 GMT</pubDate>
            <atom:updated>2026-11-07T16:39:28.566Z</atom:updated>
            <content:encoded><![CDATA[<p>Building a cloud storage and synchronization engine like <strong>Dropbox or Google Drive</strong> is one of the most common system design scenarios. At first glance, it seems simple, just let users save files to the cloud 😅. But when you start accounting for multi-gigabyte files, multi-device synchronization, offline edits, and low latency across the globe, the architecture gets tricky fast.</p><p>Here is a practical, step-by-step breakdown of how to design a reliable cloud storage service from the ground up.</p><h4>1. Defining the Requirements 🚀</h4><p>Before diving into databases and cloud services, we need to establish clear boundaries for what our system does — and what it prioritizes.</p><p><strong>Functional Requirements</strong></p><ul><li><strong>File Uploads:</strong> Users can upload files of varying formats and sizes.=</li><li><strong>File Downloads:</strong> Users can fetch their stored files on demand.</li><li><strong>Cross-Device Synchronization:</strong> Modifications made on one device (e.g., laptop) must automatically update across all other connected devices (e.g., phone, tablet).</li></ul><p><strong>Non-Functional Requirements</strong></p><ul><li><strong>High Availability Over Strict Consistency:</strong> The system should prioritize high availability for browsing and operations, utilizing eventual consistency across sync devices while guaranteeing data integrity.</li><li><strong>Low Latency:</strong> Uploads and downloads must be fast, avoiding unnecessary server hops.</li><li><strong>Large File &amp; Resumable Upload Support:</strong> The system must handle multi-gigabyte files effortlessly and allow uploads to resume seamlessly after network interruptions.</li><li><strong>High Data Integrity:</strong> Files must never be corrupted or lost during transit or storage.</li></ul><h4>2. Core Entities &amp; API Design 🔥</h4><p><strong>Data Entities</strong></p><p>We can break down our data model into three core abstractions:</p><ol><li><strong>User:</strong> Manages authentication, accounts, and quota limits.</li><li><strong>File:</strong> Represents the logical container for stored content.</li><li><strong>File Metadata:</strong> Stores structural information about files, including their chunk composition for resumable transfers.</li></ol><p>A simplified JSON representation of the <strong>File Metadata</strong> document looks like this:</p><pre>{<br>  &quot;fileId&quot;: &quot;file_992183&quot;,<br>  &quot;createdAt&quot;: &quot;2026-11-07T12:00:00Z&quot;,<br>  &quot;name&quot;: &quot;architecture_diagram.png&quot;,<br>  &quot;mimeType&quot;: &quot;image/png&quot;,<br>  &quot;chunks&quot;: [<br>    {<br>      &quot;chunkId&quot;: &quot;chk_001&quot;,<br>      &quot;status&quot;: &quot;UPLOADED&quot;<br>    },<br>    {<br>      &quot;chunkId&quot;: &quot;chk_002&quot;,<br>      &quot;status&quot;: &quot;PENDING&quot;<br>    }<br>  ]<br>}</pre><p><strong>Core API Endpoints</strong></p><p>To keep the service clean and decoupled, we separate raw data transfer from metadata control operations:</p><p>POST /file<strong> Payload:</strong> File &amp; FileMetadata</p><ul><li><strong>Purpose:</strong> Registers an upload session, creates metadata records, and returns pre-signed URLs for raw chunk storage.</li></ul><p>GET /files/:fileId</p><ul><li><strong>Returns:</strong> FileMetadata &amp; pre-signed download URLs.</li><li><strong>Purpose:</strong> Initiates file downloads by giving clients direct access to stored blob locations.</li></ul><p>GET /changes?since={timeStamp}</p><ul><li><strong>Returns:</strong> fileIds[]</li><li><strong>Purpose:</strong> Allows client devices to query for updates that occurred after a specific point in time.</li></ul><h4>3. High-Level Architecture Overview 🔥</h4><p>To scale to millions of concurrent users without melting our application servers, we separate the control plane (metadata management and sync) from the data plane (raw binary file transfer).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h3756OUxwMNYNxyKhJh_9w.png" /></figure><h3>Key System Components</h3><ul><li><strong>Client Application:</strong> Resides on the user’s device. Monitors local directories for changes, splits large files into smaller chunks, uploads/downloads chunks in parallel, and handles local storage replacement.</li><li><strong>Load Balancer &amp; API Gateway:</strong> Serves as the single entry point for API traffic. Handles rate limiting, authentication, SSL termination, and routes requests to downstream microservices.</li><li><strong>File Service:</strong> Manages metadata operations. It accepts file creation requests, generates secure pre-signed URLs for Object Storage, and updates file metadata state.</li><li><strong>Sync Service:</strong> Responsible for tracking state across devices. It calculates delta changes when files are updated and notifies client applications of remote modifications.</li><li><strong>Blob Storage (e.g., AWS S3):</strong> Object storage used to hold raw file chunks. It handles massive scale, high availability, and built-in redundancy at low cost.</li><li><strong>File Metadata DB:</strong> A fast database (NoSQL or sharded relational DB) storing file properties, directory hierarchies, user ownership, and chunk mapping tables.</li></ul><h4>4. Deep Dive: Key Workflows</h4><p><strong>1. Upload Flow (Pre-Signed URL Pattern)</strong></p><p>Passing large binary files directly through application servers causes bandwidth bottlenecks and high CPU overhead. Instead, we offload binary transfer to Object Storage:</p><ol><li><strong>Initiate Upload:</strong> The client sends file metadata to POST /files through the API Gateway to the File Service.</li><li><strong>Metadata Creation:</strong> The File Service writes initial file metadata into the DB and generates pre-signed S3 upload URLs.</li><li><strong>Direct Upload:</strong> The client uploads file chunks directly to <strong>Blob Storage (S3)</strong> using the pre-signed URLs, completely bypassing the microservices.</li><li><strong>Finalize Session:</strong> Once chunks finish uploading, S3 signals completion (or the client notifies the File Service) to update chunk statuses to UPLOADED.</li></ol><p><strong>2. Download Flow (Direct-from-S3 Pattern)</strong></p><p>Similar to uploading, downloading avoids routing file streams through our application backend:</p><ol><li><strong>Request Metadata:</strong> The client sends GET /files/:fileId to the File Service.</li><li><strong>Generate URL:</strong> The File Service verifies permissions and returns a short-lived pre-signed download URL pointing directly to the object in S3.</li><li><strong>Direct Download:</strong> The client streams the binary file directly from <strong>Blob Storage (S3)</strong>.</li></ol><p><strong>3. Synchronization Flow (Delta Sync &amp; Device State)</strong></p><p>Keeping multiple devices in sync requires handling changes from both sides:</p><pre>1. Remote Changed:<br>   Client queries Sync Service -&gt; Downloads updated chunks from S3 -&gt; Replaces local file<br><br>2. Local Changed:<br>   Local watcher detects change -&gt; Chunks modified sections -&gt; Uploads new chunks to S3 -&gt; Updates Remote Metadata</pre><ul><li><strong>Local Changes:</strong> The client watcher thread detects a file save or modification, splits the file into chunks, requests pre-signed URLs, uploads modified chunks to S3, and updates metadata.</li><li><strong>Remote Changes:</strong> The client periodically or via WebSockets queries GET /changes?since={timeStamp}. The <strong>Sync Service</strong> returns a list of modified fileIds. The client then downloads the updated file/chunks and replaces its local copy.</li></ul><p><strong>5. Architectural Trade-offs &amp; Best Practices</strong></p><ol><li><strong>Chunking &amp; Resumable Uploads:</strong> Splitting files into fixed-size chunks (e.g., 4MB) means if a 1GB upload fails at 90%, you only re-upload the failed chunks, not the entire file.</li><li><strong>Deduplication:</strong> Hashing chunks (e.g., SHA-256) before uploading allows the system to check if a chunk already exists in S3 across the system, saving massive amounts of storage space.</li><li><strong>Availability vs. Consistency:</strong> While metadata operations require strong consistency so users don’t see corrupted file trees, synchronization across devices can be eventually consistent. A delay of a few seconds in syncing across devices is completely acceptable for a smooth user experience.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7981e51e0499" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Caching Explained Through a Story: From 100 Users to 1 Million Users ]]></title>
            <link>https://gauravsingh9356.medium.com/caching-explained-through-a-story-from-100-users-to-1-million-users-3857e480edff?source=rss-bea6446d2d53------2</link>
            <guid isPermaLink="false">https://medium.com/p/3857e480edff</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[GauravSingh9356]]></dc:creator>
            <pubDate>Sat, 10 Oct 2026 10:49:44 GMT</pubDate>
            <atom:updated>2026-10-10T10:49:44.447Z</atom:updated>
            <content:encoded><![CDATA[<p><strong><em>What caching is, why we need it, how different caching strategies work, and how to solve the problems that come with it.</em></strong></p><p>Imagine you are building a <strong>music-streaming application</strong>. A user opens the app, searches for a song, checks an artist’s profile, and starts playing music. Everything works perfectly. Initially, you have just 100 users. Your database handles every request without any trouble.</p><p>Then your application becomes popular. You now have 10,000 users. Then 100,000. Eventually, you reach a million users. Suddenly, things start getting slower. Your database is receiving too many requests. Some API calls take seconds to complete. Your servers are under pressure, and users are complaining.</p><p>You look at your logs and notice something interesting. Thousands of users are requesting the same information again and again.</p><p>For example, whenever someone opens the homepage, your application fetches the same popular songs, artist details, and playlist information from the database.</p><p>Why are we going to the database every single time when the answer is often the same?</p><p><strong>What if we could remember the answers we have already fetched and reuse them?</strong></p><p>That simple idea leads us to caching.</p><p><strong>Let’s understand how it works, one problem at a time.</strong></p><h3>1. What exactly is caching, and why do we need it? 😕</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MeRb4pzBeaN6aGjAA1M49g.jpeg" /></figure><p>Think about a restaurant.</p><p>A waiter doesn’t go to the supermarket every time a customer orders a glass of water. The restaurant already has water available nearby. The water is easy to access, so serving it takes less time. Caching follows the same idea.</p><p>A cache is a place where we temporarily store data that we expect to use again. When the same data is requested later, we can retrieve it from the cache instead of fetching it from the original source.</p><p>In our music application, we might cache:</p><ul><li>Popular songs and their metadata.</li><li>Artist profiles.</li><li>User playlists.</li><li>Homepage recommendations.</li><li>Frequently accessed configuration.</li></ul><p>Instead of repeatedly asking the database for the same information, we can keep a copy in a faster storage system, such as Redis or an in-memory cache.</p><h3>How does this improve performance? 😃</h3><p>Consider a simplified example:</p><ul><li>Fetching data from a database takes 50 milliseconds.</li><li>Fetching the same data from a cache takes 2 milliseconds.</li></ul><p>Without caching, every request takes approximately 50 milliseconds for this data retrieval. With caching, requests that find the data in the cache can retrieve it in approximately 2 milliseconds. That is a <strong>25x improvement </strong>in retrieval time for this example.</p><p>The actual end-to-end improvement depends on network calls, processing, cache overhead, and other work performed by the application. Caching also reduces database load, helps applications handle more traffic, and can reduce infrastructure costs.</p><p>But there is an important detail.</p><p><strong>A cache is not the original source of truth. It is usually a faster copy of data stored somewhere else.</strong></p><p>That distinction becomes important when the original data changes. Before we discuss that problem, let’s see how an application actually uses a cache.</p><p>Let’s look at four common types.</p><h4><strong>Client-side caching</strong></h4><p>Imagine a user opens a music app and visits the same screen multiple times. Do we really need to fetch every piece of information from the server on every visit?</p><p>Not necessarily.</p><p>We can store certain data on the user’s device, such as in browser memory, local storage, or an HTTP cache. The application can reuse that data without making another network request.</p><p><strong>When to use it:</strong> For data that can safely be stored on the client, such as static assets, UI preferences, or previously fetched content with an appropriate freshness policy.</p><h4><strong>CDN caching</strong></h4><p>Now imagine millions of users are downloading the same album cover or promotional image. Instead of making every request travel all the way to our origin server, we can use a Content Delivery Network (CDN).</p><p>A CDN keeps copies of cacheable content at servers distributed across different locations. Users can fetch content from a nearby CDN server, reducing latency and traffic to the origin.</p><p><strong>When to use it:</strong> For static assets such as images, videos, JavaScript, CSS, and other content that can be safely cached close to users.</p><h4><strong>External or distributed caching</strong></h4><p>Our music application now has many backend servers. If each server keeps its own copy of every artist profile, memory usage increases, and different servers may have different versions of the data.</p><p>We can introduce a shared caching system such as Redis. All application servers can access the same logical cache instead of maintaining independent copies.</p><p><strong>When to use it:</strong> For frequently accessed backend data, session information, API responses, and other data that benefits from a shared cache across application instances.</p><h4>In-memory caching</h4><p>Sometimes, even calling Redis is unnecessary.</p><p>Imagine our application uses feature flags to decide whether a new music player feature should be enabled. These flags may be read thousands of times but change relatively infrequently.</p><p>We can keep frequently accessed data directly in the application’s memory. Reading it is extremely fast because it avoids both a network request and a database query.</p><p><strong>When to use it:</strong> For frequently read, relatively small data such as feature flags, configuration, and reference data. Remember that each application instance has its own memory, so updates must be propagated or refreshed when consistency matters.</p><h3>2. What happens when a request reaches the cache? 😯</h3><p>Imagine a user opens an artist’s profile. Our application first checks the cache.</p><p>There are two possible outcomes.</p><h3>Case 1: Cache hit</h3><p>The artist’s profile is already available in the cache. The application returns the cached data immediately. No database query is required.</p><p>This is called a <strong><em>cache hit</em>.</strong></p><h3>Case 2: Cache miss</h3><p>The artist’s profile is not available in the cache. The application fetches it from the database, returns it to the user, and may store it in the cache for future requests. This is called a <strong><em>cache miss</em>.</strong></p><p>The flow looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KPwKbqqj5qwc4POf9RmrCA.png" /></figure><p>So far, caching seems simple.</p><p>But now imagine that our application has millions of requests and different types of data. We need to answer some important questions.</p><ul><li>When should we fetch data from the database?</li><li>When should we update the cache?</li><li>What happens when someone changes their playlist?</li><li>What happens when the cache becomes full?</li></ul><p>These questions lead us to caching strategies.</p><h3>3. Caching strategies: Where should the cache fit into our application?</h3><p>Let’s continue with our music application.</p><p>We have decided to introduce Redis as our cache. But simply adding Redis does not tell us how the application should behave.</p><p>For example, suppose a user renames a playlist.</p><p>Should we update the database first? Should we update the cache first? Should we update both together? What if one update fails?</p><p>Different caching strategies answer these questions differently.</p><p>Let’s understand the four common approaches.</p><h3>3.1 Cache-aside: The application manages the cache</h3><p>This is one of the most commonly used caching strategies.</p><p>Imagine a user opens a playlist. Our application checks Redis first.</p><p>If the playlist exists in Redis, the application returns it. If it doesn’t exist, the application fetches it from the database and stores it in Redis before returning it.</p><p>The application itself decides when to read from and write to the cache. This approach is called <strong><em>cache-aside</em></strong>, also known as <strong><em>lazy loading</em></strong>.</p><p>The read flow is:</p><ol><li>Check the cache.</li><li>If the data exists, return it.</li><li>Otherwise, fetch it from the database.</li><li>Store the result in the cache.</li><li>Return the result to the user.</li></ol><p>Now suppose the user renames the playlist. A common cache-aside write approach is to update the database first and then invalidate the corresponding cache entry. The next request will fetch the updated playlist and populate the cache again.</p><p><strong>When should you use cache-aside?</strong></p><p>Use it when you want flexibility and control over what gets cached. It works well for applications where reads are frequent, but not every database record needs to live in the cache. It is also a good starting point because it is relatively easy to implement.</p><p>The downside? Your application must explicitly handle cache reads, cache misses, and cache invalidation.</p><h3>3.2 Read-through: The cache fetches missing data</h3><p>Now imagine we want the application code to be simpler.</p><p>Instead of asking Redis for data and then manually fetching it from the database on a miss, we introduce a caching layer that handles the lookup for us.</p><p>The application asks the caching layer for the playlist. If the playlist exists, the cache returns it. If it doesn’t, the caching layer fetches it from the database, stores it, and returns it to the application.</p><p>The application does not need to implement the cache-miss logic itself. That is the idea behind <em>read-through caching</em>. The key difference is who handles the cache miss.</p><ul><li>In cache-aside, the application handles it.</li><li>In read-through, the caching layer handles it.</li></ul><p><strong>When should you use read-through?</strong></p><p>Use it when you want consistent caching behavior and less repetitive cache-management code in your application.</p><p>It is especially useful when your caching library or infrastructure supports a read-through loader.</p><p>One thing to remember: Redis by itself does not automatically fetch missing values from your database. You need an application-level caching layer or a compatible caching library to provide this behavior.</p><h3>3.3 Write-through: Every write updates the cache and database</h3><p>Now let’s return to the playlist rename.</p><p>Suppose the user changes the playlist name from “Workout” to “Morning Run.” We want future reads to see the new name rather than the old one.</p><p>With <strong><em>write-through caching</em></strong>, a write is passed through the caching layer to the database, and the cache is updated as part of that write operation.</p><p>Conceptually:</p><ol><li>The application requests a playlist update.</li><li>The caching layer writes the updated data to the database.</li><li>The cache is updated with the new data.</li><li>The write is acknowledged according to the system’s consistency and failure-handling rules.</li></ol><p>The important idea is that the cache is updated as part of the write path rather than waiting for a future read.</p><p><strong>When should you use write-through?</strong></p><p>Use it when data is read frequently after being written and you want the cache to remain fresh as part of the normal write flow. For example, it can be useful for product details, account information, or playlists that users expect to see updated immediately. The trade-off is that writes can take longer because both the database and cache need to be handled. You also need to define what happens if one update succeeds and the other fails.</p><p>Write-through does not automatically make the database and cache a single atomic transaction.</p><h3>3.4 Write-behind: Update the cache first, database later</h3><p>Now imagine our music application is handling millions of listening events. Every event updates a play counter or some aggregated statistics. Writing every tiny update to the database immediately could become expensive.</p><p>What if we could accept updates quickly and persist them to the database asynchronously? That’s the idea behind <em>write-behind</em>, also called <em>write-back caching</em>.</p><p>The flow looks like this:</p><ol><li>The application updates the cache.</li><li>The cache acknowledges the update.</li><li>The updated data is queued or scheduled for asynchronous persistence.</li><li>The database is updated later.</li></ol><p>For example, our application might collect listening statistics in memory and periodically flush aggregated results to persistent storage. This can reduce database writes and improve write performance.</p><p>But there is a serious trade-off.</p><p><strong>What happens if the application crashes before pending updates reach the database?</strong></p><p>If those updates were not durably recorded, they could be lost. A production write-behind system therefore needs a clear durability and recovery strategy. This might involve a durable queue, a write-ahead log, retries, and idempotent database updates.</p><p><strong>When should you use write-behind?</strong></p><p>Use it when write throughput matters more than immediate persistence and a short delay before the database is updated is acceptable. It can be useful for analytics, counters, telemetry, and aggregation workloads.</p><p>Avoid using a simple, volatile write-behind cache as the only protection for critical financial transactions or other data that must never be lost.</p><h3>Let’s compare the four strategies 🚀</h3><h4>Cache-aside: The application manages the cache</h4><p>The application first checks the cache. If the data is missing, it fetches it from the database, stores it in the cache, and returns it to the user.</p><p>When data changes, the application typically updates the database and invalidates the corresponding cache entry.</p><p><strong>Best suited for:</strong> General-purpose application caching where you want flexibility and control over cache behavior.</p><h4>Read-through: The cache fetches missing data</h4><p>The application asks the caching layer for data. If the data is missing, the caching layer fetches it from the database, stores it in the cache, and returns it. Unlike cache-aside, the application doesn’t need to manage the cache-miss logic itself.</p><p><strong>Best suited for:</strong> Applications that want to simplify repeated read logic using a caching layer that supports automatic data loading.</p><h4>Write-through: Update the cache as part of the write flow</h4><p>When the application updates data, the caching layer writes the change to the database and updates the cached value as part of the same logical write flow. This helps keep frequently accessed data fresh, although failures between the two updates still need to be handled.</p><p><strong>Best suited for:</strong> Data that is frequently read after being updated and needs to remain reasonably fresh.</p><h4>Write-behind: Write now, persist later</h4><p>The application updates the cache, and the change is persisted to the database asynchronously. This reduces the need to write every update to the database immediately.</p><p>However, if pending changes are lost before they are persisted, data can be lost. A reliable implementation needs a durability and recovery mechanism.</p><p><strong>Best suited for:</strong> High-volume writes, such as analytics and aggregated counters, where delayed persistence is acceptable.</p><p><strong>One important detail</strong>: these strategies are not mutually exclusive. An application might use cache-aside for reads and cache invalidation for writes, while another part of the same system uses write-behind for analytics.</p><p>The right strategy depends on how your data is read, written, and expected to behave when something fails.</p><h3>4. The cache is full. What should we remove? 👮</h3><p>Our music application is growing again. We are caching artist profiles, song metadata, playlists, and recommendations. But memory is not unlimited.</p><p>Eventually, our cache reaches its capacity. We need a way to decide which entries to remove to make room for new ones. This brings us to <em>cache eviction policies</em>. Think of your cache as a small cupboard. When it becomes full, you must decide which items to throw away.</p><p>The goal is not simply to remove something. It is to remove something that is less useful than the data we want to keep.</p><p>Let’s explore the most common policies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*4qSeiyHJOHinN44geZ4KZQ.jpeg" /></figure><h3>4.1 LRU (Least Recently Used)</h3><p>Imagine that users opened these three artist profiles:</p><ul><li>Artist A was accessed a few seconds ago.</li><li>Artist B was accessed an hour ago.</li><li>Artist C was accessed two days ago.</li></ul><p>If the cache is full and needs to remove one entry, LRU removes the entry that was accessed least recently. In this example, Artist C is the likely candidate.</p><p>The reasoning is simple: data accessed recently may be requested again soon.</p><p><strong>When should you use LRU?</strong></p><p>LRU works well when recently accessed data is likely to be accessed again. For example, users may revisit recently played songs, recently opened playlists, or the same pages while navigating an application.</p><p>The limitation is that LRU does not consider how frequently an item is accessed over a longer period. A frequently used item can still be evicted if it hasn’t been accessed recently.</p><h3>4.2 LFU (Least Frequently Used)</h3><p>Now imagine two songs.</p><p>Song A was accessed 100 times last week but hasn’t been accessed today. Song B was accessed only once.</p><p>If we want to retain data that is consistently popular, recency alone may not be enough. LFU removes the entry with the lowest access frequency.</p><p>In this example, Song B would be the likely candidate.</p><p><strong>When should you use LFU?</strong></p><p>LFU can work well when a relatively small group of items receives most of the requests over time. For example, a music application might have a collection of consistently popular songs or artist profiles.</p><p>However, pure LFU has a weakness: an item that was extremely popular in the past can retain a high frequency count even after it becomes irrelevant. Practical implementations may use frequency decay or aging so older popularity does not dominate forever.</p><h3>4.3 FIFO (First In, First Out)</h3><p>Imagine three entries entered the cache in this order:</p><ol><li>Artist A</li><li>Artist B</li><li>Artist C</li></ol><p>When the cache becomes full, FIFO removes Artist A because it was inserted first. It does not matter whether Artist A was accessed recently or frequently. FIFO considers insertion order rather than access patterns.</p><p><strong>When should you use FIFO?</strong></p><p>FIFO can be useful when you want a simple eviction policy and do not need to track how often or recently items are accessed. It is straightforward to implement, but it may remove a very popular entry simply because it is old.</p><h3>4.4 TTL (Time to Live)</h3><p>Now imagine an artist changes their profile picture.</p><p>We cache the artist profile for a while, but we don’t want the cached copy to live forever. We assign it a TTL of 10 minutes. TTL stands for <em>Time to Live</em>. It defines how long a cache entry is considered valid before it expires.</p><p>After 10 minutes, the entry expires according to the cache’s expiration behavior. A subsequent request can fetch a fresh copy and cache it again.</p><p>TTL is slightly different from LRU, LFU, and FIFO. Those policies typically help decide which entries to remove when memory is needed. TTL defines a time-based expiration rule.</p><p>A cache can use both TTL and an eviction policy.</p><p><strong>When should you use TTL?</strong></p><p>TTL is useful when data can change over time and you want to limit how long a cached copy remains valid.</p><p>For example:</p><ul><li>Artist metadata might have a TTL of several minutes.</li><li>Homepage recommendations might have a TTL of a few minutes.</li><li>Relatively stable configuration might have a TTL of several hours.</li></ul><p>These are illustrative values, not universal recommendations.</p><p>For rapidly changing data, a shorter TTL may be appropriate. For stable data, a longer TTL may reduce unnecessary database traffic.</p><p>Remember that expiration does not always mean every expired entry is removed from memory at that exact instant. Many cache systems combine expiration with lazy removal or background cleanup.</p><h3>5. Everything works until thousands of requests arrive at the same time (Thundering Herd, Cache Stampede) 🏈</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ibwWowVPV1ngMdcPyAuWsw.jpeg" /></figure><p>Our application now has a million users. One morning, a very popular artist (Messi, yes football artist 😆) releases a new album.</p><p>Millions of users want to see the album details. Unfortunately, the cached album entry expires just as traffic spikes. The next thing that happens can be disastrous.</p><p>Thousands of requests arrive at the cache. All of them find that the entry is missing or expired. All of them attempt to fetch the same album details from the database.</p><p>The database suddenly receives thousands of identical queries. It slows down, requests begin timing out, and more requests retry. Soon, the database is overwhelmed.</p><p>This is called a <strong><em>cache stampede</em></strong>, also known as the <em>thundering herd problem</em>.</p><p>The problem is not simply that the cache missed. The problem is that <strong>many requests independently try to rebuild the same cached value at the same time</strong>.</p><p>How do we solve it?</p><h3>Solution 1: Request coalescing or single-flight</h3><p>Instead of allowing 1,000 requests to fetch the same missing album, let one request perform the database fetch. The other requests wait for that result.</p><p>Once the first request fetches the album and populates the cache, the waiting requests reuse the same result. Instead of 1,000 database queries, we perform approximately one fetch for that key during the shared operation.</p><p>This technique is commonly called <strong><em>request coalescing</em> or <em>single-flight</em></strong>. The coordination must work across the relevant application instances if requests are distributed across multiple servers. A process-local single-flight mechanism alone cannot coordinate every server in a distributed deployment.</p><h3>Solution 2: Use a distributed lock 🔒</h3><p>Another approach is to use a lock associated with the cache key.</p><p>When a cache miss occurs, one worker acquires the lock and refreshes the data. Other workers avoid starting the same refresh and either wait, retry, or serve an acceptable cached value.</p><p>This can be implemented using a distributed coordination mechanism. However, distributed locks introduce their own complexity, including lock expiration, failures, and duplicate work when ownership changes. Use them when simpler coordination is insufficient.</p><h3>Solution 3: Refresh the cache before it expires</h3><p>Instead of waiting until the cache expires, refresh popular entries in the background before their TTL runs out.</p><p>For example, if an album entry has a TTL of 10 minutes, the system could refresh it after 8 minutes if it is still popular. Requests continue reading the existing value while the refresh happens.</p><p>This reduces the chance that many requests encounter an empty cache simultaneously.</p><h3>6. The cache returns old data. Now what?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*96Zmo5oqQUUj8Wru4YkbhA.jpeg" /></figure><p>Let’s return to our playlist example.</p><p>A user renames a playlist from “Workout” to “Morning Run.” The database now contains “Morning Run,” but Redis still contains “Workout.”</p><p>When the user opens the playlist again, the application returns the old name. The cache has become stale. This is called <strong><em>stale cache data</em></strong>. It happens because the cached copy and the original data source are no longer in sync. Stale data is not always a serious problem. An old recommendation may be acceptable for a short time.</p><p>But stale account details, inventory counts, or access-control information can cause more serious issues. <strong>So how do we handle it?</strong></p><h3>Solution 1: Cache invalidation</h3><p>One common solution is to invalidate the cached entry whenever the underlying data changes.</p><p>For example:</p><ol><li>Update the playlist in the database.</li><li>Delete the corresponding Redis entry.</li><li>On the next request, fetch the updated playlist from the database.</li><li>Store the new value in Redis.</li></ol><p>This is a common approach when using cache-aside. Why delete the entry instead of updating it?</p><p>Because deletion is often simpler than keeping a cached object synchronized with every possible database change. The trade-off is that the next read becomes a cache miss.</p><h3>Solution 2: Update the cache after the database write</h3><p>Another option is to write the updated value to the database and then update the cache. This is closer to a write-through approach.</p><p>It can work well, but there is an important failure case. <strong>What if the database write succeeds and the cache update fails?</strong></p><p>The cache may still contain old data. You need a retry, invalidation, or reconciliation mechanism to handle that situation.</p><h3>Solution 3: Use events to propagate changes</h3><p>Imagine the playlist service updates a playlist.</p><p>It publishes an event saying that the playlist changed. A cache-maintenance process consumes the event and invalidates or refreshes the corresponding cache entry.</p><p>This approach can be useful when multiple services maintain separate caches. For example, a playlist update may need to invalidate cached playlist information in several application services.</p><p><strong>However, event-driven invalidation is usually asynchronous. There can be a delay between the database update and cache invalidation.</strong></p><p>Reliable event delivery, retries, idempotent processing, and recovery from missed events are important.</p><h3>Solution 4: Use TTL as a safety net</h3><p>Even if your application invalidates entries whenever possible, TTL provides a useful fallback.</p><p>If an invalidation event is missed, the entry eventually expires.</p><p>But remember that TTL does not guarantee immediate freshness. A stale value can still be served until expiration.</p><p><strong>The takeaway:</strong> For most application data, database writes followed by cache invalidation, combined with a sensible TTL, are a practical starting point. For data that requires stronger consistency, additional coordination or versioning may be necessary.</p><h3>7. One key is receiving millions of requests. Meet the hot-key problem (Celebrity Problem)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/792/1*vEaX_OEDRaPihibIpT0JDA.jpeg" /></figure><p>Our music application is now handling a huge amount of traffic. Most requests are distributed across millions of songs and artists.</p><p>But one particular song becomes globally popular. Suddenly, a massive percentage of traffic targets a single cache key.</p><p>For example: artist:global-superstar</p><p>This is a <strong><em>hot key</em></strong>.</p><p>The problem is that even though the cache contains the data, a single key can receive so many requests that it becomes a bottleneck. Depending on the system, this can overload one Redis shard, one cache node, one network path, or the service responsible for fetching the data.</p><p>Notice how this differs from a cache stampede.</p><ul><li>A cache stampede happens when many requests simultaneously try to load missing or expired data.</li><li>A hot key happens when one key receives unusually high traffic, even when the data is already cached.</li></ul><p>A hot key can also trigger a stampede if that key expires.</p><p>Let’s look at the solutions.</p><h3>Solution 1: Local in-memory caching</h3><p>Instead of sending every request to Redis, keep a small local copy of extremely popular, relatively stable data in each application instance.</p><p>For example, every server could keep the details of the most popular artist in its own memory. Requests served by that local cache do not need to reach Redis.</p><p>This reduces network traffic and pressure on the shared cache.</p><p>The trade-off is that different servers may hold different versions of the data. Use short expiration times or explicit invalidation when appropriate.</p><h3>Solution 2: Replicate or distribute hot data (Sharding) 🕸</h3><p>For some workloads, you can replicate popular data across multiple cache nodes or distribute copies of the data across multiple keys.</p><p>This allows traffic to be spread across multiple resources instead of overwhelming a single one. However, replication and sharding strategies depend on the cache technology, and distributing reads does not automatically solve consistency or invalidation problems.</p><h3>Solution 4: Serve stale data when acceptable</h3><p>Suppose the artist’s profile was refreshed five seconds ago and the next refresh is taking longer than expected. If the old profile is still acceptable, continue serving it while a background process fetches a fresh version.</p><p>This is often called <em>stale-while-revalidate</em>.</p><p>It is especially useful for content that does not need to be perfectly current on every request. Do not use this approach blindly for data that requires strict correctness.</p><p><strong>The takeaway:</strong> For extremely popular, relatively stable data, local caching is often a strong first option. Add replication, request coalescing, or stale-while-revalidate when the traffic pattern and consistency requirements justify them.</p><h3>8. Putting everything together: How would we design our caching system?</h3><p>Let’s imagine that our music application has finally reached a million users. We now understand that caching is not simply about adding Redis and hoping everything becomes faster.</p><p>We need to think about how data is accessed, updated, expired, and recovered when things go wrong. These are starting points, not rules that every application should follow.</p><p>A good caching design depends on the actual workload, acceptable staleness, failure behavior, memory limits, and the cost of a cache miss.</p><p>Also, monitor your cache. Useful metrics include:</p><ul><li><strong>Cache hit ratio:</strong> How often requests find the data in the cache.</li><li><strong>Cache miss rate:</strong> How often requests need another source.</li><li><strong>Latency:</strong> How long cache reads and database fallbacks take.</li><li><strong>Evictions and expirations:</strong> How often entries leave the cache.</li><li><strong>Hot-key traffic:</strong> Which keys receive disproportionate requests.</li><li><strong>Database load:</strong> Whether caching actually reduces pressure on the database.</li><li><strong>Refresh failures:</strong> Whether cached data is being refreshed successfully.</li></ul><p>A high cache hit ratio is useful, but it does not automatically mean your caching system is healthy. You could have a high hit ratio while one hot key overloads a cache node, or while the application serves stale data.</p><p>Measure the behavior that matters to your users and your system.</p><h3>9. A few final lessons about caching 🙌</h3><p>After building our music application, we can draw some simple conclusions.</p><p><strong>First, caching is a trade-off: </strong>We exchange memory for speed and reduced database load. In return, we must manage expiration, invalidation, and possible inconsistency.</p><p><strong>Second, there is no single best caching strategy: </strong>Cache-aside is a useful general-purpose starting point. Read-through simplifies cache-miss handling. Write-through helps coordinate normal writes with cache updates. Write-behind can improve write throughput, but needs careful durability and recovery design.</p><p><strong>Third, eviction and expiration solve different problems: </strong>LRU, LFU, and FIFO help determine what to remove. TTL determines how long an entry should remain valid. They can work together.</p><p><strong>Fourth, caching creates new failure modes: </strong>A cache stampede can overwhelm the database. Stale data can produce incorrect results. Hot keys can overload a single cache resource.</p><p>The solution is not to avoid caching. It is to design for these problems instead of discovering them during a production incident.</p><p>And finally, <strong>do not cache everything just because you can: </strong>Cache data that is expensive to fetch, likely to be reused, and safe to serve from a temporary copy. Measure the benefit, understand the consistency requirements, and choose the simplest strategy that satisfies them.</p><p>The ultimate goal is not to build the most complicated caching system.</p><p>It is to make the application <strong>fast, reliable, and correct</strong> for the people using it. And that is what good caching is really about! 🚀</p><p><strong>Drop your comments, if your read was meaningful ❤️</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3857e480edff" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Uber Finds Your Driver in 10 Seconds]]></title>
            <link>https://gauravsingh9356.medium.com/how-uber-finds-your-driver-in-10-seconds-0565a5a7baa4?source=rss-bea6446d2d53------2</link>
            <guid isPermaLink="false">https://medium.com/p/0565a5a7baa4</guid>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[redis]]></category>
            <dc:creator><![CDATA[GauravSingh9356]]></dc:creator>
            <pubDate>Sun, 19 Apr 2026 04:23:39 GMT</pubDate>
            <atom:updated>2026-04-19T04:23:39.126Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YHE07gjN3Raxq-H5Ul63uw.png" /><figcaption>How Uber finds your driver in less than 10 secs</figcaption></figure><h3>Most people think ride matching is simple:</h3><blockquote><em>“Find nearby drivers → assign one”</em></blockquote><p>But systems like Uber don’t work like that.</p><p>Instead, they run a <strong>real-time distributed race</strong>.</p><p>And the real challenge isn’t finding drivers.<br> It’s <strong>coordinating them safely and fast</strong>.</p><h3>Step 1: A Ride Request is Created</h3><p>The moment you tap “Request Ride”:</p><ul><li>A unique rideId is generated</li><li>The system marks it as:</li></ul><pre>ride:123 → SEARCHING</pre><p>This state is usually stored in a fast in-memory store like Redis.</p><p>👉 Why?</p><p>Because everything that follows needs to happen in <strong>milliseconds</strong>.<br>Step 2: Find Nearby Drivers</p><p>A Matching Service queries a geo-index (typically Redis):</p><ul><li>Find drivers within X km</li><li>Rank them based on:</li><li>ETA (not just distance)</li><li>Availability</li><li>Driver quality</li></ul><p>You now have a shortlist:</p><pre>[D1, D2, D3, D4, D5]</pre><h3>Step 3: The Fan-Out (Where Things Get Interesting)</h3><p>Instead of assigning one driver…</p><p>👉 The system sends the request to <strong>multiple drivers at once</strong></p><p>This is called <strong>fan-out</strong>.</p><ul><li>Delivered via WebSockets (fast)</li><li>Or push notifications (fallback)</li></ul><p>Now all drivers see:</p><blockquote><em>“New Ride Request — Accept?”</em></blockquote><h3>Step 4: The Race Begins</h3><p>Multiple drivers may accept at the same time.</p><p>Example:</p><pre>D3 → ACCEPT<br>D1 → ACCEPT (almost same time)</pre><p>Now the system has a problem:</p><p>👉 Who gets the ride?</p><h3>The Naive Solution (and why it fails)</h3><p>A simple approach might be:</p><pre>GET ride:123<br>if empty → SET driverId</pre><p>Looks fine…</p><p>Until two drivers do this simultaneously.</p><p>Result:</p><ul><li>Both see “empty”</li><li>Both write</li><li>One overwrites the other</li></ul><p>👉 Now <strong>two drivers think they won</strong></p><p>This is a classic <strong>race condition</strong>.</p><h3>Step 5: The Atomic Winner Selection</h3><p>To fix this, systems use an atomic operation:</p><pre>SET ride:123 driverId NX EX 10</pre><ul><li><strong>NX</strong> → Only set if not exists</li><li><strong>EX</strong> → Expire after 10 seconds</li></ul><h3>Why Expiry is Critical</h3><p>The EX 10 is not optional — it’s essential.</p><p>Because in real systems:</p><ul><li>Drivers may not respond</li><li>Apps may crash</li><li>Network may fail</li></ul><p>Without expiry:</p><p>👉 Ride requests can get <strong>stuck forever</strong></p><p>With expiry:</p><ul><li>System auto-resets</li><li>Can retry matching</li><li>No manual cleanup needed</li></ul><h3>Redis Is Not Just a Cache</h3><p>This is the subtle but powerful insight:</p><blockquote><em>Redis is acting as a </em><strong><em>real-time coordination engine</em></strong></blockquote><p>It’s not just storing data.</p><p>It’s managing a <strong>state machine</strong>:</p><pre>SEARCHING → ACCEPTED → CONFIRMED</pre><p>And doing it with <strong>atomic guarantees in milliseconds</strong>.</p><h3>Key Takeaways</h3><ul><li>Matching is not assignment — it’s a <strong>controlled race</strong></li><li>Fan-out improves driver utilization and speed</li><li>Atomic operations (SET NX) prevent inconsistencies</li><li>Expiry ensures system resilience</li><li>Redis acts as a <strong>coordination layer</strong>, not just cache</li></ul><h3>Final Thought</h3><blockquote><em>Distributed systems aren’t hard because of scale.<br> They’re hard because of coordination.</em></blockquote><p>And ride matching is one of the cleanest real-world examples of that.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0565a5a7baa4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[     :  …]]></title>
            <link>https://gauravsingh9356.medium.com/-1782a6220a96?source=rss-bea6446d2d53------2</link>
            <guid isPermaLink="false">https://medium.com/p/1782a6220a96</guid>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[microservices]]></category>
            <dc:creator><![CDATA[GauravSingh9356]]></dc:creator>
            <pubDate>Sun, 15 Mar 2026 13:22:09 GMT</pubDate>
            <atom:updated>2026-03-15T13:22:09.587Z</atom:updated>
            <content:encoded><![CDATA[<h3>💥 𝗧𝗵𝗲 𝗛𝗶𝗱𝗱𝗲𝗻 𝗣𝗿𝗼𝗯𝗹𝗲𝗺 𝗶𝗻 𝗠𝗶𝗰𝗿𝗼𝘀𝗲𝗿𝘃𝗶𝗰𝗲𝘀: 𝗗𝘂𝗮𝗹 𝗪𝗿𝗶𝘁𝗲𝘀 (𝗮𝗻𝗱 𝗵𝗼𝘄 𝘁𝗵𝗲 𝗧𝗿𝗮𝗻𝘀𝗮𝗰𝘁𝗶𝗼𝗻𝗮𝗹 𝗢𝘂𝘁𝗯𝗼𝘅 𝗣𝗮𝘁𝘁𝗲𝗿𝗻 𝘀𝗼𝗹𝘃𝗲𝘀 𝗶𝘁)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*poKVTwjTUtBnL89gon9Ehw.png" /><figcaption>Transactional Outbox pattern solves Dual Write problem</figcaption></figure><p>Imagine you’re building an Order Service in a microservices architecture.</p><p><strong>When a user places an order, two things must happen:</strong><br>1. Save the order in the database<br>2. Publish an OrderCreated event so other services (Inventory, Payment, Shipping) can react</p><p><strong>Sounds simple, right?</strong><br>1. Write to DB<br>2. Publish event to message broker<br>But here’s the problem.<br>These two operations are happening in two different systems.<br>Failure scenario: Order saved in DB -&gt; Service crashes before publishing event</p><p>𝗥𝗲𝘀𝘂𝗹𝘁: 𝗢𝗿𝗱𝗲𝗿 𝗲𝘅𝗶𝘀𝘁𝘀<br>Inventory service never receives the event<br>System becomes inconsistent<br>This is called the Dual Write Problem.<br>And it’s one of the most common reliability issues in distributed systems.</p><p>🚀𝗧𝗿𝗮𝗻𝘀𝗮𝗰𝘁𝗶𝗼𝗻𝗮𝗹 𝗢𝘂𝘁𝗯𝗼𝘅 𝗣𝗮𝘁𝘁𝗲𝗿𝗻<br>Instead of writing to the database and the message broker separately, we write both pieces of information inside the same database transaction.</p><pre>BEGIN TRANSACTION<br>Insert Order<br>Insert Event into Outbox Table<br>COMMIT</pre><p>𝗪𝗵𝗮𝘁 𝗵𝗮𝗽𝗽𝗲𝗻𝘀 𝗻𝗲𝘅𝘁?<br>A background worker reads the Outbox table and publishes events to a message broker like Kafka.<br>𝗢𝗿𝗱𝗲𝗿 𝗦𝗲𝗿𝘃𝗶𝗰𝗲 -&gt; 𝗢𝗿𝗱𝗲𝗿 𝗗𝗕 + 𝗢𝘂𝘁𝗯𝗼𝘅 -&gt; 𝗢𝘂𝘁𝗯𝗼𝘅 𝗪𝗼𝗿𝗸𝗲𝗿 -&gt; 𝗠𝗲𝘀𝘀𝗮𝗴𝗲 𝗕𝗿𝗼𝗸𝗲𝗿 -&gt; 𝗜𝗻𝘃𝗲𝗻𝘁𝗼𝗿𝘆 / 𝗣𝗮𝘆𝗺𝗲𝗻𝘁 / 𝗦𝗵𝗶𝗽𝗽𝗶𝗻𝗴</p><p>Even if the worker crashes, the event is still safely stored in the database.<br>No events are lost.</p><p>𝗪𝗵𝘆 𝘁𝗵𝗶𝘀 𝗽𝗮𝘁𝘁𝗲𝗿𝗻 𝘄𝗼𝗿𝗸𝘀 𝘀𝗼 𝘄𝗲𝗹𝗹<br>Databases provide strong guarantees:<br>1. Atomic transactions<br>2. Durability<br>3. Consistency<br>By treating the database as the source of truth, we eliminate the risk of lost events.</p><h4>𝗪𝗵𝗲𝗿𝗲 𝗶𝘀 𝘁𝗵𝗶𝘀 𝗽𝗮𝘁𝘁𝗲𝗿𝗻 𝘂𝘀𝗲𝗱?</h4><p>The Transactional Outbox Pattern is widely used for:<br>1. Event publishing in microservices<br>2. Reliable message delivery to Kafka / queues<br>3. Updating search indexes (Elasticsearch)<br>4. Sending emails or notifications<br>5. Cache invalidation<br>6. Event-driven architectures<br>Anywhere you see a “write to DB + send event” flow, this pattern can help.</p><p>𝗜𝗺𝗽𝗼𝗿𝘁𝗮𝗻𝘁: 𝗧𝗵𝗶𝘀 𝗱𝗼𝗲𝘀 𝗡𝗢𝗧 𝗴𝘂𝗮𝗿𝗮𝗻𝘁𝗲𝗲 𝗲𝘅𝗮𝗰𝘁𝗹𝘆-𝗼𝗻𝗰𝗲 𝗱𝗲𝗹𝗶𝘃𝗲𝗿𝘆<br>Message brokers typically deliver messages at least once.<br>So consumers must still implement:<br>1. Idempotent processing<br>2. Deduplication<br>3. Retry handling</p><p>𝗜𝗻 𝗽𝗿𝗮𝗰𝘁𝗶𝗰𝗲, 𝗿𝗼𝗯𝘂𝘀𝘁 𝘀𝘆𝘀𝘁𝗲𝗺𝘀 𝗰𝗼𝗺𝗯𝗶𝗻𝗲:<br>Transactional Outbox + Message Broker + Idempotent Consumers + Retries / DLQ<br>This is how modern distributed systems achieve reliable event-driven communication.</p><h4>𝗖𝗼𝗻𝗰𝗹𝘂𝘀𝗶𝗼𝗻:</h4><p><strong>The Transactional Outbox Pattern solves a deceptively simple but dangerous problem by making the database transaction the single source of truth, we remove the risk of losing critical events.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1782a6220a96" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Future is Agentic: Build Your Autonomous AI Assistant]]></title>
            <link>https://gauravsingh9356.medium.com/the-future-is-agentic-build-your-autonomous-ai-assistant-cc4d4713ad01?source=rss-bea6446d2d53------2</link>
            <guid isPermaLink="false">https://medium.com/p/cc4d4713ad01</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[GauravSingh9356]]></dc:creator>
            <pubDate>Sun, 04 Jan 2026 14:36:43 GMT</pubDate>
            <atom:updated>2026-01-04T14:47:21.172Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PuTphxwG7MJ2fl8uMK3TeA.png" /></figure><p>We’ve all read a lot about <strong>LLMs</strong>, <strong>Agents</strong>, <strong>tools</strong>, and the next big thing in AI.<br> Honestly, for a long time, none of this really <em>clicked</em> for me.</p><p>First, it was LLMs.<br> Then suddenly… <em>Agents</em>.</p><p>And my reaction was very real:</p><blockquote><em>“Wait… what is this now?”</em></blockquote><p>Is this just another buzzword?<br> Or is there actually something new and useful here?</p><p>This post is my attempt to <strong>make sense of Agents by building one</strong>, end to end, for a very real and very boring problem:<br> <strong>my daily life</strong>.</p><h3>Let’s start simple: What exactly is an Agent?</h3><p>Here’s the simplest explanation that finally worked for me:</p><blockquote><strong><em>An Agent is just an LLM that can take actions.</em></strong></blockquote><p>That’s it.</p><p>Nothing mystical.</p><p>We already know what an LLM is:</p><ul><li>A large transformer model</li><li>Trained on massive amounts of data</li><li>Very good at understanding language</li><li>Very good at reasoning and decision-making</li></ul><p>But by default, an LLM can only <strong>talk</strong>.</p><p>It can tell you <em>what</em> to do, but it can’t actually <strong>do</strong> anything.</p><p>And that’s where the idea of Agents becomes interesting.</p><h3>Why plain LLMs feel limited</h3><p>Think about how we usually interact with LLMs.</p><p>You ask:</p><blockquote><em>“What meetings do I have today?”</em></blockquote><p>The LLM replies:</p><blockquote><em>“You should check your calendar.”</em></blockquote><p>That’s… helpful, but not very powerful.</p><p>The LLM clearly understands:</p><ul><li>Your intent</li><li>What information is needed</li><li>What action should be taken</li></ul><p>But it can’t <strong>access your calendar</strong>.<br> It can’t <strong>fetch real-time data</strong>.<br> It can’t <strong>modify anything</strong>.</p><p>So the real question becomes:</p><blockquote><em>If LLMs are already good at deciding </em>what<em> to do,<br> why not let them actually </em>do it<em>?</em></blockquote><h3>Enter Actions (the missing piece)</h3><p>An <strong>action</strong> is just a function.</p><p>Nothing fancy.</p><p>Examples:</p><ul><li>Call a Google Calendar API</li><li>Fetch today’s date</li><li>Search the web</li><li>Create or cancel a meeting</li><li>Query a database</li></ul><p>So when people say:</p><blockquote><em>“Agents are LLMs with actions”</em></blockquote><p>What they really mean is:</p><blockquote><em>“LLMs that are allowed to call functions when needed.”</em></blockquote><p>And suddenly, everything makes sense.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2TN95vkADUWiq6IZUfgcWQ.png" /><figcaption>High Level Design — Agentic AI</figcaption></figure><h3>The moment it clicked for me</h3><p>At some point, I reframed the whole thing like this:</p><ul><li>The <strong>LLM</strong> is the brain</li><li>The <strong>tools/actions</strong> are the hands</li><li>The <strong>agent framework</strong> is the nervous system connecting them</li></ul><p>The LLM decides:</p><ul><li>“I need calendar data”</li><li>“I need real-time information”</li><li>“I should create or cancel an event”</li></ul><p>The system then:</p><ul><li>Executes the action</li><li>Feeds the result back to the LLM</li><li>Lets the LLM continue reasoning</li></ul><p>That feedback loop is what makes it feel <em>alive</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4w3jkZqIcXSTt_06y8C5SA.png" /><figcaption>AI Agent Decision Loop</figcaption></figure><h3>So… can we build our own Agent?</h3><p>That question bothered me enough that I decided to try.</p><p>Not a demo.<br> Not a toy.<br> Not a notebook experiment.</p><p>I wanted something that:</p><ul><li>I could actually use</li><li>Felt like Siri / ChatGPT</li><li>Did real things for me</li></ul><p>So I decided to build a <strong>personal agentic AI assistant</strong> from scratch.</p><h3>What problem was I trying to solve?</h3><p>Very simple daily frustrations:</p><ul><li>Checking meetings</li><li>Creating or canceling calendar events</li><li>Asking questions that require <strong>real-time information</strong></li><li>Talking to my assistant instead of typing commands</li><li>Having it remember context like modern AI systems do</li></ul><p>Basically:</p><blockquote><em>“Can I build my own JARVIS?”</em></blockquote><h3>Defining the functional requirements</h3><p>Before writing any code, I forced myself to be very clear about what the system should do.</p><h3>1. Voice-first interaction</h3><p>I didn’t want another chat box.</p><p>I wanted to:</p><ul><li>Speak to it</li><li>Hear responses back</li><li>Interact naturally, like a real assistant</li></ul><h3>2. Real-time information</h3><p>LLMs don’t know:</p><ul><li>Today’s date</li><li>Current weather</li><li>Live events</li></ul><p>So the system must be able to <strong>search the web</strong> when needed.</p><h3>3. Personal system integration</h3><p>This was non-negotiable.</p><p>The agent should:</p><ul><li>Read my Google Calendar</li><li>Create meetings</li><li>Cancel meetings</li><li>Understand names, dates, and intent</li></ul><h3>4. Memory and continuity</h3><p>Modern AI systems don’t feel stateless.</p><p>If I say:</p><blockquote><em>“Cancel my meeting with Gaurav”</em></blockquote><p>I don’t want to explain everything again.</p><p>The system should:</p><ul><li>Remember context</li><li>Track conversation history</li><li>Behave like a single continuous assistant</li></ul><h3>High-level architecture (in plain English)</h3><p>Here’s how the system works conceptually:</p><ol><li>I speak or type a command in the UI</li><li>The frontend sends the text to the backend</li><li>The backend passes it to an LLM</li><li>The LLM decides:</li></ol><ul><li>“I can answer directly”</li><li>or “I need to use a tool”</li></ul><p>If a tool is needed:</p><ul><li>The system executes it</li><li>Feeds the result back to the LLM</li></ul><p>5. The LLM generates a final response</p><p>6. The UI displays it and speaks it out loud</p><p>No magic.<br> Just a very clean feedback loop.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nTFGdYrxhbesX_J__95FfQ.png" /><figcaption>Full end to end flow</figcaption></figure><h3>Why this feels different from a normal chatbot</h3><p>The key difference is <strong>agency</strong>.</p><p>The LLM is no longer just responding.<br> It is:</p><ul><li>Interpreting intent</li><li>Choosing actions</li><li>Executing side effects</li><li>Verifying results</li><li>Responding in natural language</li></ul><p>That’s when it stops feeling like a chatbot<br> and starts feeling like an assistant.</p><h3>What surprised me the most</h3><p>A few unexpected lessons:</p><ul><li>The <strong>LLM logic was the simplest part</strong></li><li>The hardest parts were:</li><li>Voice UX</li><li>Output formatting</li><li>Making responses sound human</li><li>Once actions are added, LLMs feel <em>much</em> smarter</li><li>Prompt discipline matters more than model size</li></ul><p>Most importantly:</p><blockquote><em>Agents are not about smarter models.<br> They are about </em><strong><em>better system design</em></strong><em>.</em></blockquote><h3>High-Level Design: What Does It Actually Take to Build an Agent?</h3><p>Before getting lost in frameworks and buzzwords, I tried to answer one simple question:</p><blockquote>What are the minimum building blocks required to make an AI assistant that actually works end to end?</blockquote><p>Surprisingly, the answer is not “a lot of ML magic”, but <strong>a well-thought-out system design</strong>.</p><p>At a high level, the system breaks down into five major layers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BmF1NKZat4qD7DCRQBlQZg.png" /><figcaption>End to End Personal Agentic AI</figcaption></figure><h3>1. Frontend: Where Humans Talk to the Agent</h3><p>This is the only part the user ever sees, so it matters a lot.</p><h3>Responsibilities</h3><ul><li>Capture <strong>voice input</strong> from the user</li><li>Allow <strong>text input</strong> as a fallback</li><li>Display the agent’s responses in a readable timeline</li><li>Speak responses back using text-to-speech</li><li>Maintain a smooth, conversational experience (auto-scroll, status updates, etc.)</li></ul><h3>Technologies Used</h3><ul><li>HTML + Tailwind CSS for a clean, agentic UI</li><li>Browser Speech Recognition API for voice input</li><li>Browser Speech Synthesis API for voice output</li><li>Plain JavaScript (no heavy frameworks)</li></ul><p>Why keep it simple?<br> Because the frontend’s job is not to be smart — it’s to <strong>get out of the way</strong>.</p><h3>2. Backend API: The Glue Layer</h3><p>The backend is the bridge between the UI and the intelligence.</p><h3>Responsibilities</h3><ul><li>Accept user input (text or voice-transcribed)</li><li>Maintain a unique conversation thread per user</li><li>Forward requests to the agent orchestration layer</li><li>Return the final response back to the UI</li></ul><h3>Technologies Used</h3><ul><li>Node.js</li><li>Express.js</li><li>Simple REST endpoint (POST /)</li></ul><p>This layer is intentionally thin.<br> It doesn’t reason, decide, or interpret — it just <strong>routes information correctly</strong>.</p><h3>3. Agent Orchestration: The Brain’s Nervous System</h3><p>This is where things get interesting.</p><p>A single LLM call is not enough to build an agent.<br> You need something that can:</p><ul><li>Maintain state</li><li>Loop between reasoning and actions</li><li>Decide when to stop</li></ul><h3>Responsibilities</h3><ul><li>Store conversation memory per thread</li><li>Pass messages between the LLM and tools</li><li>Decide whether the agent should:</li><li>Respond directly</li><li>Or invoke a tool and continue reasoning</li></ul><h3>Technologies Used</h3><ul><li>LangGraph (StateGraph)</li><li>MemorySaver for thread-level memory</li><li>ToolNode for executing actions</li></ul><p>This layer is what transforms an LLM from a chatbot into an <strong>agent</strong>.</p><h3>4. LLM: Reasoning and Decision Making</h3><p>The LLM is responsible for <strong>thinking</strong>, not doing.</p><h3>Responsibilities</h3><ul><li>Understand user intent</li><li>Decide whether a tool is required</li><li>Interpret tool results</li><li>Generate clear, human-friendly responses</li></ul><h3>Technologies Used</h3><ul><li>ChatGroq</li><li>Model: openai/gpt-oss-120b</li><li>Deterministic configuration (temperature = 0)</li></ul><p>A critical design choice here was <strong>prompt discipline</strong>.</p><p>The system prompt strictly enforces:</p><ul><li>Plain English output</li><li>No markdown</li><li>No tables or formatting</li><li>Voice-friendly responses</li></ul><p>This dramatically simplifies the frontend and improves voice quality.</p><h3>5. Tools: Giving the Agent Hands</h3><p>Tools are what make the system <em>useful</em>.</p><p>Each tool is just a function, but together they give the agent real-world power.</p><h3>Core Tools Implemented</h3><ul><li>Web Search tool for real-time information</li><li>Calendar read tool to fetch events</li><li>Calendar create tool to schedule meetings</li><li>Calendar cancel tool to remove meetings by name and date</li></ul><h3>Technologies Used</h3><ul><li>Google Calendar API</li><li>External web search APIs</li><li>LangChain tool abstractions</li></ul><p>The key idea:</p><blockquote><em>The LLM decides </em>when<em> to use a tool,<br> but the system controls </em>how<em> the tool is executed.</em></blockquote><h3>Putting It All Together</h3><p>If we zoom out, the entire system looks like this:</p><ul><li>Frontend handles <strong>interaction</strong></li><li>Backend handles <strong>routing</strong></li><li>Agent orchestrator handles <strong>state and flow</strong></li><li>LLM handles <strong>reasoning</strong></li><li>Tools handle <strong>side effects</strong></li></ul><p>Each layer does one job well.</p><p>And when they work together, you get something that feels surprisingly close to a real assistant.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s_mVXVHIzY8WBfTbtJbD4Q.png" /><figcaption>Full Scalable Agentic AI system</figcaption></figure><h3>Why This Design Scales</h3><p>What I like most about this architecture is that it scales naturally.</p><ul><li>Want to add email support? Add a tool.</li><li>Want reminders? Add a tool.</li><li>Want WhatsApp or mobile UI? Swap the frontend.</li><li>Want a different model? Swap the LLM.</li></ul><p>The core agent logic stays the same.</p><p>That’s when you realize:</p><blockquote><em>Agents are less about AI<br> and more about </em><strong><em>clean system boundaries</em></strong><em>.</em></blockquote><h3>Final thoughts</h3><p>If you’re confused about Agents, you’re not alone.<br> I was too.</p><p>The mental model that finally worked for me was:</p><blockquote><strong><em>Agents = LLM + Actions + Memory + Feedback Loop</em></strong></blockquote><p>Once you see it that way, everything else is just engineering.</p><p>And the best way to understand it is not to read another blog post — <br> it’s to build one yourself.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cc4d4713ad01" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scaling the Data Layer in Distributed Systems]]></title>
            <link>https://gauravsingh9356.medium.com/scaling-the-data-layer-in-distributed-systems-ecd585668b0c?source=rss-bea6446d2d53------2</link>
            <guid isPermaLink="false">https://medium.com/p/ecd585668b0c</guid>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <dc:creator><![CDATA[GauravSingh9356]]></dc:creator>
            <pubDate>Thu, 18 Dec 2025 18:47:53 GMT</pubDate>
            <atom:updated>2025-12-18T18:47:53.666Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vn-Sj4_3cadp0hFVXBzSSA.png" /><figcaption>Scaling Data layer of Distributed Systems</figcaption></figure><p>Scaling a <strong>stateless</strong> system is relatively straightforward. We can horizontally scale application servers by adding more instances behind a load balancer, and the system continues to work as expected.</p><p>But what happens to the <strong>database</strong>?</p><p>How can a database running on a single machine handle requests coming from <strong>N horizontally scaled application servers</strong>? Databases must scale too — and this is where things get interesting.</p><h3>The First Idea: Replication</h3><p>A natural first thought is:</p><blockquote><em>“Let’s just replicate the database and create multiple copies.”</em></blockquote><p>At first glance, this sounds reasonable. But the moment we try to scale traditional <strong>SQL databases</strong> using replication, we run into fundamental constraints.</p><h3>Why SQL Databases Don’t Scale Easily</h3><p>SQL databases are built around powerful guarantees:</p><ul><li>Joins across tables</li><li>Cross-row and multi-table transactions</li><li>Global constraints (foreign keys, unique keys, auto-increment IDs)</li></ul><p>All of these assume one critical thing:</p><blockquote><strong><em>All data lives in one logical place.</em></strong></blockquote><p>Once we attempt to shard or distribute SQL data:</p><ul><li>Joins turn into cross-network calls</li><li>Transactions span machines</li><li>Locks stop working globally</li></ul><p>As a result:</p><ul><li>Complexity explodes</li><li>Performance degrades</li><li>Application logic becomes significantly more complex</li></ul><p>This doesn’t mean SQL <em>cannot</em> be sharded — it can — but doing so safely requires heavy coordination and careful design.</p><h3>The Leader–Follower Model</h3><p>To improve scalability, many systems move to a <strong>leader–follower replication model</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0FotP0oZ_zI4eOn6PHCUYg.png" /><figcaption>Leader Follower Replication Model</figcaption></figure><h3>How It Works</h3><ul><li>A <strong>single leader (primary)</strong> accepts all writes</li><li><strong>Followers (replicas)</strong> copy data from the leader</li><li>Reads may be served from followers to scale read traffic</li></ul><p>This gives us:</p><ul><li>One source of truth for writes</li><li>Multiple copies for read scaling and fault tolerance</li></ul><p>But a key question remains:</p><blockquote><strong><em>How does the leader propagate writes to followers?</em></strong></blockquote><p>The answer lies in <strong>replication strategies</strong>.</p><h3>Replication Strategies in Leader–Follower Systems</h3><h3>1. Strong Consistency (Synchronous Replication)</h3><p>In this model:</p><ul><li>The leader writes data locally</li><li>The leader waits for acknowledgements from a <strong>quorum (majority)</strong> of replicas</li><li>Only then does it respond to the client</li></ul><p>This ensures:</p><ul><li>Strong consistency</li><li>No stale reads (when reads also use quorum or leader)</li></ul><p>Tradeoffs:</p><ul><li>Higher write latency</li><li>Reduced availability if replicas are slow or unavailable</li></ul><blockquote><em>Importantly, strong consistency does </em><strong><em>not</em></strong><em> require waiting for </em>all<em> followers — waiting for a </em><strong><em>majority</em></strong><em> is sufficient.</em></blockquote><h3>2. Eventual Consistency (Asynchronous Replication)</h3><p>Here:</p><ul><li>The leader writes data locally</li><li>It sends replication messages to followers</li><li>It responds to the client <strong>without waiting</strong> for most acknowledgements</li></ul><p>This model:</p><ul><li>Improves write latency and throughput</li><li>Allows reads from followers to return stale data temporarily</li><li>Relies on the system eventually converging</li></ul><p>This is a deliberate tradeoff:</p><blockquote><strong><em>Availability and performance over immediate consistency</em></strong></blockquote><h3>The Leader Bottleneck Problem</h3><p>Even with replication, a fundamental limitation remains:</p><blockquote><strong><em>All writes still go through a single leader.</em></strong></blockquote><p>As write QPS grows (e.g., 10K+ writes per second):</p><ul><li>The leader becomes a bottleneck</li><li>CPU, I/O, and replication overhead increase</li><li>Vertical scaling eventually hits limits</li></ul><p>At this point, simply adding more replicas doesn’t help — because replicas don’t accept writes.</p><p>This is where <strong>partitioning (sharding)</strong> becomes necessary.</p><h3>The Entry of NoSQL</h3><p>NoSQL databases emerged to solve exactly this problem:<br> <strong>scaling writes and reads horizontally at massive scale</strong>.</p><p>Key motivations behind NoSQL systems:</p><ul><li>High write throughput</li><li>High availability</li><li>Fault tolerance</li><li>Geo-distribution</li><li>Low latency at scale</li></ul><p>Rather than optimizing purely for normalization and storage efficiency, NoSQL systems are designed to scale <strong>by default</strong>.</p><h3>Sharding in NoSQL Databases</h3><p>NoSQL databases distribute data using <strong>sharding</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x2LL1UpzCawkT-G2D6eeMw.png" /><figcaption>NoSQL Sharding Architecture</figcaption></figure><h3>How Sharding Works</h3><ol><li>A <strong>partition (shard) key</strong> is chosen (e.g., user_id)</li><li>The key is hashed or range-mapped</li><li>Data is distributed across shards</li><li>Each shard owns a <strong>mutually exclusive subset of data</strong></li></ol><p>Common partitioning strategies:</p><ul><li>Consistent hashing</li><li>Range-based partitioning (A–G, H–M, etc.)</li></ul><p>Choosing the correct shard key is critical:</p><blockquote><em>A poor shard key can cause hotspots and destroy scalability.</em></blockquote><h3>Replication Inside a Shard</h3><p>Each shard is still replicated for fault tolerance.<br> This is where <strong>two NoSQL replication models</strong> appear.</p><h3>Model 1: Leader–Follower per Shard</h3><p>Used by systems like:</p><ul><li>MongoDB</li><li>DynamoDB</li><li>HBase</li></ul><h3>Per Shard:</h3><ul><li>One leader</li><li>Multiple followers</li></ul><h3>Write Flow:</h3><ol><li>Client routes request to shard leader</li><li>Leader writes data</li><li>Leader propagates to followers</li><li>Leader waits for:</li></ol><ul><li>Quorum acknowledgements (stronger consistency), or</li><li>Minimal acknowledgements (eventual consistency)</li></ul><h3>Read Flow:</h3><ul><li>Reads may go to leader (fresh)</li><li>Or followers (faster, possibly stale)</li></ul><p>This model is simple and efficient but still has:</p><ul><li>Leader hotspots</li><li>Leader failover complexity</li></ul><h3>Model 2: Quorum-Based (Leaderless) Replication</h3><p>Used by systems like:</p><ul><li>Cassandra</li><li>Riak</li><li>Dynamo-style designs</li></ul><h3>Per Shard:</h3><ul><li>No leader</li><li>All replicas are equal</li></ul><h3>Write Flow:</h3><ol><li>Client sends write to any replica (coordinator)</li><li>Coordinator sends write to all replicas</li><li>Write succeeds when <strong>W replicas acknowledge</strong></li></ol><h3>Read Flow:</h3><ol><li>Client reads from <strong>R replicas</strong></li><li>Latest version wins</li><li>Inconsistencies are repaired in the background</li></ol><p>This model:</p><ul><li>Avoids leader bottlenecks</li><li>Improves availability</li><li>Requires conflict resolution and versioning</li></ul><h3>Quorum Explained (Simply)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XqnL2zp1r5WhgcR1aN2_hw.png" /><figcaption>NoSQL Quorum</figcaption></figure><p>Let:</p><ul><li><strong>N</strong> = total replicas per shard</li><li><strong>W</strong> = replicas required to acknowledge a write</li><li><strong>R</strong> = replicas required for a read</li></ul><p>Rules:</p><ul><li><strong>Strong consistency</strong>: R + W &gt; N</li><li><strong>Eventual consistency</strong>: R + W ≤ N</li></ul><p>Examples:</p><ul><li>Banking, inventory → strong consistency</li><li>Social feeds, likes, analytics → eventual consistency</li></ul><p>Quorum decisions are made <strong>per shard</strong>, not globally.</p><h3>Final Takeaway</h3><ul><li>SQL databases struggle with horizontal write scaling due to strong global guarantees</li><li>Leader–follower replication improves read scaling but not write scaling</li><li>NoSQL databases solve this by <strong>sharding data ownership</strong></li><li>Each shard scales independently</li><li>Replication within shards is handled using leader-based or quorum-based models</li><li>Consistency is a <strong>configurable tradeoff</strong>, not a fixed property</li></ul><blockquote><strong><em>Modern data systems don’t ask “Can we scale?” — they ask “What consistency are we willing to trade for scale?”</em></strong></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ecd585668b0c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Evolution of AI: Unpacking LLMs, Agents, and MCP Servers]]></title>
            <link>https://gauravsingh9356.medium.com/the-evolution-of-ai-unpacking-llms-agents-and-mcp-servers-c58c736f97e8?source=rss-bea6446d2d53------2</link>
            <guid isPermaLink="false">https://medium.com/p/c58c736f97e8</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[openai]]></category>
            <dc:creator><![CDATA[GauravSingh9356]]></dc:creator>
            <pubDate>Sun, 14 Sep 2025 16:39:36 GMT</pubDate>
            <atom:updated>2025-09-14T16:39:36.219Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uHfJ_ZN6jJxVm2QjYQj-Eg.png" /></figure><h3>Are we on the brink of an AI revolution that could redefine human–computer interaction?</h3><p>From chatbots that simplify customer service to advanced virtual assistants that understand our needs, it’s clear that artificial intelligence is evolving at an unprecedented pace. Central to this transformation are Large Language Models (LLMs), AI Agents, and Model Context Protocol (MCP) Servers — three pillars that define the current AI landscape.</p><h3>Origin and Research Background:</h3><p>The inception of LLMs can be traced back to foundational research in natural language processing (NLP) and machine learning. The groundbreaking transformer architecture introduced by <em>Vaswani et al. in 2017</em> has been a game-changer, enabling models to understand and generate text with remarkable fluency. These models are designed to predict the next word in a sentence, drawing insights from vast datasets containing billions of words.</p><h3>Training and Creation:</h3><p>Creating an LLM involves a two-step process: <em>pre-training</em> and <em>fine-tuning</em>. During pre-training, the model learns language structure using massive datasets from books, websites, and other textual sources. Fine-tuning involves training the model on specific datasets tailored to particular tasks, enhancing its ability to provide relevant and context-aware responses.</p><h3>Current Capabilities and Limitations:</h3><p>Today, LLMs exhibit astonishing abilities — they can write essays, answer complex queries, and even create poetry. However, they still have limitations: they can generate plausible-sounding but factually incorrect information, misunderstand nuanced commands, and struggle with reasoning beyond surface-level understanding. The lack of common sense and contextual awareness means they often require human oversight.</p><h3>🤖 Understanding AI Agents</h3><h3>What Are AI Agents?</h3><p>AI Agents are programs designed to perform tasks autonomously, making decisions based on the data they’re trained on. They can be embedded in various applications, enhancing functionality and user interaction. Think of them as the <em>“doers”</em> in the AI ecosystem.</p><h3>How They Work ?</h3><p>AI Agents can chain tasks together to complete more complex workflows. By utilizing techniques like reinforcement learning, they can learn from their actions and adjust their strategies accordingly. For example, an AI Agent might analyze data, generate insights with an LLM, and then create a report — all without human intervention.</p><h3>Why They Matter</h3><p>The rise of AI Agents is crucial for the future of AI, as they streamline processes, improve efficiency, and allow for more personalized user experiences. Their adaptability makes them invaluable in sectors like healthcare, finance, and customer service, where rapid decision-making is essential.</p><h3>🔗 Introducing MCP Servers (Model Context Protocol)</h3><h3>What Are MCP Servers?</h3><p>MCP Servers serve as the communication backbone between LLMs, tools, and external systems. They manage context, maintaining coherence during interactions and ensuring that decisions made by AI are relevant and contextually appropriate.</p><h3>How They Enable Interaction</h3><p>By acting as intermediaries, MCP Servers facilitate seamless interactions between various AI components. For instance, they can help an LLM provide user-specific responses while integrating data from other applications and systems. This synergy elevates the capabilities of AI by ensuring that it utilizes up-to-date and contextually relevant information.</p><h3>🔄 The Intricate Web of Integration</h3><h3>How LLMs + Agents + MCP Servers Work Together</h3><p>When LLMs, AI Agents, and MCP Servers collaborate, they create a powerful ecosystem. Imagine a virtual assistant powered by an LLM that uses an AI Agent to book appointments and an MCP Server to synchronize data across different platforms. This integration streamlines workflows, enhances user experience, and reduces operational overhead.</p><h3>Real-World Examples of Collaboration</h3><p>Consider a customer service application where an AI Agent utilizes an LLM for conversation and an MCP Server to pull in user data from the company’s CRM. This collaborative effort allows the AI to offer personalized assistance, address inquiries promptly, and ultimately improve customer satisfaction.</p><h3>🌍 Current State of AI: Progress and Challenges</h3><h3>Where We Are Today ?</h3><p>The AI landscape is vibrant and rapidly evolving. Companies are increasingly leveraging these technologies to innovate, improve efficiency, and drive growth. LLMs have become prevalent in various applications, while AI Agents are enhancing the capabilities of existing software solutions.</p><h3>Key Challenges</h3><p>However, this progress is accompanied by challenges. Scaling these systems while maintaining quality and effectiveness presents a hurdle. Moreover, issues surrounding reasoning, alignment with user intentions, and safety concerns need focused attention to build trust in AI technologies.</p><h3>Future Directions &amp; Opportunities</h3><p>As we look to the future, there are exciting opportunities for growth in this domain. Advancements in AI ethics, better alignment techniques, and enhancing reasoning capabilities will be pivotal in ensuring that AI serves humanity responsibly. Furthermore, ongoing research into hybrid models that combine different AI approaches may lead us to breakthroughs we can only imagine today.</p><h3>🧭 Conclusion</h3><p>The rapid evolution of Large Language Models, Agent technologies, and MCP Servers is reshaping how we interact with technology. By understanding their dynamics and interplay, we can harness their potential to drive innovation and empower users.</p><p>Read this Far ? Do share your thoughts about it. Would love to hear!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c58c736f97e8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Rate Limiting in Distributed System — Deep Dive]]></title>
            <link>https://gauravsingh9356.medium.com/rate-limiting-in-distributed-system-deep-dive-386b2913901f?source=rss-bea6446d2d53------2</link>
            <guid isPermaLink="false">https://medium.com/p/386b2913901f</guid>
            <category><![CDATA[amazon]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[rate-limiting]]></category>
            <dc:creator><![CDATA[GauravSingh9356]]></dc:creator>
            <pubDate>Mon, 18 Aug 2025 07:00:39 GMT</pubDate>
            <atom:updated>2025-08-18T07:00:39.333Z</atom:updated>
            <content:encoded><![CDATA[<h3>Rate Limiting in Distributed System — Deep Dive</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NY9-2JUXg-9cQQcjjPZypg.png" /></figure><p>If you’ve ever built an API that went public, you’ve probably asked yourself:</p><blockquote>“What happens if someone spams my service with requests?”</blockquote><p>That’s where rate limiting comes in.</p><p>In this article, we’ll explore how rate limiting works, why it’s tricky in distributed systems, and how Redis helps us solve those nasty race conditions. I’ll also walk you through common algorithms like Token Bucket, Fixed Window, and Sliding Window, in plain English.</p><h3>💡 What is Rate Limiting?</h3><p>Think of rate limiting like a bouncer at a nightclub.</p><ul><li>Every customer (user or IP address) wants to get in (make requests).</li><li>The bouncer only allows a certain number of people in every minute.</li><li>If the limit is hit → the bouncer says <em>“wait outside”</em> (returns HTTP 429).</li></ul><p>Why is this important?</p><ul><li>Protect your system from abuse.</li><li>Prevent denial-of-service.</li><li>Ensure fairness across users.</li><li>Save your backend from being overwhelmed.</li></ul><h3>🖥️ Rate Limiting on a Single Machine</h3><p>If you run only one server, life is simple.</p><p>You can keep an in-memory counter for each user/IP:</p><ul><li>Count how many requests in the last 60 seconds.</li><li>Allow if under the limit. Block if over.</li></ul><p>👉 This works fine until you scale to multiple servers.</p><h3>🌍 The Distributed Problem</h3><p>Imagine you have 3 servers behind a load balancer.</p><ul><li>User A sends requests that go to Server 1, 2, and 3.</li><li>Each server only knows what <em>it</em> saw.</li><li>So the user can bypass limits easily by spraying requests across servers.</li></ul><p>That’s the distributed systems challenge: We need a shared brain that all servers can trust for counting requests.</p><h3>🔑 Enter Redis</h3><p>Redis is a fast, in-memory datastore that’s perfect for this job.</p><p>Why?</p><ul><li>It’s centralized → all servers talk to the same source of truth.</li><li>It’s single-threaded → commands run atomically, no race conditions.</li><li>It has powerful data structures (Counters, Sorted Sets, etc).</li></ul><p>Redis is like the traffic cop of your system:</p><ul><li>All requests go through it.</li><li>It makes sure no two cars pass at the same time.</li><li>It enforces the rules you define.</li></ul><h3>🏗️ Common Rate Limiting Algorithms</h3><p>Let’s break down the 3 most popular ones.</p><h3>1. Fixed Window Counter</h3><p>How it works:</p><ul><li>Keep a counter per time window (e.g., “requests in the last minute”).</li><li>Use Redis INCR and EXPIRE.</li></ul><p>Example:</p><ul><li>Allow 100 requests/minute.</li><li>At 12:00:01, counter starts.</li><li>At 12:01:00, counter resets.</li></ul><p>✅ Super simple. ❌ But at the boundary, a user can send 100 requests at 12:00:59 and another 100 at 12:01:00 → effectively 200 in 2 seconds.</p><h3>2. Token Bucket</h3><p>How it works:</p><ul><li>Imagine a bucket of tokens.</li><li>Each request consumes a token.</li><li>Tokens refill at a fixed rate.</li></ul><p>If the bucket is empty → request denied.</p><p>This keeps traffic smooth over time. Used widely in API gateways and networking.</p><p>✅ Good balance of fairness and performance. ❌ Needs careful refill math.</p><h3>3. Sliding Window (with Redis Sorted Sets)</h3><p>How it works:</p><ul><li>Store a timestamp for each request in a Redis Sorted Set.</li><li>Before allowing a new request:</li></ul><p>✅ Very fair → true per-second limits. ❌ Slightly heavier (stores every request’s timestamp).</p><h3>🔥 The Race Condition Problem (and Solution)</h3><p>Here’s the real challenge:</p><p>If you have multiple servers checking limits at the same time, they might both say <em>“OK, allow”</em> even if the combined total exceeds the limit.</p><p>This is a race condition.</p><p>Redis solves it because:</p><ul><li>Commands like INCR are atomic.</li><li>Even multi-step logic can be wrapped in a transaction or Lua script, which Redis runs without interruption.</li></ul><p>👉 This means no two servers can “sneak in” at the same time. Redis is effectively the referee keeping score in order.</p><h3>🛠️ Which Approach Should You Use?</h3><p>It depends on your use case:</p><ul><li>Fixed Window → if performance matters more than strict fairness (e.g., 1000 requests/minute).</li><li>Token Bucket → if you want to smooth traffic and avoid bursts (e.g., payment API).</li><li>Sliding Window (Sorted Set) → if you want precise per-second fairness (e.g., login brute-force protection).</li></ul><h3>🏗️ High-Level Design of a Distributed Rate Limiter</h3><p>Let’s put everything together and design a production-grade distributed rate limiter.</p><h3>🎯 Goals</h3><ul><li>Limit requests per user/IP or per API.</li><li>Work across multiple servers (distributed).</li><li>Be fast, fair, and reliable.</li><li>Handle race conditions gracefully.</li></ul><h3>🔹 Key Components</h3><ol><li>Clients (Users / Services)</li><li>API Gateway / Load Balancer</li><li>Rate Limiter Service</li><li>Redis (Centralized Store)</li><li>Application Servers</li></ol><h3>🔹 Architecture Diagram (HLD)</h3><pre>┌───────────────┐<br>        │    Clients    │<br>        │ (Users / Apps)│<br>        └───────┬───────┘<br>                │<br>        ┌───────▼────────┐<br>        │ API Gateway /  │<br>        │ Load Balancer  │<br>        └───────┬────────┘<br>                │<br>        ┌───────▼─────────┐<br>        │  Rate Limiter   │<br>        │  (Service/Lib)  │<br>        └───┬────────┬────┘<br>            │        │<br> ┌──────────▼─┐   ┌──▼──────────┐<br> │   Redis    │   │ Application │<br> │ (Central   │   │   Servers   │<br> │   Store)   │   │             │<br> └────────────┘   └─────────────┘</pre><h3>🔹 Workflow</h3><ol><li>Client sends request → Gateway routes it to a server.</li><li>Server calls Rate Limiter Service with:</li><li>Rate Limiter queries Redis:</li><li>If limit exceeded → request blocked (429). Else → request proceeds to backend.</li></ol><h3>🔹 Example Redis Key Design</h3><p>For per-IP per-API limits:</p><pre>rate_limit:&lt;ip&gt;:&lt;api_endpoint&gt;</pre><p>For user-based limits:</p><pre>rate_limit:user:&lt;userId&gt;</pre><p>Each key tracks counters or tokens depending on the algorithm chosen.</p><h3>🔹 Scaling Considerations</h3><ul><li>Redis Cluster / Sentinel for high availability.</li><li>Local Caching for extremely high-traffic APIs to reduce Redis load.</li><li>Different limits per endpoint (e.g., /login stricter, /feed more lenient).</li><li>Monitoring &amp; Metrics (Prometheus + Grafana dashboards).</li></ul><h3>📌 Key Takeaways</h3><ul><li>Rate limiting is like a bouncer for your API.</li><li>Works fine locally, but in distributed systems you need a shared state.</li><li>Redis is a perfect shared state store because it’s fast and atomic.</li><li>You don’t <em>always</em> need a Sorted Set → pick the algorithm that balances fairness, memory, and performance for your needs.</li></ul><h3>🚀 Final Thoughts</h3><p>Next time you design a distributed system, remember:</p><ul><li>Without a rate limiter, you’re inviting trouble.</li><li>Without Redis (or some centralized store), your limiter is blind.</li><li>With Redis, you can pick your favorite algorithm — and sleep peacefully knowing race conditions won’t break your limits.</li></ul><p><strong>Read this Far ? Please feel free to drop comments regarding your queries or anything. I would love to answer them. ❤️</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=386b2913901f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[       ’ …]]></title>
            <link>https://gauravsingh9356.medium.com/-3e97eefc92ed?source=rss-bea6446d2d53------2</link>
            <guid isPermaLink="false">https://medium.com/p/3e97eefc92ed</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[amazon]]></category>
            <category><![CDATA[faang]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[GauravSingh9356]]></dc:creator>
            <pubDate>Sat, 16 Aug 2025 23:16:49 GMT</pubDate>
            <atom:updated>2025-08-16T23:16:49.615Z</atom:updated>
            <content:encoded><![CDATA[<h3>𝐖𝐡𝐲 𝐉𝐚𝐯𝐚 𝐒𝐡𝐨𝐮𝐥𝐝 𝐁𝐞 𝐨𝐧 𝐄𝐯𝐞𝐫𝐲 𝐂𝐨𝐥𝐥𝐞𝐠𝐞 𝐆𝐫𝐚𝐝𝐮𝐚𝐭𝐞’𝐬 𝐑𝐚𝐝𝐚𝐫 𝐢𝐧 2025 ?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bV69bP43crLzUpNXdIWE-Q.png" /></figure><p>Think Java is “old”? Think again.</p><p>Java isn’t just legacy — it’s the backbone of modern systems, powering everything from mobile apps to global microservices. Here’s why:</p><p>Java, often underestimated, remains a powerhouse in modern technology landscapes, essential for various applications from mobile platforms to global microservices. Here’s why every college student should consider diving into Java now:</p><p>✅ 𝐄𝐧𝐭𝐞𝐫𝐩𝐫𝐢𝐬𝐞 &amp; 𝐁𝐚𝐜𝐤𝐞𝐧𝐝 𝐃𝐨𝐦𝐢𝐧𝐚𝐧𝐜𝐞:<br>- Java is pivotal in critical systems, with 92% of financial institutions relying on it, and 65% already embracing Java 11+.<br>- A significant 65% of backend developers in enterprise environments prefer Java as their primary language.<br>- Major tech players like Gmail, Netflix’s Spring Boot microservices, Amazon, Uber, and Airbnb trust Java for their infrastructure needs.</p><p>✅ 𝐀𝐧𝐝𝐫𝐨𝐢𝐝 𝐚𝐬 𝐚 𝐒𝐭𝐚𝐫𝐭𝐢𝐧𝐠 𝐏𝐨𝐢𝐧𝐭:<br>- Java supports 70% of Android apps and seamlessly integrates with Kotlin, offering control over Android ecosystems even in Kotlin-centric environments.</p><p>✅ 𝐂𝐥𝐨𝐮𝐝-𝐍𝐚𝐭𝐢𝐯𝐞 &amp; 𝐑𝐞𝐚𝐥-𝐓𝐢𝐦𝐞 𝐒𝐲𝐬𝐭𝐞𝐦𝐬:<br>- Java frameworks such as Spring Boot, Micronaut, and Quarkus lead the way in microservices development.<br>- Distributed Java systems like Hadoop, HBase, Storm, and Druid are the backbone of tech giants like Netflix, Airbnb, Alibaba, Uber and <a href="https://www.linkedin.com/search/results/all/?keywords=%23paypal&amp;origin=HASH_TAG_FROM_FEED">PayPal</a>.</p><p>✅ 𝐌𝐚𝐫𝐤𝐞𝐭 𝐒𝐡𝐚𝐫𝐞 &amp; 𝐉𝐨𝐛 𝐃𝐞𝐦𝐚𝐧𝐝:<br>- Java consistently ranks among the top 3 languages on platforms like TIOBE, Stack Overflow, and GitHub.<br>- It powers 5.3% of all server-side websites and almost 14% of top-tier sites, with over 90% of Fortune 500 companies relying on it.<br>- Java skills are in high demand, offering entry-level salaries ranging from $65k–85k and senior roles commanding $130k–160k.</p><p>✅ 𝐅𝐮𝐭𝐮𝐫𝐞-𝐏𝐫𝐨𝐨𝐟 &amp; 𝐕𝐞𝐫𝐬𝐚𝐭𝐢𝐥𝐞:<br>- Java’s platform independence and JVM features enable “write once, run anywhere” functionality.<br>- It seamlessly integrates modern features like multithreading, concurrency, and cloud optimizations, ensuring adaptability to evolving tech landscapes.<br>- With a robust ecosystem including Spring, Tomcat, Hibernate, and a vast community of over 10M+ — means support and opportunity are everywhere</p><p>🎯 𝐖𝐡𝐲 𝐘𝐨𝐮 𝐒𝐡𝐨𝐮𝐥𝐝 𝐒𝐭𝐚𝐫𝐭 𝐉𝐚𝐯𝐚 𝐢𝐧 𝐂𝐨𝐥𝐥𝐞𝐠𝐞<br>✅ Build a strong OOP + DSA foundation — essential for any complex software<br>✅ Hit the ground running in enterprise, Android, or cloud internships<br>✅ Boost your employability — Java skills are sought-after at tech giants and beyond<br>✅ Future-proof your career with a language that evolves, not evaporates</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3e97eefc92ed" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[      :     …]]></title>
            <link>https://gauravsingh9356.medium.com/-699628e8fd18?source=rss-bea6446d2d53------2</link>
            <guid isPermaLink="false">https://medium.com/p/699628e8fd18</guid>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[design]]></category>
            <dc:creator><![CDATA[GauravSingh9356]]></dc:creator>
            <pubDate>Sat, 16 Aug 2025 23:12:36 GMT</pubDate>
            <atom:updated>2025-08-16T23:12:36.226Z</atom:updated>
            <content:encoded><![CDATA[<h3>🚀 𝗙𝗿𝗼𝗺 𝟭 𝗨𝘀𝗲𝗿 𝘁𝗼 𝟭 𝗠𝗶𝗹𝗹𝗶𝗼𝗻: 𝗛𝗼𝘄 𝗪𝗲 𝗦𝗵𝗼𝘂𝗹𝗱 𝗧𝗵𝗶𝗻𝗸 𝗔𝗯𝗼𝘂𝘁 𝗦𝗰𝗮𝗹𝗶𝗻𝗴 𝗦𝘆𝘀𝘁𝗲𝗺𝘀</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*Q6tSz_8bzTEkdqVdRDqjww.jpeg" /><figcaption>Scaling to Million of Users</figcaption></figure><p>Ever thought about how apps like Netflix or Instagram handle millions of users without crashing? The answer isn’t magic — it’s smart, step-by-step scaling.</p><p>𝗛𝗲𝗿𝗲’𝘀 𝗵𝗼𝘄 𝗜 𝗯𝗿𝗲𝗮𝗸 𝗶𝘁 𝗱𝗼𝘄𝗻 𝘄𝗵𝗲𝗻 𝗜’𝗺 𝗱𝗲𝘀𝗶𝗴𝗻𝗶𝗻𝗴 𝗼𝗿 𝘀𝗰𝗮𝗹𝗶𝗻𝗴 𝘀𝘆𝘀𝘁𝗲𝗺𝘀:</p><p>🔹 Start Simple — One server handles everything. Easy to build, easy to deploy.</p><p>🔹 𝗧𝗵𝗲𝗻 𝗨𝘀𝗲𝗿𝘀 𝗙𝗹𝗼𝗼𝗱 𝗜𝗻…<br> Boom! Latency spikes. Downtime risk. Bottlenecks everywhere.<br>💡 That’s when the real fun begins. Time to scale smartly:</p><p>✅ Split Reads and Writes — Avoid overwhelming your database.<br> ✅ Add Load Balancers — Direct traffic like a pro🚦<br> ✅ Introduce Caching — Redis or Memcached to serve hot data in milliseconds<br> ✅ Go Horizontal — Spin up more servers, add DB replicas, and auto-scale.<br> ✅ Use CDNs — Bring content closer to users across the globe 🌍<br> ✅ Queue It Up — Offload heavy work to background jobs.</p><p>A single-server setup handles everything — web requests, database queries, the works. It’s easy to deploy but hits limits fast due to resource constraints (think CPU, memory).</p><p>As users surge, shift to horizontal scaling: Add multiple servers. Here’s the theory — servers become “stateless” (no session data stored locally), allowing a load balancer to distribute traffic evenly (e.g., round-robin or least-connections algorithms). This leverages parallelism, reducing single points of failure.</p><p>Databases are the real bottleneck. Now the CAP theorem (Consistency, Availability, Partition tolerance) — you can’t have all three in distributed systems, so prioritize based on needs (e.g., eventual consistency for social apps). Add sharding to split data across databases</p><p>Don’t forget caching: caches like Redis exploit locality principles (temporal and spatial) to store frequently accessed data in memory, slashing latency by orders of magnitude. Combine with CDNs (Content Delivery Networks) for geo-distributed edge caching, minimizing global latency.</p><p>And for async magic? Message queues (e.g., Kafka) decouple services, handling spikes without crashing</p><p>🎯 𝗧𝗵𝗲 𝗸𝗲𝘆?<br> Build with growth in mind, piece by piece. This mindset has helped me in both real-world projects and interviews — because when systems break, it’s rarely about code. It’s about design.</p><p>📊 Just made a quick sequence diagram to visualize how a request flows through a scaled system. Thought it might help others too:</p><p>📈 And here’s a visual roadmap showing how we scale from one user to millions:</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=699628e8fd18" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>