<?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 Tushar on Medium]]></title>
        <description><![CDATA[Stories by Tushar on Medium]]></description>
        <link>https://medium.com/@khandelwaltushar2002?source=rss-423da887408a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*f1NXuUHmz5nU4m4g</url>
            <title>Stories by Tushar on Medium</title>
            <link>https://medium.com/@khandelwaltushar2002?source=rss-423da887408a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 06:45:54 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@khandelwaltushar2002/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 Video Streaming Platform(Youtube)]]></title>
            <link>https://medium.com/@khandelwaltushar2002/design-video-streaming-platform-youtube-75af6d50433d?source=rss-423da887408a------2</link>
            <guid isPermaLink="false">https://medium.com/p/75af6d50433d</guid>
            <dc:creator><![CDATA[Tushar]]></dc:creator>
            <pubDate>Sat, 03 Jan 2026 11:28:10 GMT</pubDate>
            <atom:updated>2026-01-03T11:28:10.598Z</atom:updated>
            <content:encoded><![CDATA[<p>Designing a video streaming platform is one of the most common — and most interesting — system design problems. Platforms like <strong>YouTube</strong> handle massive uploads, real-time streaming, global traffic, and diverse devices, all while keeping latency low and availability high.</p><p>This article walks through the <strong>end-to-end design</strong> of such a system — from requirements to deep optimizations.</p><h3>Why YouTube?</h3><p>Total number of monthly active users: 2 billion. <br>• Number of videos watched per day: 5 billion. <br>• 73% of US adults use YouTube.<br> • 50 million creators on YouTube. <br>• YouTube’s Ad revenue was $15.1 billion for the full year 2019, up 36% from 2018. <br>• YouTube is responsible for 37% of all mobile internet traffic. • YouTube is available in 80 different languages</p><p><strong>Step 1 — Understand the problem and establish design scope</strong></p><pre>Candidate: What features are important?<br>Interviewer: Ability to upload a video and watch a video.<br>Candidate: What clients do we need to support?<br>Interviewer: Mobile apps, web browsers, and smart TV.<br>Candidate: How many daily active users do we have?<br>Interviewer: 5 million<br>Candidate: What is the average daily time spent on the product?<br>Interviewer: 30 minutes.<br>Candidate: Do we need to support international users?<br>Interviewer: Yes, a large percentage of users are international users.<br>Candidate: What are the supported video resolutions?<br>Interviewer: The system accepts most of the video resolutions and formats.<br>Candidate: Is encryption required?<br>Interviewer: Yes<br>Candidate: Any file size requirement for videos?<br>Interviewer: Our platform focuses on small and medium-sized videos. The maximum<br>allowed video size is 1GB.Candidate: Can we leverage some of the existing cloud infrastructures provided by Amazon,<br>Google, or Microsoft?<br>Interviewer: That is a great question. Building everything from scratch is unrealistic for most<br>companies, it is recommended to leverage some of the existing cloud services.</pre><p>we focus on designing a video streaming service with the following features: <br>• Ability to upload videos fast <br>• Smooth video streaming <br>• Ability to change video quality<br> • Low infrastructure cost <br>• High availability, scalability, and reliability requirements<br>• Clients supported: mobile apps, web browser, and smart TV</p><p><strong>Step 2 — Propose high-level design and get buy-in</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tazu0w-urRgE9CyyBA0qfQ.png" /></figure><p>At the high-level, the system comprises three components</p><pre>Client: You can watch YouTube on your computer, mobile phone, and smartTV.<br>CDN: Videos are stored in CDN. When you press play, a video is streamed from the CDN.<br>API servers: Everything else except video streaming goes through API servers. This includes<br>feed recommendation, generating video upload URL, updating metadata database and cache,<br>user signup, etc.<br>In the question/answer session, the interviewer showed interests in two flows:<br>• Video uploading flow<br>• Video streaming flow</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3GWcLoq_Sd8EwCAq14nXNQ.png" /></figure><pre>It consists of the following components:<br>• User: A user watches YouTube on devices such as a computer, mobile phone, or smart<br>TV.<br>• Load balancer: A load balancer evenly distributes requests among API servers.<br>• API servers: All user requests go through API servers except video streaming.<br>• Metadata DB: Video metadata are stored in Metadata DB. It is sharded and replicated to<br>meet performance and high availability requirements.<br>• Metadata cache: For better performance, video metadata and user objects are cached.<br>• Original storage: A blob storage system is used to store original videos. A quotation in<br>Wikipedia regarding blob storage shows that: “A Binary Large Object (BLOB) is a<br>collection of binary data stored as a single entity in a database management system” [6].<br>• Transcoding servers: Video transcoding is also called video encoding. It is the process of<br>converting a video format to other formats (MPEG, HLS, etc), which provide the best<br>video streams possible for different devices and bandwidth capabilities.<br>Transcoded storage: It is a blob storage that stores transcoded video files.<br>• CDN: Videos are cached in CDN. When you click the play button, a video is streamed<br>from the CDN.<br>• Completion queue: It is a message queue that stores information about video transcoding<br>completion events.<br>• Completion handler: This consists of a list of workers that pull event data from the<br>completion queue and update metadata cache and database.<br>Now that we understand each component individually, let us examine how the video<br>uploading flow works. The flow is broken down into two processes running in parallel.<br>a. Upload the actual video.<br>b. Update video metadata. Metadata contains information about video URL, size,<br>resolution, format, user info, etc.</pre><p><strong>Step 3 — Design deep dive</strong></p><p>Video transcoding :<br>When you record a video, the device (usually a phone or camera) gives the video file a certain format. If you want the video to be played smoothly on other devices, the video must be encoded into compatible bitrates and formats. Bitrate is the rate at which bits are processed over time. A higher bitrate generally means higher video quality. High bitrate streams need more processing power and fast internet speed. Video transcoding is important for the following reasons:<br> • Raw video consumes large amounts of storage space. An hour-long high definition video recorded at 60 frames per second can take up a few hundred GB of space. <br>• Many devices and browsers only support certain types of video formats. Thus, it is important to encode a video to different formats for compatibility reasons. <br>• To ensure users watch high-quality videos while maintaining smooth playback, it is a good idea to deliver higher resolution video to users who have high network bandwidth and lower resolution video to users who have low bandwidth. <br>• Network conditions can change, especially on mobile devices. To ensure a video is played continuously, switching video quality automatically or manually based on network conditions is essential for smooth user experience.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zAJoyb5WkHEXb6e41zAf7w.png" /></figure><p><strong>Directed acyclic graph (DAG) model </strong>Transcoding a video is computationally expensive and time-consuming. Besides, different content creators may have different video processing requirements. For instance, some content creators require watermarks on top of their videos, some provide thumbnail images themselves, and some upload high definition videos, whereas others do not.<br>To support different video processing pipelines and maintain high parallelism, it is important to add some level of abstraction and let client programmers define what tasks to execute. For example, Facebook’s streaming video engine uses a directed acyclic graph (DAG) programming model, which defines tasks in stages so they can be executed sequentially or parallelly [8]. In our design, we adopt a similar DAG model to achieve flexibility and parallelism. Figure 14–8 represents a DAG for video transcoding.</p><p><strong>Video transcoding architecture <br></strong>The proposed video transcoding architecture that leverages the cloud services, is shown in Figure 14–10. The architecture has six main components: preprocessor, DAG scheduler, resource manager, task workers, temporary storage, and encoded video as the output. Let us take a close look at each component. <br>Preprocessor:<br>The preprocessor has 4 responsibilities: 1. Video splitting. Video stream is split or further split into smaller Group of Pictures (GOP) alignment. GOP is a group/chunk of frames arranged in a specific order. Each chunk is an independently playable unit, usually a few seconds in length. <br>2. Some old mobile devices or browsers might not support video splitting. Preprocessor split videos by GOP alignment for old clients. <br>3. DAG generation. The processor generates DAG based on configuration files client programmers write. is a simplified DAG representation which has 2 nodes and 1 edge: This DAG representation is generated from the two configuration files below <br>4. Cache data. The preprocessor is a cache for segmented videos. For better reliability, the preprocessor stores GOPs and metadata in temporary storage. If video encoding fails, the system could use persisted data for retry operations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VKWI2ELSjjUxW5IjDdzE1w.png" /></figure><p><strong>System optimizations</strong> <br>At this point, you ought to have good understanding about the video uploading flow, video streaming flow and video transcoding. Next, we will refine the system with optimizations, including speed, safety, and cost-saving. Speed optimization: parallelize video uploading Uploading a video as a whole unit is inefficient. We can split a video into smaller chunks by GOP alignment <br>This allows fast resumable uploads when the previous upload failed. The job of splitting a video file by GOP can be implemented by the client to improve the upload speed . Speed optimization: place upload centers close to users Another way to improve the upload speed is by setting up multiple upload centers</p><h3>Thankyou for Reading!!!</h3><h3>If you found it valuable, hit a like ❤️ and consider subscribing for more such content every week.!!!</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=75af6d50433d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Google Drive System Design]]></title>
            <link>https://medium.com/@khandelwaltushar2002/google-drive-system-design-b3fea324a816?source=rss-423da887408a------2</link>
            <guid isPermaLink="false">https://medium.com/p/b3fea324a816</guid>
            <dc:creator><![CDATA[Tushar]]></dc:creator>
            <pubDate>Fri, 02 Jan 2026 02:38:03 GMT</pubDate>
            <atom:updated>2026-01-02T02:38:03.596Z</atom:updated>
            <content:encoded><![CDATA[<p>Google Drive is a file storage and synchronization service that helps you store documents, photos, videos, and other files in the cloud</p><p>Candidate: What are the most important features? Interviewer: Upload and download files, file sync, and notifications. Candidate: Is this a mobile app, a web app, or both? Interviewer: Both. Candidate: What are the supported file formats? Interviewer: Any file type. Candidate: Do files need to be encrypted? Interview: Yes, files in the storage must be encrypted. Candidate: Is there a file size limit? Interview: Yes, files must be 10 GB or smaller. Candidate: How many users does the product have? Interviewer: 10M DAU.</p><p>So basically we have these Functional Requirements:</p><ol><li>Upload(Add files. The easiest way to add a file is to drag and drop a file into Google drive.)</li><li>Download</li><li>Sync(When a file is added to one device, it is automatically synced to other devices)</li><li>Read</li><li>Share(files with your friends, family, and coworkers)</li></ol><p>Non Functional Requirements:</p><p>LCS (latency consistency scaliability)</p><p>DFS(durability prevents data loss; fault tolerance, security via encryption)</p><p>so latency should be low for upload download</p><p>High availability. Users should still be able to use the system when some servers are offline, slowed down, or have unexpected network errors.</p><p>Back of the envelope estimation • Assume the application has 50 million signed up users and 10 million DAU. • Users get 10 GB free space. • Assume users upload 2 files per day. The average file size is 500 KB. • 1:1 read to write ratio. • Total space allocated: 50 million * 10 GB = 500 Petabyte • QPS for upload API: 10 million * 2 uploads / 24 hours / 3600 seconds = ~ 240 • Peak QPS = QPS * 2 = 480</p><p>We will start with something simple: build everything in a single server. Then, gradually scale it up to support millions of users. By doing this exercise, it will refresh your memory about some important topics covered in the book.</p><p>Let us start with a single server setup as listed below: • A web server to upload and download files. • A database to keep track of metadata like user data, login info, files info, etc. • A storage system to store files. We allocate 1TB of storage space to store files</p><p>We spend a few hours setting up an Apache web server, a MySql database, and a directory called drive/ as the root directory to store uploaded files. Under drive/ directory, there is a list of directories, known as namespaces. Each namespace contains all the uploaded files for that user. The filename on the server is kept the same as the original file name. Each file or folder can be uniquely identified by joining the namespace and the relative path.</p><h3>APIs</h3><p>What do the APIs look like? We primary need 3 APIs: upload a file, download a file, and get file revisions.</p><ol><li><strong>Upload a file to Google Drive</strong> Two types of uploads are supported: • <strong>Simple upload.</strong> Use this upload type when the file size is small. • <strong>Resumable upload</strong>. Use this upload type when the file size is large and there is high chance of network interruption. Here is an example of resumable upload API: <a href="https://api.example.com/files/upload?uploadType=resumabl">**https://api.example.com/files/upload?uploadType=resumabl</a>e**</li></ol><p>Params: • uploadType=resumable • data: Local file to be uploaded.</p><p>A resumable upload is achieved by the following 3 steps [2]: • Send the initial request to retrieve the resumable URL. • Upload the data and monitor upload state. • If upload is disturbed, resume the upload.</p><ol><li><strong>Download a file from Google Drive</strong> Example API: <a href="https://api.example.com/files/download">https://api.example.com/files/download</a> Params: • path: download file path. Example params: { “path”: “/recipes/soup/best_soup.txt” }</li><li>Get file revisions Example API: <a href="https://api.example.com/files/list_revisions">https://api.example.com/files/list_revisions</a> Params: • path: The path to the file you want to get the revision history. • limit: The maximum number of revisions to return. Example params: { “path”: “/recipes/soup/best_soup.txt”, “limit”: 20</li></ol><p>All the APIs require user authentication and use HTTPS. Secure Sockets Layer (SSL) protects data transfer between the client and backend servers.</p><p>So now its time to move away from single server as yr storage space is exhausted So the first soln that comes to my mind is sharding based on user_id</p><p>So now the fire is stopped but still worried abt potential data loss in case of storage server outage so use Amazon S3 (simple storage service is an object storage service)</p><p>Amazon S3 supports same-region and cross-region replication</p><p>So now data loss is also handled</p><p>Now what next Load Balancer,More webServers</p><ul><li>Metadata database: Move the database out of the server to avoid single point of failure. In the meantime, set up data replication and sharding to meet the availability and scalability requirements.</li><li>File storage: Amazon S3 is used for file storage. To ensure availability and durability, files are replicated in two separate geographical regions.</li></ul><p>So now we have decoupled web servers, metadata database, and file storage from a single server</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NfmapeJbMg8C3Wm75MX4ZQ.png" /></figure><p>Now We Handle Sync Conflicts</p><p>When two users modify the same file or folder at the same time, a conflict happens. How can we resolve the conflict? Here is our strategy: the first version that gets processed wins, and the version that gets processed later receives a conflict.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yk-i40shaBwsEqP6P4w4RA.png" /></figure><p>Our system presents both copies of the same file: user 2’s local copy and the latest version from the server (Figure 15–9). User 2 has the option to merge both files or override one version with the other</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dvEI_pI1he5U_XLODbr_Jg.png" /></figure><p>A file can be split into several blocks, each with a unique hash value, stored in our metadata database. Each block is treated as an independent object and stored in our storage system (S3). To reconstruct a file, blocks are joined in a particular order.</p><p><strong>Cold storage/Archieved</strong>: Cold storage is a computer system designed for storing inactive data, meaning files are not accessed for a long time.</p><p>Metadata cache: Some of the metadata are cached for fast retrieval.</p><p><strong>Notification service</strong>: It is a publisher/subscriber system that allows data to be transferred from notification service to clients as certain events happen. In our specific case, notification service notifies relevant clients when a file is added/edited/removed elsewhere so they can pull the latest changes. <strong>Offline backup queue</strong>: If a client is offline and cannot pull the latest file changes, the offline backup queue stores the info so changes will be synced when the client is online.</p><h3>Design Deep Dive</h3><ol><li><strong>Optimizations for Uploading Service:</strong></li></ol><p>A) Pre-signed URLs let you give clients <strong>temporary, limited access</strong> to upload (or download) objects <strong>directly</strong> to blob storage (like S3) <strong>without routing the file through your application server</strong>.</p><h3>How it works (quick flow)</h3><ol><li>Your backend <strong>generates a pre-signed URL</strong> with:</li></ol><ul><li>Allowed operation (PUT/GET)</li><li>Expiry time</li><li>Optional constraints (file size, content type)</li></ul><ol><li>The backend sends this URL to the client.</li><li>The client uploads <strong>directly to storage</strong> using that URL.</li><li>The URL <strong>expires automatically</strong> → access revoked</li></ol><p>B)Compression</p><p>C)Delta Changes (instead of the whole file using a sync algorithm)</p><p>D) Encryption before storing</p><p>E) Seperate Read &amp; Write Service so as to better handle the traffic</p><p>f) Permissions mapping for Sharing service</p><ol><li>strong consistency for metadata cache and database layers.</li></ol><p>How?</p><p>Data in cache replicas and the master is consistent. • Invalidate caches on database write to ensure cache and database hold the same value.</p><p><strong>Schema</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*miwpTMr8g_U5E7cwtnMiag.png" /></figure><p>Other Failure Handling Mech:</p><p>Metadata DB failure. • Master down: If the master is down, promote one of the slaves to act as a new master and bring up a new slave node. • Slave down: If a slave is down, you can use another slave for read operations and</p><ol><li>Sync Service: Moves in a fashion like Client to Server and then from Server to other clients as thee file needs to be in sync globally</li></ol><p>so from client to server (we pass it via write service and also add this to the event into the kafka so now from sync service to all the users who have permission</p><p>poll for stale it says that i will notify to user when he is available back again online</p><h3>Thankyou for Reading!!!</h3><h3>If you found it valuable, hit a like ❤️ and consider subscribing for more such content every week.!!!</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b3fea324a816" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[IRCTC System Design]]></title>
            <link>https://medium.com/@khandelwaltushar2002/irctc-system-design-398d34b0501c?source=rss-423da887408a------2</link>
            <guid isPermaLink="false">https://medium.com/p/398d34b0501c</guid>
            <category><![CDATA[design-systems]]></category>
            <category><![CDATA[high-level-design]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[irctc]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <dc:creator><![CDATA[Tushar]]></dc:creator>
            <pubDate>Sat, 15 Nov 2025 18:53:53 GMT</pubDate>
            <atom:updated>2025-11-15T18:53:53.867Z</atom:updated>
            <content:encoded><![CDATA[<h3>⭐ Why IRCTC?</h3><p>IRCTC deals with <strong>very high concurrency and very high throughput</strong>.</p><ul><li><strong>High Concurrency:</strong><br> No two users should ever be able to book the same train seat simultaneously.</li><li><strong>High Throughput:</strong><br> Ticket booking spikes dramatically during peak hours (especially Tatkal).<br> The system still needs to guarantee <em>zero double bookings</em> under massive load.</li></ul><p>These constraints make <strong>IRCTC a very interesting and challenging system to design</strong>.</p><h3>Minimum Viable Product</h3><p>● User Registration</p><p>● Given a source, destination and date, fetch the list of trains connecting the source to destination.</p><p>● Given a trainID, class and date, check for seat availability.</p><p>● For a given train, class, and date, book tickets if seats are available.</p><p>● Given a trainID, get all stops of the train (planned schedule).</p><p>● Payment gateway</p><p>● Notification of ticket booking (email, message)</p><h3>Estimation of Scale</h3><p>● Let’s assume 10000 trains run per day.</p><p>○ Each bogie has an average of 72 seats.</p><p>○ Assuming a train has an average of 15 bogies, total number of seats in a train on average is equal to 15 * 72 = 1080 seats.</p><p>● Hence, total number of seats to be booked in all trains = 10000 * 1080 which is approximately 10 million seats.</p><h3>Need for Sharding?</h3><p>● <strong>User </strong>table which stores the credentials of IRCTC users may hold upto one billion entries equivalent to the population of India.</p><p>● The <strong>Bookings </strong>table will store the details of bookings such as userID, trainID, date, seat details, src and destination.</p><p>○ Historical bookings will be stored in a separate table.</p><p>○ The <strong>Bookings </strong>table stores ticket details of current and upcoming journeys only.</p><p>● Now, IRCTC allows booking of train seats upto 3 months in future. Hence, in the worst case, all train seats for the next 90 days are booked by users.</p><p>● This leads to a total 90 * 10 = 900 million seat bookings. Hence, the maximum number of records in the Bookings table can grow upto <strong>900 million</strong>.</p><p>● Assuming userID (8B), trainID(8B), date(8B), seat(4B), src(4B), destination(4B), the size of a single record is <strong>36 Bytes, </strong>let’s approximate this to 50 Bytes.</p><p>● Total storage size needed for storing <strong>Bookings </strong>data= 50 * 900 million Bytes = 50 GB.</p><p>● Again, assuming the User table size to be <strong>100 GB </strong>(since it contains 1 Billion records at max), we have to store around 150 GB of data to get the system functioning.</p><p>Hence, as such there is <strong>no need of sharding</strong>. However, you might choose to shard if your design requires that. But based on the volume of data, there is no need to shard.</p><h3>Read or Write Heavy System System Type 1</h3><p><strong>Trains List and Schedules (A Static Microservice)</strong></p><p>Mostly Read operations are carried on the tables containing details of:</p><p>● Trains running on specific dates from a source to destination</p><p>● Train schedules always handle read operations</p><p>● These details are almost static and there are mostly read operations.</p><p>● We can consider this system as a separate microservice built on heavy caching and replicas.</p><h3>System Type 2</h3><p><strong>Seat Availability System</strong></p><p>Given the trainID, src, destination, date and class, show the number of seats available for booking.</p><p>● This system should be eventually consistent.</p><p>● There is no concept of a highly consistent system in this regard as well. It is because the number of available seats are changing every second, hence the system should be eventually consistent.</p><p>● The exact number of seats available does not matter that much as the data is changing every second.</p><p>● The system can become consistent in the time gap between showing the availability of seats and booking the seats.</p><p>● Also, this system is a read heavy system. It derives its data from the <strong>Bookings </strong>Table.</p><h3>System Type 3</h3><p>Now, write operations are carried out on the <strong>Bookings </strong>table. In this regard:</p><p>● Booking of seats needs to be highly consistent. Any seat cannot be booked twice in any situation.</p><p>● The Booking system is HC and it is both a read and write heavy system.</p><p>System <strong>2 </strong>and <strong>3 </strong>are dependent on each other. Whenever there are write operations on the <strong>Bookings </strong>table, the <strong>Seat Availability System </strong>has to update itself to become eventually consistent.</p><p>System <strong>2 </strong>can be thought of as a Caching layer that keeps track of seat availability based on the Bookings system. The Booking layer/system in such a case is write heavy and Caching layer is ready heavy.</p><p><strong>High Throughput </strong>is one of the design goals as during the peak time, for example in tatkal booking, the system would have to handle millions of requests in a small period of time.</p><h3>Summary Till Now</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/922/1*LzCLZGyFEthEpTK7b-8lVA.png" /></figure><h3>Problem #1 (Consistency):</h3><p>Suppose a request comes to the load balancer trying to book a seat. Now the system has to make sure that once a seat is assigned to this request, no other request can claim that seat. In other words, the system has to be completely consistent. How do you do that?</p><p>There are essentially 3 steps:</p><p>● <strong>Step 1: </strong>Check for availability, let’s say 1 seat is available, <strong>X</strong>.</p><p>● <strong>Step 2: </strong>Book the seat X</p><p>● <strong>Step 3: </strong>Return X</p><p>When we transition from Step 1 and Step 2, there are chances that there are no seats left (even though step 1 indicated availability of a seat). How to ensure these three steps are <strong>atomic </strong>in nature? Either all of them happen or none.</p><p>Could we leverage the atomicity property of relational DBs?</p><h3>Answer:</h3><p>● Leverage the Atomicity property of Relational DBs to solve this problem.</p><p>● If you try to make the sequence of operations atomic on the application side (servers), it becomes extremely hard to make the entire operation atomic.</p><p>● Since the eventual source of data is your database, hence you should think of ways to make it atomic on your database itself.</p><p>● The advantage of this approach is that if you pass one large query, it provides you guarantee that either the entire query will succeed or nothing will succeed.</p><p>● Assume the Bookings table is prepopulated with the details of all seats of all trains and each seat is available for the next 90 days.</p><h3>Query to allocate seat:</h3><p>UPDATE Bookings SET available = userID WHERE</p><p>trainID = T and date = D and (src = S ….) and available = 1</p><p>LIMIT 1;</p><p>● The where clause checks for seat availability, and only from available seats it will book one seat if available. <strong>LIMIT 1 </strong>implies only one of the available seats will be impacted randomly.</p><p>● If the above query is executed atomically, either both Update and where clause succeed or none of them succeed.</p><p>● It cannot happen that the where clause gives you an available seat but before updating the bookings table, that seat is booked. This is due to the way atomic operations are handled in RDBMS.</p><p>● The replicas of <strong>Bookings </strong>database do not need to run the queries. They can get transaction <strong>logs </strong>from the main database and update themselves accordingly. It is similar to the master slave system. All the slaves receive the transaction logs and update themselves.</p><p>● A highly consistent system means that the master should return success only after some number of slaves have also written the update through the logs.</p><h3>Problem #2: How to handle berth preference?</h3><p>It’s the art of writing SQL queries. You can use ORDER BY to sort the records according to the berth preference. So the WHERE clause filters records and ORDER BY clause is for handling preferences.</p><h3>Problem #3: Increase the Throughput</h3><p>All writes have to go to the master DB in master slave. If there is only one master, it will become the bottleneck. So, how do we increase throughput?</p><p>What if we shard? Not because we need to for storage, but because it helps us have different independent masters to increase write throughput.</p><p>● Best solution is to shard based on trainID.</p><p>○ A single shard can contain multiple trains but a single train is on one shard only.</p><p>● The trainID is a good sharding key because:</p><p>○ Ticket booking happens on only one train at one time.</p><p>● Now the throughput is the summation of the throughputs of all shards.</p><p>You can now horizontally scale by adding more and more shards to distribute load between more storage machines. You can still stay consistent, because for a given train, you only go to a single master where you can utilise the atomicity of RDBMS update.</p><h3>Segmentation of Journey</h3><p>The IRCTC ticket booking system is a little more complex than other ticket booking sites like makemytrip, etc. Here, a single seat can be booked several times during the length of a journey.</p><p>● Break down the entire journey into segments (collection of contiguous stations). In this situation, when you book a seat, book it for one or more segments.</p><p>Example, when A says to book a seat 8C from Hyd to Delhi. Do the following things:</p><p>● Figure out the segments of Hyd and Delhi let’s say X and Y respectively.</p><p>○ Hyd is the starting point of segment X.</p><p>○ Delhi is the ending point of segment Y.</p><p>● In that case book 8C for all segments between X to Y (both inclusive).</p><p>● Now, the query checks seat availability in all segments from X to Y and then updates the status for all such rows/segments.</p><h3>Block Diagram</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/930/1*uQxZcFXESEiNOzxUTPzdew.png" /></figure><p>There are two cases regarding how IRCTC can function:</p><h3>Case 1:</h3><p>● Fill passenger details</p><p>● Complete Payment</p><p>● Seat Booking Happens</p><p>● If the seat is booked, return the PNR and seat details otherwise refund.</p><h3>Case 2</h3><p>● Fill passenger details</p><p>● Temporarily block seats for the passenger if available. Change the status of blocked seats to <em>temporarily_blocked</em>.</p><p>● If no seats, game over.</p><p>● Otherwise, ask for payment within 60 seconds(this time can be decided).</p><p>● If payment is done within the stipulated time, return the PNR and other details and change status to <em>permanently_booked</em>.</p><p>We have been designing for <strong>Case 1 </strong>till now. For <strong>Case 2</strong>, only one thing changes, every 60 seconds run a <strong>Cron job </strong>making all the <em>temporarily_blocked </em>seats <em>available </em>again.</p><h3>CRON JOB</h3><p>UPDATE Bookings SET available = 1 WHERE</p><p>available = -1 and</p><p>updated_at = NOW() — 60 seconds</p><p>Assumption: Let <strong>available </strong>be a column with three possible values:</p><p>● 1 if seat is free or available</p><p>● 0 if it is permanently booked</p><p>● -1 if it is temporarily blocked</p><p>In Case 1, when a user books more than one seat for multiple users:</p><p>● The BookSeats API is called multiple times.</p><p>● Each time the request goes to the <strong>same shard </strong>because the trainID in all the cases are the same.</p><p>○ Also, if somehow magically, all the requests arrive at the same time with difference in nanoseconds, since the shard guarantees atomicity the queries corresponding to these requests will run in parallel independently.</p><p>○ This is the property of the database system.</p><p>○ If only one seat gets booked out of 5, the remaining seats can get a refund.</p><p>● So, the booking of seats happens one by one once the payment successful message is received.</p><p>● Till the second step in Case 1 (Complete Payment), the details of the passengers are not stored in the databases.</p><p>● Once the payment is completed, the details are fetched from the client and booking is done.</p><h3>System 2 Design — Seat Availability System</h3><p>● Each time a query comes to find the number of available seats, the actual answer is stored in the database in the shard as shown below.</p><p>● But if each time we query the database, it will become both a read and write heavy system. In earlier classes, you have learnt it is impossible to design a database that is both read and write heavy.</p><p>● To avoid this scenario, you can build a cache on top of it. If this cache needs to be highly consistent, you can build a write-through cache. You can build a bunch of caching machines which cache data from the database.</p><p>○ Whenever there is an update, they can propagate upwards.</p><p>● Another solution is to use a master-slave system. The read requests will be directed towards the slaves. However, if you want the AvailableSeats API to be very fast, it would be better to use cache.</p><p>● Regarding the buffer time, it is not there. You are trying to propagate the updates as soon as possible. The kafka would have some delay depending on the throughput of kafka.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/928/1*E6dOEv7W8DTen6vwzGDBmA.png" /></figure><h3>Generic Question</h3><p>● You need to be one driving the discussion. Nobody should be poking you giving you scenarios to think of. Because in that case it means you are doing the bare minimum and walking off.</p><p>● How deep the discussion should be depends on the interviewer. It is your responsibility to probe the interviewer regarding this and get the job done. It is because we can go as deep as possible like we can go till the code and start discussing the functions.</p><p>● There are types of HLD interviews as well. Most of the MAANG and US-based startups prioritize discussion on the high-level components and not the solutioning. The</p><h3>Thankyou for Reading!!!</h3><h3>If you found it valuable, hit a like ❤️ and consider subscribing for more such content every week.!!!</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=398d34b0501c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Google Doc System Design]]></title>
            <link>https://medium.com/@khandelwaltushar2002/google-doc-system-design-f74d852bc239?source=rss-423da887408a------2</link>
            <guid isPermaLink="false">https://medium.com/p/f74d852bc239</guid>
            <category><![CDATA[design-systems]]></category>
            <category><![CDATA[googledoc-systemdesign]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[google-docs]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <dc:creator><![CDATA[Tushar]]></dc:creator>
            <pubDate>Mon, 27 Oct 2025 16:48:55 GMT</pubDate>
            <atom:updated>2025-10-27T16:48:55.219Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>In every system design interview, the first and most crucial step is <strong>requirement gathering</strong>. This step isn’t just about listing what the system should do; it’s about clarifying the problem, eliminating assumptions, and laying the groundwork for a scalable and efficient design.</p><p>Jumping directly into the solution, is a common mistake. Without understanding the <strong>context and scope</strong> of the problem, even the most sophisticated technical solutions can miss the mark. For instance, designing a system for 1,000 videos is vastly different from building one for 1 million or 1 billion. Gathering requirements allows you to uncover these crucial details.</p><p>The key here is to treat the requirements gathering process as a <strong>conversation</strong>. Many times, the problem statement provided by the interviewer will be intentionally vague. This is a test of your ability to navigate ambiguity — an essential skill, especially in senior or staff-level roles. It shows your ability to extract valuable insights and ask the right questions to paint a clearer picture.</p><p>Start by asking questions that clarify:</p><ul><li><strong>Who</strong> are the users?</li><li><strong>What</strong> are the specific use cases?</li><li><strong>What</strong> are the constraints?</li><li><strong>What’s the scale</strong> of the problem?</li></ul><p>These questions don’t just serve as a checklist — they open the door to deeper insights that will help you craft a solution tailored to the actual problem, not a generalized one. Demonstrating this early in the interview also shows your ability to strategically think through customer needs and weigh trade-offs before jumping into design.</p><h3>Functional Requirements</h3><p>Once you’ve clarified the big picture, it’s time to dive into the <strong>functional requirements</strong> — the “what” of the system. Functional requirements describe what the system needs to accomplish from the user’s perspective. Think of these as the “must-have” features.</p><p>In system design interviews, focusing on <strong>clarity</strong> and <strong>prioritization</strong> is crucial. It’s easy to get carried away with ideas about the system’s various capabilities, but remember, time is limited. You’ll want to focus on the <strong>top three functional requirements</strong> that are central to the problem. These could be, for example:</p><ul><li>Users should be able to search for YouTube videos.</li><li>Users should be able to sort videos by popularity or upload date.</li><li>The system should recommend videos based on viewing history.</li></ul><p>Rather than just listing all possible functionalities, your goal is to prioritize based on <strong>business impact</strong> and <strong>technical feasibility</strong>. Clearly communicating this prioritization signals your ability to make critical decisions under constraints, a key trait for senior roles. Mention any additional features as “out of scope”, showing the interviewer you’ve considered them but won’t focus on them unless there’s extra time.</p><p>When gathering functional requirements, also think about <strong>edge cases</strong> and <strong>future expansion</strong>. For instance:</p><ul><li>How does the system behave when a search query returns zero results?</li><li>How will the system adapt as user activity grows?</li></ul><p>By factoring in these elements early, you’re not just addressing immediate needs but also showcasing <strong>foresight</strong> and <strong>strategic thinking</strong>.</p><h3>Core Requirements</h3><ol><li><strong>Single User Editing</strong>: Single-user CRUD Operations in the Browser: Users can create, read, update, and delete documents directly in their web browser.</li><li><strong>Multi-user Collaborative Editing</strong>: Users should be able to edit the same document concurrently and view each other’s changes in real-time.</li></ol><h3>Out of Scope</h3><ul><li>Authentication and authorization</li><li>Document versioning and history</li><li>Document sharing and permissions management</li><li>Document comments and annotations</li><li>Document offline access</li></ul><h3>Scale Requirements</h3><ul><li>DAU: 1 million.</li><li>Traffic Spike: 5x during peak hours</li><li>Read to write ratio: 10:1</li><li>Average Document Size: 100KB. Assume each user has an average of 10 documents.</li><li>Edit Frequency: 1 edit per second per document during peak hours</li><li>Allow up to 100 concurrent users per documen</li></ul><h3>Non-Functional Requirements</h3><ul><li>High availability: The system must be accessible at all times, minimizing downtime to ensure continuous collaboration.</li><li>Low latency: End-to-end latency should be under 200 milliseconds.</li><li>Eventual Consistency: All users should eventually see the same document state, even if edits arrive at different times.</li><li>Read-Your-Writes Consistency: Users should see their own edits immediately to confirm their changes have been registered.</li></ul><h3>API Endpoints</h3><h3>POST /api/documents</h3><p>Create a new document</p><pre>Request Body:</pre><pre>{<br>  &quot;title&quot;: &quot;My Document&quot;<br>}</pre><pre>Response Body:</pre><pre>{<br>  &quot;documentId&quot;: &quot;doc-123&quot;,<br>  &quot;title&quot;: &quot;My Document&quot;<br>}</pre><h3>GET /api/documents/{documentId}</h3><p>Retrieve a document by ID</p><p><strong>Response Body:</strong></p><pre>{<br>  &quot;documentId&quot;: &quot;doc-123&quot;,<br>  &quot;title&quot;: &quot;My Document&quot;,<br>  &quot;content&quot;: &quot;Document content&quot;<br>}</pre><h3>PUT /api/documents/{documentId}</h3><p>Update document metadata or content</p><pre>Request Body:<br>{<br>  &quot;title&quot;: &quot;Updated Title&quot;,<br>  &quot;content&quot;: &quot;Updated content&quot;<br>}<br>Response Body:</pre><pre>{<br>  &quot;documentId&quot;: &quot;doc-123&quot;,<br>  &quot;title&quot;: &quot;Updated Title&quot;<br>}</pre><h3>High Level Design</h3><h3>1. Single User Editing</h3><p>Single-user CRUD Operations in the Browser: Users can create, read, update, and delete documents directly in their web browser.</p><p>First, let’s understand how file URLs are structured for a cloud editing tool.</p><h3>File URL structure</h3><p>In a typical operating system, a hierarchical file system is used. For example, on macOS, the URL structure is like this:</p><ul><li>~/Documents/my-document.txt</li><li>~/Downloads/my-document.txt</li><li>~/Desktop/my-document.txt</li></ul><p>In a typical cloud storage system, the URL structure is like this:</p><ul><li><a href="https://s3.amazonaws.com/bucket-name/user-id/document-id">https://s3.amazonaws.com/bucket-name/user-id/document-id</a></li></ul><p>However, in our collaborative editing system, we do not want a hierarchical URL structure because:</p><ul><li>The file is meant to be shared with others, so we do not want to expose the folder structure to other users.</li><li>A long URL with folder structure is hard to type and share.</li></ul><p>Therefore, we should use a flat structure. For example:</p><ul><li>Google Docs: <a href="https://docs.google.com/document/d/1Ss4s93AGpdksZp1X3Gjzy717LCv8xY49G_PewUwmZ5A">https://docs.google.com/document/d/1Ss4s93AGpdksZp1X3Gjzy717LCv8xY49G_PewUwmZ5A</a></li><li>Notion: <a href="https://www.notion.so/6b8b4565327b4c52b0bf765434a1210d">https://www.notion.so/6b8b4565327b4c52b0bf765434a1210d</a></li></ul><h3>How to generate the document ID?</h3><p>We want an ID that is:</p><ul><li><strong>Globally Unique</strong>: The ID should be unique across the entire system. No two documents should have the same ID ever.</li><li><strong>Short</strong>: Ideally, the ID should be short because it needs to be part of the URL. However, this is not a hard requirement.</li></ul><p>Let’s take a look at what Google Docs and Notion do.</p><ul><li>Google Docs: https://docs.google.com/document/d/1Ss4s93AGpdksZp1X3Gjzy717LCv8xY49G_PewUwmZ5A. Google Docs&#39; ID is alphanumeric without strict formatting rules (like JWT or MD5).</li><li>Notion: https://www.notion.so/6b8b4565327b4c52b0bf765434a1210d. Notion&#39;s ID is a MD5 hash of the document name.</li></ul><h3>How to Store Documents?</h3><p>For a document, we need to store both the document metadata and the document content.</p><h3>Document Metadata</h3><p>The document metadata includes:</p><ul><li>Document title, author, permissions, creation and last modified timestamps.</li><li>Access control data (e.g., roles like owner, editor, viewer).</li><li>Versioning pointers, references to document snapshots, and other attributes.</li></ul><p>The metadata is typicall <strong>small and structured</strong>, and the typical queries we need to fulfill are:</p><ul><li>Fast queries and filtering: For example, we may want to query all documents created by a specific user or retrieve documents that a user has permission to edit.</li><li>Data Integrity: We want to make sure the metadata is consistent and correct. For example, the relationship between users, documents, and permissions should be strictly enforced.</li><li>Transactional Consistency: Operations like adding or updating metadata (e.g., changing permissions or titles) should be atomic.</li></ul><p>Based on the above requirements, we should use a <strong>relational database</strong> to store the document metadata because:</p><ul><li>It has strong consistency and ACID-compliant transactions.</li><li>Relational databases are optimized for fast complex queries, making it easy for filtering and sorting.</li><li>The constraints that comes with relational databases make it difficult to insert incorrect data and therefore ensure data integrity.</li></ul><h3>Document Content</h3><p>Document content tends to be <strong>larger and less structured</strong> than metadata, especially for text documents, images, and other rich media. Additionally, the system may need to store multiple snapshots or versions of the content for version history, which increases storage needs over time.</p><p>Cloud object storage services (e.g., AWS S3, Google Cloud Storage) are designed to handle massive amounts of unstructured data. They are optimized for high throughput, scalability, and durability. They are also cost effective for large amounts of data. Therefore, we should use a <strong>cloud object storage service</strong> to store the document content.</p><p>Check out this video on <a href="https://www.youtube.com/watch?v=AV4Ei1qW89o">File vs Object Storage</a> if you need more details.</p><p>Here’s design diagram for single-user CRUD operations-storing the document metadata in a relational database and storing the document content in a cloud storage service:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O2BLNVXgjYX0Fd9RUgYeGA.png" /></figure><h3>2. Multi-user Collaborative Editing</h3><p>Users should be able to edit the same document concurrently and view each other’s changes in real-time.</p><h3>Synchronizing Document State</h3><p>To support multi-user collaborative editing, we need to solve the following problems:</p><ul><li>How to synchronize the document state for different users?</li><li>How to handle conflicts when multiple users edit the same document?</li></ul><p>First, let’s <em>assume there is no conflict</em> in editing between different users. Imagine different users are editing different parts of the document independently, and we only need to synchronize the part edited by each user to other users. Let’s compare our options for synchronizing the document state for different users.</p><h3>Synchronization Protocol Options</h3><h3>HTTP Polling</h3><p>Not Suitable</p><p>Client periodically requests updates from server</p><h3>How it works:</h3><p>The client sends regular HTTP requests to the server at fixed intervals to check for updates. If there are changes, the server responds with the latest document state.</p><h3>Pros:</h3><ul><li>Simple to implement</li><li>Works with standard HTTP infrastructure</li><li>Supported by all browsers</li></ul><h3>Cons:</h3><ul><li>High latency: Updates are delayed until next poll</li><li>Server overhead: Many requests may return no changes</li><li>Bandwidth intensive: Full headers sent with each request</li></ul><h3>Server-Sent Events (SSE)</h3><p>Suitable with Caveats</p><p>Server pushes updates to client over HTTP</p><h3>How it works:</h3><p>Uses HTTP connection for server to push updates to client. Client establishes connection and server sends events as they occur.</p><h3>Pros:</h3><ul><li>Real-time updates from server</li><li>Works over standard HTTP</li><li>Automatic reconnection</li><li>Simpler than WebSocket</li></ul><h3>Cons:</h3><ul><li>One-way communication only (server to client)</li><li>Limited browser support</li><li>May require additional mechanism for client-to-server updates</li></ul><h3>WebSocket</h3><p>Very Suitable</p><p>Persistent bidirectional connection</p><h3>How it works:</h3><p>Establishes a persistent TCP connection that allows real-time bidirectional communication between client and server.</p><h3>Pros:</h3><ul><li>Low latency: Updates sent immediately</li><li>Efficient: Minimal overhead after connection established</li><li>Bidirectional: Server can push updates to clients</li><li>Reduced server load compared to polling</li></ul><h3>Cons:</h3><ul><li>More complex to implement</li><li>Requires WebSocket-specific infrastructure</li><li>Need to handle connection management and reconnection</li></ul><h3>Conclusion:</h3><p>Most suitable for real-time collaborative editing due to low latency and efficient bidirectional communication.</p><p>Websocket is the best option for our system because it supports bidirectional communication and is suitable for real-time collaborative editing.</p><p>We want to add a Websocket Service in front of Document Service to support bidirectional communication. We could include the websocket service in Document Service, but it would be better to have a separate service because to separate the concerns of document storage and document synchronization and to make the Document Service <a href="https://systemdesignschool.io/fundamentals/evolution-of-a-web-app-stateless-vs-stateful">stateless</a>.</p><p>Additionally, we want to add a Message Queue between Document Service and Websocket Service to decouple them and to improve the availability and reliability of the Document Service. This is the classic <a href="https://systemdesignschool.io/fundamentals/system-design-template">system design template</a> for large scale system design we have been using throughout our courses.</p><p>Here’s the updated design diagram:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/921/1*1YYXU5UdsNJqxzeKKrHjmQ.png" /></figure><p>Here’s how it works:</p><ul><li><strong>Client 1 Sends Edit</strong>: Client 1 sends an edit to the WebSocket Service over its WebSocket connection. We don’t need to send the entire document. We can save space and send only the edits, similar to how Git works.</li><li><strong>WebSocket Service Adds Edit to Queue</strong>: The WebSocket Service places the edit in the message broker queue (e.g., Kafka, RabbitMQ, or Redis Pub/Sub). This decoupling allows the WebSocket Service to quickly move on to handling other incoming messages.</li><li><strong>Document Service Consumes Edit</strong>: The Document Service, acting as a consumer, reads the edit from the queue.</li><li><strong>Document Service Processes and Persists Edit</strong>: The Document Service validates, processes, and persists the edit in the database.</li><li><strong>Notify WebSocket Service</strong>: After updating the database, the Document Service can either:</li><li>Notify the WebSocket Service (possibly through the queue) that the update is complete.</li><li>Optionally, send the updated document state to the WebSocket Service for broadcasting.</li><li><strong>WebSocket Service Broadcasts Update</strong>: Upon receiving the update or confirmation, the WebSocket Service broadcasts the updated state to all connected clients, including Client 1, Client 2.</li></ul><h3>Operational Transformation</h3><p>The primary goal of Operational Transformation (OT) is to <strong>ensure that all users see the same final document state</strong> after a series of edits, even if those edits are made out of order. It does this by <strong>applying transformation functions to modify the conflicting operation</strong> so that they can be applied in a way that preserves the intention of each user’s changes.</p><p>Let’s use the same example as above to illustrate how OT works. At step 6, instead of choosing the latest edit, the OT will transform the edit</p><ul><li>Since A’s edit comes first, it will be applied first.</li><li>After applying this operation, the document becomes “Hello beautiful World”</li></ul><p>OT will then transform User B’s Operation Based on User A’s Edit</p><ul><li>User B wanted to insert “ amazing” at position 6 in the original document. However, User A’s insertion of “ beautiful” has shifted the text “World” to the right.</li><li><strong>New Position for User B’s Edit</strong>: After User A’s insertion of “ beautiful,” position 6 becomes position 16 (because “ beautiful” is 10 characters long).</li><li><strong>Transformed User B’s Operation</strong>: Insert “ amazing” at position 16 in the updated document.</li></ul><p>Now we can apply User B’s transformed operation to the document.</p><ul><li>The document state becomes “Hello beautiful amazing World” and this is the final state.</li></ul><p>This is a simple example. In a real-world collaborative editing system, the operations can be much more complex.</p><p><strong>Pros:</strong></p><ul><li>Preserves the intention of each user’s changes</li><li>Suitable for fine-grained collaboration</li></ul><p><strong>Cons:</strong></p><ul><li>More complex to implement</li><li>OT may have scalability limitations, especially when many users are making edits simultaneously. The transformation functions can become computationally expensive as the number of operations and conflicts increases, potentially leading to performance bottlenecks.</li></ul><p>This is one of the reason why collaborative editing systems typically allow only a small number of concurrent users to edit the same document.</p><h3>How to implement document version history?</h3><p>Document version history can be implemented using several strategies:</p><p>Snapshot-Based Versioning</p><ul><li>Store <strong>complete document snapshots</strong> at regular intervals</li><li>Pros: Fast retrieval, simple to implement</li><li>Cons: Storage intensive</li></ul><h3>Thankyou for Reading!!!</h3><h3>If you found it valuable, hit a like ❤️ and consider subscribing for more such content every week.!!!</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f74d852bc239" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Design a System for 5-9s(99.999%) high availability]]></title>
            <link>https://medium.com/@khandelwaltushar2002/design-a-system-for-5-9s-99-999-high-availability-8934f3e2b24f?source=rss-423da887408a------2</link>
            <guid isPermaLink="false">https://medium.com/p/8934f3e2b24f</guid>
            <category><![CDATA[data-availability]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[availability-zone]]></category>
            <category><![CDATA[high-availability]]></category>
            <dc:creator><![CDATA[Tushar]]></dc:creator>
            <pubDate>Thu, 25 Sep 2025 17:20:24 GMT</pubDate>
            <atom:updated>2025-09-25T17:20:24.933Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Availability</strong> refers to the ability of a system to remain operational and accessible to users over time, even in the event of hardware failures, software bugs, or network issues. It is often expressed as a percentage of uptime over a given period targets being “five nines” (99.999% availability), which translates to about 5 minutes of downtime per year.</p><h3>Key Concepts in Availability</h3><h3>1. Redundancy</h3><p>Redundancy involves having multiple components (servers, databases, networks) that can take over if one fails. This prevents a single point of failure from bringing down the entire system.</p><ul><li><strong>Horizontal Redundancy</strong>: Deploying multiple instances of the same component across different locations or servers.</li><li><strong>Vertical Redundancy</strong>: Having backup components within the same system (e.g., a secondary power supply).</li></ul><p><strong>Example</strong>: In a web application, you might have multiple web servers behind a load balancer. If one server fails, the load balancer redirects traffic to the remaining servers.</p><h3>2. Load Balancing</h3><p>Load balancing distributes incoming traffic across multiple servers to ensure that no single server becomes a bottleneck. This improves both availability and performance.</p><p><strong>Types of Load Balancing</strong>:</p><ul><li><strong>DNS Load Balancing</strong>: Distributes traffic based on DNS queries.</li><li><strong>Application Layer Load Balancing</strong>: Distributes traffic based on specific application logic, such as user location.</li></ul><p><strong>Example</strong>: A global e-commerce platform might use load balancers to distribute traffic across data centers in different regions, ensuring that users can access the site even if one data center goes down.</p><h3>3. Failover Mechanisms</h3><p>Failover is the process of automatically switching to a standby system when the primary system fails. This ensures continuous availability.</p><ul><li><strong>Active-Passive Failover</strong>: The standby system only becomes active when the primary system fails.</li><li><strong>Active-Active Failover</strong>: All systems are active and share the load, with any failing system’s load being taken over by the remaining systems.</li></ul><p><strong>Example</strong>: A database cluster might use active-passive failover, where a secondary database instance takes over if the primary instance becomes unavailable.</p><h3>4. Geographic Distribution</h3><p>Distributing your system across multiple geographic locations (data centers) reduces the risk of a single point of failure affecting availability. This approach also helps in improving latency by serving users from the nearest data center.</p><ul><li><strong>Regions and Availability Zones</strong>: Cloud providers like AWS, Azure, and Google Cloud offer multiple regions and availability zones, allowing for geographic redundancy.</li></ul><p><strong>Example</strong>: A content delivery network (CDN) uses edge servers located in different regions to serve content quickly and reliably, even if one region experiences an outage.</p><h3>5. Monitoring and Alerting</h3><p>Continuous monitoring and alerting are critical for maintaining high availability. By detecting issues early, you can respond before they cause significant downtime.</p><ul><li><strong>Monitoring Tools</strong>: Tools like Prometheus, Grafana, and Datadog can monitor system performance, resource utilization, and availability.</li><li><strong>Alerting</strong>: Setting up alerts for key metrics (e.g., CPU usage, response time) allows for proactive management of potential issues.</li></ul><p><strong>Example</strong>: An online banking system might use monitoring tools to track transaction latency and set alerts to notify engineers if latency exceeds a certain threshold.</p><h3>6. Disaster Recovery</h3><p>Disaster recovery involves having a plan to restore services after a catastrophic failure, such as a natural disaster or major hardware failure.</p><ul><li><strong>Backup and Restore</strong>: Regularly backing up data and ensuring the ability to restore it quickly.</li><li><strong>Cold, Warm, and Hot Standby</strong>: Different levels of readiness for disaster recovery, with cold standby being the least ready (slowest recovery) and hot standby being the most ready (fastest recovery).</li></ul><h3>2. Complexity vs. Simplicity</h3><p>Implementing high availability can add complexity to your system, making it harder to manage and maintain. Simplifying your architecture might reduce this complexity but could also reduce availability.</p><p><strong>Example</strong>: Using microservices with redundant instances can improve availability but also adds complexity in managing inter-service communication and state.</p><h3>3. Consistency vs. Availability (CAP Theorem)</h3><p>In distributed systems, the CAP theorem states that you can only achieve two out of three: Consistency, Availability, and Partition Tolerance. Often, to achieve high availability, you may need to compromise on consistency (Know more about consistency — <a href="https://medium.com/@profoliohub/achieving-consistency-in-system-design-interviews-9cff7c240de0">here</a>).</p><p><strong>Example</strong>: A distributed database might choose eventual consistency to ensure high availability, meaning that users might see slightly outdated data temporarily.</p><h3>Strategies for Achieving High Availability</h3><h3>1. Active-Active Architecture</h3><p>Deploying an active-active architecture where all nodes are actively handling traffic can improve availability. If one node fails, the others continue to serve requests without any noticeable impact on users.</p><p><strong>Example</strong>: A global API service might use active-active load balancing across multiple regions to ensure that traffic is distributed evenly and that no single region’s failure causes downtime.</p><h3>2. Multi-Region Deployment</h3><p>Deploying your application across multiple geographic regions ensures that a failure in one region doesn’t affect the entire system. This is particularly important for global services where users expect low latency and high availability.</p><p><strong>Example</strong>: A streaming service might deploy its content servers across North America, Europe, and Asia to ensure that users in any region can access content even if one region’s servers go down.</p><h3>3. Automated Recovery and Self-Healing</h3><p>Automating recovery processes can significantly reduce downtime. Self-healing systems automatically detect and recover from failures without human intervention.</p><p><strong>Example</strong>: A containerized application using Kubernetes might have self-healing capabilities where failed containers are automatically restarted and scaled as needed.</p><h3>4. Database Replication</h3><p>Replicating databases across multiple nodes or regions can ensure that data remains available even if one database instance fails. Synchronous replication offers strong consistency, while asynchronous replication improves availability at the cost of potential data lag.</p><p><strong>Example</strong>: A financial application might use synchronous replication across data centers to ensure that all transactions are available and consistent in real-time, despite the higher cost and complexity.</p><h3>5. Graceful Degradation</h3><p>Designing your system to degrade gracefully under failure conditions allows you to maintain partial functionality rather than experiencing a complete outage.<strong>Example</strong>: A news website might prioritize delivering text content if video servers are down, ensuring that users can still access critical information even if some features are unavailable.</p><h3>Example Scenario: Designing a Highly Available E-Commerce Platform</h3><p>Imagine you’re asked to design an e-commerce platform that must remain available during high traffic events like Black Friday. Here’s how you could approach it:</p><h3>Step 1: Identify Critical Components</h3><ul><li><strong>Web Servers</strong>: Handle incoming requests.</li><li><strong>Application Servers</strong>: Process business logic.</li><li><strong>Databases</strong>: Store product information, user data, and transactions.</li><li><strong>Payment Gateways</strong>: Process payments.</li></ul><h3>Step 2: Implement Redundancy</h3><ul><li><strong>Web and Application Servers</strong>: Deploy multiple instances in different availability zones with load balancers distributing traffic.</li><li><strong>Databases</strong>: Use master-slave replication with automatic failover. Ensure that critical data is replicated across regions.</li><li><strong>Payment Gateways</strong>: Integrate multiple payment gateways, so if one fails, the system can switch to another without affecting the user experience.</li></ul><h3>Step 3: Deploy Across Multiple Regions</h3><ul><li>Use cloud providers to deploy the platform across several geographic regions. Ensure that each region can handle the full load if others fail.</li></ul><h3>Step 4: Monitor and Automate Recovery</h3><ul><li>Set up continuous monitoring for key metrics (e.g., response times, server health) and automate recovery processes, such as scaling out servers during traffic spikes.</li></ul><h3>Step 5: Plan for Disaster Recovery</h3><ul><li>Implement a disaster recovery strategy with regular backups and a hot standby environment in a different region. Test recovery processes regularly to ensure they work as expected.</li></ul><p><strong>Conclusion</strong>: By focusing on redundancy, geographic distribution, automated recovery, and disaster planning, you can design an e-commerce platform that remains highly available even under extreme conditions.</p><h3>Common Pitfalls in High Availability Design</h3><ul><li><strong>Overlooking Single Points of Failure</strong>: Failing to identify and address single points of failure can undermine your entire high availability strategy.</li><li><strong>Ignoring Cost Implications</strong>: Designing for extreme availability can be expensive. It’s essential to weigh the costs against the actual availability needs of your system.</li><li><strong>Complexity Overhead</strong>: Adding too many layers of redundancy and failover mechanisms can complicate the system, making it harder to manage and increasing the likelihood of misconfigurations.</li></ul><h3>Conclusion</h3><p>High availability is a critical aspect of system design, particularly for applications where downtime is costly or unacceptable. By implementing strategies such as redundancy, load balancing, geographic distribution, and automated recovery, you can build systems that remain available even in the face of failures.</p><h3>In system design interviews, demonstrating your understanding of these concepts and your ability to apply them effectively can set you apart as a candidate</h3><h3>Stay tuned for more of such content!</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8934f3e2b24f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Design A Web Crawler — System Design Interview Problem]]></title>
            <link>https://medium.com/@khandelwaltushar2002/design-a-web-crawler-system-design-interview-problem-bb55e9dd9478?source=rss-423da887408a------2</link>
            <guid isPermaLink="false">https://medium.com/p/bb55e9dd9478</guid>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[web-crawler]]></category>
            <category><![CDATA[high-level-design]]></category>
            <dc:creator><![CDATA[Tushar]]></dc:creator>
            <pubDate>Thu, 17 Jul 2025 17:40:52 GMT</pubDate>
            <atom:updated>2025-07-17T17:40:52.124Z</atom:updated>
            <content:encoded><![CDATA[<h3>Design A Web Crawler — System Design Interview Problem</h3><p>A web crawler is known as a robot or spider. It is widely used by search engines to discover new or updated content on the web. Content can be a web page, an image, a video, a PDF file, etc. A web crawler starts by collecting a few web pages and then follows links on those pages to collect new content. Figure 1 shows a visual example of the crawl process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tpXO0qXFLYNG0lle" /></figure><p>Figure 1</p><p>A crawler is used for many purposes:</p><ul><li>Search engine indexing: This is the most common use case. A crawler collects web pages to create a local index for search engines. For example, Googlebot is the web crawler behind the Google search engine.</li><li>Web archiving: This is the process of collecting information from the web to preserve data for future uses. For instance, many national libraries run crawlers to archive web sites. Notable examples are the US Library of Congress [1] and the EU web archive [2].</li></ul><h3>Understand the problem and establish design scope</h3><p>The basic algorithm of a web crawler is simple:</p><p>1. Given a set of URLs, download all the web pages addressed by the URLs.</p><p>2. Extract URLs from these web pages</p><p>3. Add new URLs to the list of URLs to be downloaded. Repeat these 3 steps.</p><p>Does a web crawler work truly as simple as this basic algorithm? Not exactly. Designing a vastly scalable web crawler is an extremely complex task. Before jumping into the design, we must ask questions to understand the requirements and establish design scope:</p><p><strong>Candidate</strong>: What is the main purpose of the crawler? Is it used for search engine indexing, data mining, or something else?<br><strong>Interviewer</strong>: Search engine indexing.</p><p><strong>Candidate</strong>: How many web pages does the web crawler collect per month?<br><strong>Interviewer</strong>: 1 billion pages.</p><p><strong>Candidate</strong>: What content types are included? HTML only or other content types such as PDFs and images as well?<br><strong>Interviewer</strong>: HTML only.</p><p><strong>Candidate</strong>: Shall we consider newly added or edited web pages?<br><strong>Interviewer</strong>: Yes, we should consider the newly added or edited web pages.</p><p><strong>Candidate</strong>: Do we need to store HTML pages crawled from the web?<br><strong>Interviewer</strong>: Yes, up to 5 years</p><p><strong>Candidate</strong>: How do we handle web pages with duplicate content?<br><strong>Interviewer</strong>: Pages with duplicate content should be ignored.</p><p>It is important to understand the requirements and clarify ambiguities. Even if you are asked to design a straightforward product like a web crawler, you and your interviewer might not have the same assumptions.</p><p>Beside functionalities to clarify with your interviewer, it is also important to note down the following characteristics of a good web crawler:</p><ul><li>Scalability: The web is very large. There are billions of web pages out there. Web crawling should be extremely efficient using parallelization.</li><li>Robustness: The web is full of traps. Bad HTML, unresponsive servers, crashes, malicious links, etc. are all common. The crawler must handle all those edge cases.</li><li>Politeness: The crawler should not make too many requests to a website within a short time interval.</li><li>Extensibility: The system is flexible so that minimal changes are needed to support new content types. For example, if we want to crawl image files in the future, we should not need to redesign the entire system.</li></ul><h3>Back of the envelope estimation</h3><p>The following estimations are based on many assumptions, and it is important to communicate with the interviewer to be on the same page.</p><ul><li>Assume 1 billion web pages are downloaded every month.</li><li>QPS: 1,000,000,000 / 30 days / 24 hours / 3600 seconds = ~400 pages per second.</li><li>Peak QPS = 2 * QPS = 800</li><li>Assume the average web page size is 500k.</li><li>1-billion-page x 500k = 500 TB storage per month. If you are unclear about digital storage units, go through “Power of 2” section in the “Back-of-the-envelope Estimation” chapter again.</li><li>Assuming data are stored for five years, 500 TB * 12 months * 5 years = 30 PB. A 30 PB storage is needed to store five-year content.</li></ul><h3>HLD</h3><p>Once the requirements are clear, we move on to the high-level design. Inspired by previous studies on web crawling [4] [5], we propose a high-level design as shown in Figure 2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/739/1*zX8SKRdArZ_ogYSBfuJqDg.png" /><figcaption>Fig 2</figcaption></figure><p>First, we explore each design component to understand their functionalities. Then, we examine the crawler workflow step-by-step.</p><p><strong>Seed URLs</strong></p><p>A web crawler uses seed URLs as a starting point for the crawl process. For example, to crawl all web pages from a university’s website, an intuitive way to select seed URLs is to use the university’s domain name.</p><p>To crawl the entire web, we need to be creative in selecting seed URLs. A good seed URL serves as a good starting point that a crawler can utilize to traverse as many links as possible. The general strategy is to divide the entire URL space into smaller ones. The first proposed approach is based on locality as different countries may have different popular websites. Another way is to choose seed URLs based on topics; for example, we can divide URL space into shopping, sports, healthcare, etc. Seed URL selection is an open-ended question. You are not expected to give the perfect answer. Just think out loud.</p><p><strong>URL Frontier</strong></p><p>Most modern web crawlers split the crawl state into two: to be downloaded and already downloaded. The component that stores URLs to be downloaded is called the URL Frontier. You can refer to this as a First-in-First-out (FIFO) queue. For detailed information about the URL Frontier, refer to the deep dive.</p><p><strong>HTML Downloader</strong></p><p>The HTML downloader downloads web pages from the internet. Those URLs are provided by the URL Frontier.</p><p><strong>DNS Resolver</strong></p><p>To download a web page, a URL must be translated into an IP address. The HTML Downloader calls the DNS Resolver to get the corresponding IP address for the URL. For instance, URL www.wikipedia.org is converted to IP address 198.35.26.96 as of 3/5/2019.</p><p><strong>Content Parser</strong></p><p>After a web page is downloaded, it must be parsed and validated because malformed web pages could provoke problems and waste storage space. Implementing a content parser in a crawl server will slow down the crawling process. Thus, the content parser is a separate component.</p><p><strong>Content Seen?</strong></p><p>Online research [6] reveals that 29% of the web pages are duplicated contents, which may cause the same content to be stored multiple times. We introduce the “Content Seen?” data structure to eliminate data redundancy and shorten processing time. It helps to detect new content previously stored in the system. To compare two HTML documents, we can compare them character by character. However, this method is slow and time-consuming, especially when billions of web pages are involved. An efficient way to accomplish this task is to compare the hash values of the two web pages [7].</p><p><strong>Content Storage</strong></p><p>It is a storage system for storing HTML content. The choice of storage system depends on factors such as data type, data size, access frequency, life span, etc. Both disk and memory are used.</p><ul><li>Most of the content is stored on disk because the data set is too big to fit in memory.</li><li>Popular content is kept in memory to reduce latency.</li></ul><p><strong>URL Extractor</strong></p><p>URL Extractor parses and extracts links from HTML pages. Figure 3 shows an example of a link extraction process. Relative paths are converted to absolute URLs by adding the “https://en.wikipedia.org” prefix.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/675/1*HP0nS_nA2jBt4qM3MC3fQQ.png" /><figcaption>Fig3</figcaption></figure><p><strong>URL Filter</strong></p><p>The URL filter excludes certain content types, file extensions, error links and URLs in “blacklisted” sites.</p><p><strong>URL Seen?</strong></p><p>“URL Seen?” is a data structure that keeps track of URLs that are visited before or already in the Frontier. “URL Seen?” helps to avoid adding the same URL multiple times as this can increase server load and cause potential infinite loops.</p><p>Bloom filter and hash table are common techniques to implement the “URL Seen?” component. We will not cover the detailed implementation of the bloom filter and hash table here. For more information, refer to the reference materials [4] [8].</p><p><strong>URL Storage</strong></p><p>URL Storage stores already visited URLs.</p><p>So far, we have discussed every system component. Next, we put them together to explain the workflow.</p><p><strong>Web crawler workflow</strong></p><p>To better explain the workflow step-by-step, sequence numbers are added in the design diagram as shown in Figure 4.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/739/1*Zz8ooDnv-7kA0vizghfp4Q.png" /><figcaption>Fig4</figcaption></figure><p>Step 1: Add seed URLs to the URL Frontier</p><p>Step 2: HTML Downloader fetches a list of URLs from URL Frontier.</p><p>Step 3: HTML Downloader gets IP addresses of URLs from DNS resolver and starts downloading.</p><p>Step 4: Content Parser parses HTML pages and checks if pages are malformed.</p><p>Step 5: After content is parsed and validated, it is passed to the “Content Seen?” component.</p><p>Step 6: “Content Seen” component checks if a HTML page is already in the storage.</p><ul><li>If it is in the storage, this means the same content in a different URL has already been processed. In this case, the HTML page is discarded.</li><li>If it is not in the storage, the system has not processed the same content before. The content is passed to Link Extractor.</li></ul><p>Step 7: Link extractor extracts links from HTML pages.</p><p>Step 8: Extracted links are passed to the URL filter.</p><p>Step 9: After links are filtered, they are passed to the “URL Seen?” component.</p><p>Step 10: “URL Seen” component checks if a URL is already in the storage, if yes, it is processed before, and nothing needs to be done.</p><p>Step 11: If a URL has not been processed before, it is added to the URL Frontier.</p><h3>Design deep dive</h3><p>Up until now, we have discussed the high-level design. Next, we will discuss the most important building components and techniques in depth:</p><ul><li>Depth-first search (DFS) vs Breadth-first search (BFS)</li><li>URL frontier</li><li>HTML Downloader</li><li>Robustness</li><li>Extensibility</li><li>Detect and avoid problematic content</li></ul><h3>DFS vs BFS</h3><p>You can think of the web as a directed graph where web pages serve as nodes and hyperlinks (URLs) as edges. The crawl process can be seen as traversing a directed graph from one web page to others. Two common graph traversal algorithms are DFS and BFS. However, DFS is usually not a good choice because the depth of DFS can be very deep.</p><p>BFS is commonly used by web crawlers and is implemented by a first-in-first-out (FIFO) queue. In a FIFO queue, URLs are dequeued in the order they are enqueued. However, this implementation has two problems:</p><ul><li>Most links from the same web page are linked back to the same host. In Figure 5, all the links in wikipedia.com are internal links, making the crawler busy processing URLs from the same host (wikipedia.com). When the crawler tries to download web pages in parallel, Wikipedia servers will be flooded with requests. This is considered as “impolite”.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/685/1*jJ9LO7NR2beYdcyYcccv1A.png" /><figcaption>Fig 5</figcaption></figure><ul><li>Standard BFS does not take the priority of a URL into consideration. The web is large and not every page has the same level of quality and importance. Therefore, we may want to prioritize URLs according to their page ranks, web traffic, update frequency, etc.</li></ul><h3>URL frontier</h3><p>URL frontier helps to address these problems. A URL frontier is a data structure that stores URLs to be downloaded. The URL frontier is an important component to ensure politeness, URL prioritization, and freshness. A few noteworthy papers on URL frontier are mentioned in the reference materials [5] [9]. The findings from these papers are as follows:</p><h4>Politeness</h4><p>Generally, a web crawler should avoid sending too many requests to the same hosting server within a short period. Sending too many requests is considered as “impolite” or even treated as denial-of-service (DOS) attack. For example, without any constraint, the crawler can send thousands of requests every second to the same website. This can overwhelm the web servers.</p><p>The general idea of enforcing politeness is to download one page at a time from the same host. A delay can be added between two download tasks. The politeness constraint is implemented by maintain a mapping from website hostnames to download (worker) threads. Each downloader thread has a separate FIFO queue and only downloads URLs obtained from that queue. Figure 6 shows the design that manages politeness.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/520/1*4H7wAFdq51aQgPX9kpDRYg.png" /><figcaption>Fig 6</figcaption></figure><ul><li>Queue router: It ensures that each queue (b1, b2, … bn) only contains URLs from the same host.</li><li>Mapping table: It maps each host to a queue.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/1*9DfEey3xXhOUbo7fJJ7-Yw.png" /><figcaption>Table 1</figcaption></figure><ul><li>FIFO queues b1, b2 to bn: Each queue contains URLs from the same host.</li><li>Queue selector: Each worker thread is mapped to a FIFO queue, and it only downloads URLs from that queue. The queue selection logic is done by the Queue selector.</li><li>Worker thread 1 to N. A worker thread downloads web pages one by one from the same host. A delay can be added between two download tasks.</li></ul><h4>Priority</h4><p>A random post from a discussion forum about Apple products carries very different weight than posts on the Apple home page. Even though they both have the “Apple” keyword, it is sensible for a crawler to crawl the Apple home page first.</p><p>We prioritize URLs based on usefulness, which can be measured by PageRank [10], website traffic, update frequency, etc. “Prioritizer” is the component that handles URL prioritization. Refer to the reference materials [5] [10] for in-depth information about this concept.</p><p>Figure 7 shows the design that manages URL priority.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/513/1*SnN3LlmNb_ddIeYwx09Eog.png" /><figcaption>Fig 7</figcaption></figure><ul><li>Prioritizer: It takes URLs as input and computes the priorities.</li><li>Queue f1 to fn: Each queue has an assigned priority. Queues with high priority are selected with higher probability.</li><li>Queue selector: Randomly choose a queue with a bias towards queues with higher priority.</li></ul><p>Figure 8 presents the URL frontier design, and it contains two modules:</p><ul><li>Front queues: manage prioritization</li><li>Back queues: manage politeness</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/556/1*v2GdSz1renNIF8m0VdHKLw.png" /><figcaption>Figure 8</figcaption></figure><h4>Freshness</h4><p>Web pages are constantly being added, deleted, and edited. A web crawler must periodically recrawl downloaded pages to keep our data set fresh. Recrawl all the URLs is time-consuming and resource intensive. Few strategies to optimize freshness are listed as follows:</p><ul><li>Recrawl based on web pages’ update history.</li><li>Prioritize URLs and recrawl important pages first and more frequently.</li></ul><h4>Storage for URL Frontier</h4><p>In real-world crawl for search engines, the number of URLs in the frontier could be hundreds of millions [4]. Putting everything in memory is neither durable nor scalable. Keeping everything in the disk is undesirable neither because the disk is slow; and it can easily become a bottleneck for the crawl.</p><p>We adopted a hybrid approach. The majority of URLs are stored on disk, so the storage space is not a problem. To reduce the cost of reading from the disk and writing to the disk, we maintain buffers in memory for enqueue/dequeue operations. Data in the buffer is periodically written to the disk.</p><h3>HTML Downloader</h3><p>The HTML Downloader downloads web pages from the internet using the HTTP protocol. Before discussing the HTML Downloader, we look at Robots Exclusion Protocol first.</p><p>Robots.txt</p><p>Robots.txt, called Robots Exclusion Protocol, is a standard used by websites to communicate with crawlers. It specifies what pages crawlers are allowed to download. Before attempting to crawl a web site, a crawler should check its corresponding robots.txt first and follow its rules.</p><p>To avoid repeat downloads of robots.txt file, we cache the results of the file. The file is downloaded and saved to cache periodically. Here is a piece of robots.txt file taken from https://www.amazon.com/robots.txt. Some of the directories like creatorhub are disallowed for Google bot.</p><pre>User-agent: Googlebot<br>Disallow: /creatorhub/\*<br>Disallow: /rss/people/\*/reviews<br>Disallow: /gp/pdp/rss/\*/reviews<br>Disallow: /gp/cdp/member-reviews/<br>Disallow: /gp/aw/cr/</pre><p>Besides robots.txt, performance optimization is another important concept we will cover for the HTML downloader.</p><h3>Extensibility</h3><p>As almost every system evolves, one of the design goals is to make the system flexible enough to support new content types. The crawler can be extended by plugging in new modules. Figure 10 shows how to add new modules.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/658/1*GedxyHJUFCCXGFyPQMGAcw.png" /></figure><ul><li>PNG Downloader module is plugged-in to download PNG files.</li><li>Web Monitor module is added to monitor the web and prevent copyright and trademark infringements.</li></ul><h3>Detect and avoid problematic content</h3><p>This section discusses the detection and prevention of redundant, meaningless, or harmful content.</p><p>1. Redundant content</p><p>As discussed previously, nearly 30% of the web pages are duplicates. Hashes or checksums help to detect duplication [11].</p><p>2. Spider traps</p><p>A spider trap is a web page that causes a crawler in an infinite loop. For instance, an infinite deep directory structure is listed as follows: <a href="http://www.spidertrapexample.com/foo/bar/foo/bar/foo/bar/...">http://www.spidertrapexample.com/foo/bar/foo/bar/foo/bar/...</a></p><p>Such spider traps can be avoided by setting a maximal length for URLs. However, no one-size-fits-all solution exists to detect spider traps. Websites containing spider traps are easy to identify due to an unusually large number of web pages discovered on such websites. It is hard to develop automatic algorithms to avoid spider traps; however, a user can manually verify and identify a spider trap, and either exclude those websites from the crawler or apply some customized URL filters.</p><p>3. Data noise</p><p>Some of the contents have little or no value, such as advertisements, code snippets, spam URLs, etc.</p><h3>Thankyou for Reading!!!</h3><h3>If you found it valuable, hit a like ❤️ and consider subscribing for more such content every week.!!!</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bb55e9dd9478" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Design a Scalable Notification Service — System Design Interview Problem]]></title>
            <link>https://medium.com/@khandelwaltushar2002/design-a-scalable-notification-service-system-design-interview-problem-d77ecf52ad3a?source=rss-423da887408a------2</link>
            <guid isPermaLink="false">https://medium.com/p/d77ecf52ad3a</guid>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[scalable-notification]]></category>
            <category><![CDATA[notification-system]]></category>
            <category><![CDATA[hld-system-design]]></category>
            <category><![CDATA[notification-service]]></category>
            <dc:creator><![CDATA[Tushar]]></dc:creator>
            <pubDate>Thu, 17 Jul 2025 17:02:32 GMT</pubDate>
            <atom:updated>2025-07-17T17:02:32.067Z</atom:updated>
            <content:encoded><![CDATA[<h3>Design a Scalable Notification Service — System Design Interview Problem</h3><p>A <strong>notification service</strong> is a system responsible for delivering timely and relevant information to users across various channels such as SMS, email, push notifications, and in-app messages.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*FjvhFLkwMbZ6onMZ.png" /></figure><p>Unified Notification Hub</p><h3>Requirements</h3><h3>Functional Requirements:</h3><ol><li><strong>Multi-channel Support</strong>: The system must support sending notifications through various channels including email, SMS, push notifications, and in-app messages.</li><li><strong>Multiple Notification Types</strong>: Support transactional (e.g., order confirmation), promotional (e.g., discount offers), and system-generated alerts (e.g., password reset).</li><li><strong>Scheduled Delivery</strong>: Support scheduling of notifications for future delivery.</li><li><strong>Rate Limiting</strong>: Ensure that users receive only a limited number of promotional messages in a given day to prevent spam.</li><li><strong>Retry Mechanism</strong>: Handle notification delivery failures, retrying when necessary (e.g., failed SMS or email).</li></ol><h3>Non-Functional Requirements:</h3><ul><li><strong>Scalability:</strong> The system should handle millions of notifications per minute, supporting millions of concurrent users.</li><li><strong>High availability:</strong> Ensure minimal downtime so that notifications are delivered even in case of failures.</li><li><strong>Reliability:</strong> Guarantee at-least-once delivery of notifications, with the possibility of exactly-once semantics for certain use cases.</li><li><strong>Low latency:</strong> Notifications should be sent as quickly as possible to ensure timely delivery.</li></ul><h3>Scale Estimation</h3><p>Let’s estimate the scale to better inform design decisions.</p><ul><li><strong>Users</strong>: Assume the system serves <strong>50 million daily users</strong>.</li><li><strong>Notifications per user</strong>: On average, each user receives <strong>5 notifications/day</strong>.</li><li><strong>Peak load</strong>: Assume the peak time sees <strong>1 million notifications</strong> within 1 minutes (a common scenario during flash sales, for example).</li></ul><p>This means the system should handle:</p><ul><li><strong>Notifications per day:</strong> 50 million x 5 = 250 million notifications/day</li><li><strong>Peak notifications per second:</strong> 1 million / 60 **= ~**17,000 notifications/second</li></ul><h3>Storage Requirements</h3><p>Assuming average notification and user data size of 1KB.</p><ul><li><strong>Storage for user data:</strong> 50 million * 1 KB = 50GB</li><li><strong>Daily Storage for notifications:</strong> 50 million * 5 * 1 KB = 250GB</li></ul><h3>HLD</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*Qz28-uWEu898_bxG.png" /></figure><p>High Level Diagram(Microservices Integration with Centralized Notification Service)</p><h3>Complete Notification System HLD — Component-by-Component Handling Functional &amp; Non Functional Requirements</h3><h3>🧑 User</h3><ul><li>The <strong>origin</strong> of any event (e.g., comment, like, purchase, login).</li></ul><h3>🔀 Load Balancer(Ensures Availability)</h3><ul><li>Ensures <strong>high availability</strong> by distributing incoming traffic across multiple backend servers.</li><li>Supports <strong>Multi-AZ Replication</strong> for failover and reliability.</li></ul><h3>🛡️ API Gateway(Ensures Security)</h3><ul><li>Acts as the <strong>entry point</strong> for all clients.</li><li>Authenticates users via tokens (e.g., OAuth, JWT).</li><li>Performs request validation and routing.</li><li>Also supports rate-limiting, throttling, and basic monitoring.</li></ul><h3>📬 Async Event Queue (Kafka or RabbitMQ)</h3><ul><li>Stores user-triggered events <strong>asynchronously</strong> for decoupled processing.</li><li>Provides durability, buffering, and support for <strong>at-least-once</strong> delivery.</li><li>Helps the system handle <strong>burst traffic</strong> without overload.</li></ul><h3>🧠 Classifier</h3><ul><li>Consumes messages from the queue.</li><li>Separates events into:</li><li><strong>Transactional</strong> (OTP, password reset)</li><li><strong>Promotional</strong> (discounts, new feature alerts)</li><li>Could also apply filtering rules (e.g., block duplicate promos).</li></ul><h3>🗃️ Database &amp; Redis Cache</h3><ul><li><strong>DB</strong> holds user profiles, channel preferences, and historical data.</li><li><strong>Sharding strategy</strong>:</li><li><strong>User-based sharding</strong>: horizontal scale based on user ID.</li><li><strong>Time-based sharding</strong>: for archiving old data.</li><li><strong>Redis</strong>:</li><li>Caches frequent lookups (preferences, online status).</li><li>Reduces DB pressure and improves latency.</li></ul><h3>🧮 Digester</h3><ul><li>Collects <strong>low-priority messages</strong> for online users.</li><li>Aggregates them into <strong>summary notifications</strong> (e.g., “5 people liked your photo”).</li><li>Sends these via <strong>in-app notifications</strong>, avoiding noisy emails/SMS.</li></ul><h3>🚦 Channel Router</h3><ul><li>Decides the <strong>best channel</strong> based on:</li><li>User preferences (email over SMS, etc.)</li><li>Message priority</li><li>System health or availability of third-party APIs</li><li>Routes to one or more processors accordingly.</li></ul><h3>📤 Channel Processors</h3><p>Each processor formats, queues, and sends the notification:</p><ul><li><strong>WhatsApp Processor</strong>:</li><li>Talks to WhatsApp Business API.</li><li>Useful for transactional notifications.</li><li><strong>Email Processor</strong>:</li><li>Sends via services like SES, SendGrid, Mailgun.</li><li><strong>SMS Processor</strong>:</li><li>Works with Twilio, AWS SNS, or local telcos.</li></ul><h3>📊 Rate Limiter</h3><ul><li>Protects channels like SMS/WhatsApp from overuse.</li><li>Especially important for high-priority transactional messages.</li><li>Can use token bucket or leaky bucket algorithms.</li></ul><h3>📌 Priority Queues (P0, P1, P2)</h3><ul><li><strong>P0</strong>: Immediate (e.g., OTPs) — real-time</li><li><strong>P1</strong>: Important (e.g., password change alerts)</li><li><strong>P2</strong>: Low-priority (e.g., likes)</li></ul><h3>🗑️ Dead Letter Queue (DLQ)</h3><ul><li>Stores failed messages for debugging, retries, or analysis.</li><li>Critical for ensuring <strong>no silent failures</strong>.</li></ul><h3>📈 Centralized Logging &amp; Alerts</h3><ul><li>Powered by tools like <strong>Prometheus, Grafana, ELK Stack, or Datadog</strong>.</li><li>Tracks:</li><li>Delivery success/failure</li><li>Latency across services</li><li>Retry attempts and DLQ size</li></ul><h3>🗄️ Old Archived Data</h3><ul><li>Stores historical notification data (cold storage).</li><li>May be used for analytics, reporting, or legal compliance.</li></ul><h3>APIs</h3><p><strong>Notification Request Creation:</strong></p><h3>Sample Request:</h3><pre>{<br>  &quot;requestId&quot;: &quot;abc123&quot;,<br>  &quot;timestamp&quot;: &quot;2024-09-17T14:00:00Z&quot;,<br>  &quot;notificationType&quot;: &quot;transactional&quot;,<br>  &quot;channels&quot;: [&quot;email&quot;, &quot;sms&quot;, &quot;push&quot;],<br>  &quot;recipient&quot;: {<br>    &quot;userId&quot;: &quot;user789&quot;,<br>    &quot;email&quot;: &quot;user@example.com&quot;<br>  },<br>  &quot;message&quot;: {<br>    &quot;subject&quot;: &quot;Order Confirmation&quot;,<br>    &quot;body&quot;: &quot;Thank you for your order! Your order #123456 has been confirmed.&quot;,<br>    &quot;attachments&quot;: [&quot;&lt;https://example.com/invoice123456.pdf&gt;&quot;],<br>    &quot;smsText&quot;: &quot;Thank you for your order! Order #123456 confirmed.&quot;,<br>    &quot;pushNotification&quot;: {<br>      &quot;title&quot;: &quot;Order Confirmed&quot;,<br>      &quot;body&quot;: &quot;Your order #123456 has been confirmed. Check your email for details.&quot;,<br>      &quot;icon&quot;: &quot;&lt;https://example.com/icon.png&gt;&quot;,<br>      &quot;action&quot;: {<br>        &quot;type&quot;: &quot;viewOrder&quot;,<br>        &quot;url&quot;: &quot;&lt;https://example.com/order/123456&gt;&quot;<br>      }<br>    }<br>  },<br>  &quot;schedule&quot;: {<br>    &quot;sendAt&quot;: &quot;2024-09-17T15:00:00Z&quot;<br>  },<br>  &quot;metadata&quot;: {<br>    &quot;priority&quot;: &quot;high&quot;,<br>    &quot;retries&quot;: 3<br>  }<br>}</pre><h3>2) Notification Service Ingestion</h3><p>The <strong>Notification Service</strong> (via an <strong>API Gateway / Load Balancer</strong>) receives the notification request.</p><p>The request is <strong>authenticated</strong> and <strong>validated</strong> to ensure it’s coming from an authorized source and all necessary information (recipient, message, channels, etc.) is present and correct.</p><h3>3) Fetching User Preferences</h3><h3>Sample Response from User Preference Service:</h3><pre>{<br>  &quot;userId&quot;: &quot;user789&quot;,<br>  &quot;preferences&quot;: {<br>    &quot;channels&quot;: {<br>      &quot;transactional&quot;: [&quot;email&quot;, &quot;push&quot;],<br>      &quot;promotional&quot;: [&quot;sms&quot;],<br>      &quot;systemAlert&quot;: [&quot;push&quot;, &quot;sms&quot;]<br>    },<br>    &quot;doNotDisturb&quot;: {<br>      &quot;enabled&quot;: true,<br>      &quot;startTime&quot;: &quot;22:00&quot;,<br>      &quot;endTime&quot;: &quot;08:00&quot;,<br>      &quot;timezone&quot;: &quot;America/New_York&quot;<br>    },<br>    &quot;dailyLimits&quot;: {<br>      &quot;promotionalLimit&quot;: 2,<br>      &quot;promotionalSentToday&quot;: 1<br>    },<br>    &quot;optOut&quot;: {<br>      &quot;email&quot;: false,<br>      &quot;sms&quot;: false,<br>      &quot;push&quot;: false<br>    },<br>    &quot;preferredTimeForDelivery&quot;: {<br>      &quot;enabled&quot;: true,<br>      &quot;startTime&quot;: &quot;09:00&quot;,<br>      &quot;endTime&quot;: &quot;21:00&quot;,<br>      &quot;timezone&quot;: &quot;America/New_York&quot;<br>    }<br>  }<br>}</pre><h3>4)Queueing the Notification</h3><p>Once the <strong>Notification Service</strong> has created and formatted the messages for the required channels, it places each message into the respective <strong>topic</strong> in the <strong>Notification Queue System</strong> (e.g., <strong>Kafka</strong>, <strong>RabbitMQ</strong>, <strong>AWS SQS</strong>)</p><ul><li>The <strong>Email Message</strong> is placed into the <strong>Email Topic</strong>.</li><li>The <strong>SMS Message</strong> is placed into the <strong>SMS Topic</strong>.</li><li>The <strong>Push Notification Message</strong> is placed into the <strong>Push Topic</strong>.</li></ul><h3>5) Sending the Notification</h3><p>Each <strong>Channel Processor</strong> handles the delivery of the notification through the specified channel:</p><h3>Email Processor:</h3><ul><li>Connects to the email provider (e.g., <strong>SendGrid</strong>, <strong>Mailgun</strong>, <strong>Amazon SES</strong>).</li><li>Sends the email, ensuring it follows the user’s preferences (e.g., HTML vs. plain text).</li><li>Handles errors such as bounces or invalid email addresses.</li></ul><h3>SMS Processor:</h3><ul><li>Connects to the SMS provider (e.g., <strong>Twilio</strong>, <strong>Nexmo</strong>).</li><li>Sends the SMS with any formatting adjustments to meet character limits or regional requirements.</li><li>Handles issues such as invalid phone numbers or network errors.</li></ul><h3>Push Notification Processor:</h3><ul><li>Uses services like <strong>Firebase Cloud Messaging (FCM)</strong> for Android or <strong>Apple Push Notification Service (APNs)</strong> for iOS.</li><li>Sends the push notification, including any metadata (e.g., app-specific actions or icons).</li><li>Handles failures such as expired device tokens or offline devices.</li></ul><h3>In-App Notification Processor:</h3><ul><li>Sends the in-app notification via <strong>WebSockets</strong> or <strong>long polling</strong> to the user’s active session.</li><li>Formats the message for display in the app’s UI, adhering to any app-specific display rules.</li></ul><h3>6) Monitoring and Logging</h3><p>To ensure smooth operation at scale, the system should have:</p><ul><li><strong>Centralized Logging</strong>: Use tools like <strong>ELK Stack</strong> or <strong>Prometheus/Grafana</strong> to collect logs from various components and monitor the health of the system.</li><li><strong>Alerting</strong>: Set up alerts for failures (e.g., notification delivery failure rates exceed a threshold).</li><li><strong>Metrics</strong>: Track metrics like success rate, failure rate, delivery latency, and throughput for each channel.</li></ul><h3>7) Sharding &amp; Partitioning</h3><p>To efficiently handle large datasets, particularly for user data and notification logs, sharding and partitioning distribute the load across multiple databases or geographic regions:</p><ul><li><strong>User-based Sharding</strong>: Distribute users across different databases or regions based on geographic location or user ID to balance the load.</li><li><strong>Time-based Partitioning</strong>: Organize notification logs into time-based partitions (e.g., daily or monthly) to improve query performance and manage large volumes of historical data.</li></ul><h3>8) Caching</h3><p>Implement caching with solutions like <strong>Redis</strong> or <strong>Memcached</strong> to store frequently accessed data, such as user preferences.</p><p>Caching reduces the load on the database and improves response times for real-time notifications by avoiding repeated database lookups.</p><h3>Thankyou for Reading!!!</h3><h3>If you found it valuable, hit a like ❤️ and consider subscribing for more such content every week.!!!</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d77ecf52ad3a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Instagram System Design]]></title>
            <link>https://medium.com/@khandelwaltushar2002/instagram-system-design-6357ad62d50a?source=rss-423da887408a------2</link>
            <guid isPermaLink="false">https://medium.com/p/6357ad62d50a</guid>
            <category><![CDATA[microservice-architecture]]></category>
            <category><![CDATA[hld]]></category>
            <category><![CDATA[lld]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[instagram]]></category>
            <dc:creator><![CDATA[Tushar]]></dc:creator>
            <pubDate>Wed, 09 Jul 2025 18:42:55 GMT</pubDate>
            <atom:updated>2025-07-09T19:03:53.195Z</atom:updated>
            <content:encoded><![CDATA[<h3>Functional Requirement:</h3><p><em>1. Image/video Upload — Users should able to upload image/video from mobile devices. The system should support different image format and sizes.</em></p><p>2. <strong>Likes and comments</strong> — User should able to like and comment on images. Views the likes and comments on images. Receive notification when their images being liked or commented. More information about notification service <strong>here</strong>.</p><p>3. <strong>Follow</strong> — Users should able to follow others and can be followed by others. Users get notification when they are followed by others.</p><p>4. <strong>News feed</strong> — System should generate news feed of images. News feed should be sorted based on relevancy and freshness.</p><h3>Nonfunctional requirement:</h3><p>1. Highly Scalable</p><p><em>2. Failover/Highly resilient to failures.</em></p><p><em>3. Consistency: eventual consistency.</em></p><p><em>4. Minimal Latency</em></p><h3><strong>Back of the Envelope Estimation</strong></h3><pre>RPS/QPS: <br>metric that measures how many requests or queries a system can handle <br>every second.Can be able to handle 2B monthly active user. Daily active <br>user would be 2 * 10^9 / 30 = 70M daily active user. So based on number of<br>requests</pre><pre>Storage space:</pre><pre>With 2 B active user with 50% of the user post 3 times a month. <br>1 Billion user 3 posts / 30days = 100M posts per day. <br>Each user can have 200 posts, so 200B posts in total. </pre><pre>Each post will be having post data and metadata in which should need storage <br>of 400TB. Assume each user posts 100 stories, so total story data storage <br>space needed for 100B stories 200TB.</pre><pre>Upload 10 images per day, with a maximum of 500 images per month. </pre><pre>Each image would be of size 10M. So you can expect 1.5 PB of storage <br>space per year. 4.5 PB for 3 years.</pre><pre>Average post size 10MB. Each user upload 10 images per day. That helps to <br>find storage requirements. Storage requirements for post <br>100Million/day * 10MB per post = 100TB storage.</pre><pre>200 comments per post, and an average of 50 likes per post, <br>should handle atleast 1Million likes and comments. Users should follow <br>1000 other users.</pre><pre>So total storage needed is 4.8 PB of storage.</pre><pre>Cache Needed: Based on the storage space needed by each object of Instagram, <br>Instagram would need approximately 312 TB of cache space to store frequently <br>accessed data efficiently, assuming the given percentages and average sizes. <br>It&#39;s not just post data, it also cache user profiles and follower/following <br>list and many more. </pre><pre>Compute resources: Concurrent operations as expectation would be 10000 <br>concurrent upload. That define no of threads needed in thread pool, <br>that define no of processor needed.</pre><pre>Compute resources or number of cpus needed based on concurrent uploads. <br>processing cores required 10,000. 1 Server 32 cores. <br>     Total server required is 3125.</pre><pre>Network bandwidth Average image upload time is 5 secs. <br>     Concurrent upload 10,000. Maximum network bandwidth 50GBps.</pre><h3>Databases:</h3><p>Different data stored in different databases that suits their nature and requirement. User informations being stored in any of the relational databases like <strong>sql or postgre-sql</strong> database.</p><p>Similarly when it comes to likes and comments it’s generally stored in <strong>graph database (neo4j)</strong>. The reason of having graph database is for its complex relationships between data entities such as users, post, follower and their comments as nodes and relationships as edges of the graph.</p><p>Separate <strong>Columnar database</strong> like Cassandra to store informations like user feeds, activities and counters.</p><p>Instagram add following indexes to <strong>elasticsearch</strong> to power its search functionalities, providing fast and scalable search capabilities</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h7sJUT4X5rjmYfQVj0Vl5w.png" /><figcaption>Relational Database schema</figcaption></figure><pre>CREATE INDEX idx_users_username ON Users(username);<br>CREATE INDEX idx_posts_user_id ON Posts(user_id);<br>CREATE INDEX idx_comments_post_id ON Comments(post_id);<br>CREATE INDEX idx_likes_post_id ON Likes(post_id);<br>CREATE INDEX idx_followers_follower_id ON Followers(follower_id);</pre><p>Elasticsearch organizes data into indices, documents, and fields:</p><ul><li><strong>Index</strong>: A collection of documents that have similar characteristics.</li><li><strong>Document</strong>: A single item in an index, expressed in JSON format.</li><li><strong>Field</strong>: A key-value pair within a document.</li></ul><h3>HLD</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FY30Z_Mf0qWmfuZob0ri8Q.png" /><figcaption>High Level Diagram</figcaption></figure><p>The app sends requests to the <strong>API Gateway</strong>, and API Gateway acts as an entry point for all client requests, handles authentication, rate limiting, and routing to appropriate backend services.</p><p>Before routing, the api gateway need check the <strong>content delivery network (CDN)</strong> for any cached content. CDN distributes static content (images, videos) globally for fast access. If the gateway doesn’t find the content, request will be forwarded to the appropriate backend service (e.g., fetching user feed, uploading media).</p><p><strong>Load balancer</strong> act as the distributed agent, distributes incoming traffic across multiple backend servers to ensure availability and scalability.</p><p>Instagram has <strong>notification Service</strong> for notifying user on likes, comments, follows, and other interactions.</p><p>It has <strong>Analytics Service</strong> that Collects and analyzes data for insights, such as user behavior, content performance, and system metrics and Search Service that Powers the search functionality, including user search, hashtag search, and location search.</p><p><strong>Search service</strong> has been integrates with Elasticsearch. Instagram internally uses distributed messaging queue like <strong>Kafka or Rabbit MQ</strong> to handle real-time updates and communication between services to ensure consistency and responsiveness. Instagram also uses distributed caches, like Redis or memcached to store query responses for scale and lower latency.</p><p>Instagram has separate <strong>metadata services</strong> to handle metadata for newly created posts, new followers or new images Or fetch information about user, image or followers.</p><p><strong>Fanout services</strong> is to get or retrieve follower list and send information to all their feeds and notify users.</p><p>Two major work flows in Instagram.</p><ol><li>Posting image/media/likes/comments on Instagram. (<strong>Write Service</strong>)</li><li>Fetch User feed (based on follower/Following information) or fetch specific user’s data. (<strong>Read service</strong>)</li></ol><p><strong>Write Service</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sK6Jw77dEXCmYdgfMeMGbg.png" /><figcaption>Write Service</figcaption></figure><p>There are two major services get executed when a user posts an image on Instagram. First the synchronous process (<strong>media service</strong>) responsible for uploading image content on file storage, persist media metadata on graph data storage, notify the user via <strong>user service</strong>. The <strong>feed service</strong> automatically triggered asynchronously, persist user activity in a columnar data storage (<strong>Cassandra</strong>) and triggered the process to precompute the feed for the followers.</p><p>🧩 <strong>Step-by-step breakdown</strong></p><ol><li>✅ <strong>User Service</strong> authenticates the user request.</li><li>🖼 <strong>Media Service</strong> handles image upload to a CDN and stores metadata (like caption, tags, etc.).</li><li>🧠 <strong>Feed Service</strong> kicks in asynchronously and stores the post in a columnar store (like Cassandra).</li><li>🧾 It calls the <strong>Follower Service</strong> to fetch the list of all followers.</li><li>📣 Then, the <strong>Fanout Service</strong> pushes this content to each follower’s feed.</li></ol><p>But for high-follower accounts, Instagram uses <strong>asynchronous fanout</strong>, <strong>batch processing</strong>, or even <strong>pull-based models</strong> to prevent overloading the system with 600M+ feed updates at once.</p><p>Here also there is a catch, if the follower is a <strong>celebrity user</strong>, we shouldn’t precompute feeds as they might have millions of followers that need extremely high number of compute resources and IO intensive process for fan-out all their followers. The feed data for celebrity user usually stored in distributed cache, which fetch only if the user really interested for. For <strong>non celebrity user</strong>, Instagram perform the <strong>precompute feed</strong> and store the results in CDN. So that the feed can be delivered to user as soon as the user comes online. When we say precompute a feed, what does it means?</p><p>Precomputing a feed involves generating and storing the feed content in advance to optimize performance and reduce latency when serving user requests. The high-level procedure for precomputing a feed as follows.</p><p><strong>Data collection</strong> by collecting data from various sources like databases, APIs, or user interactions.</p><p>With <strong>aggregation,</strong> we combine data from multiple sources and apply any necessary transformations or filters.</p><p>Apply algorithms to <strong>rank</strong> or <strong>score</strong> the content based on relevance, user preferences, or other criteria.</p><p>Apply algorithms to <strong>rank</strong> or <strong>score</strong> the content based on relevance, user preferences, or other criteria.</p><p>The ranking systems has been adopted to handle user’s feed to provide the best content in the users feed. The Home Feed Ranking System ranks the posts from the sources you follow based on factors like engagement, relevance, and freshness. Instagram uses <strong>ranking system</strong> by using the machine learning techniques that ranks the user’s feed by assigning scores to individual feeds (probability of click, like and comment). It’s using the feature management, in which each feed represented by feature vector, which contains info about user, the feed, the interactions which the user had with the people in the feed. With the deep Neural networks which takes several features (more then 100K dense features) through n-fold layers for predicting the probability of different events and the preferences it should get in the overall feed structure.</p><p>The precomputed messages being added in the user feed service queue. Once the message is added to the queue, the feed service makes a call to the <strong>follower service</strong> and then <strong>fanout service</strong> first fetch all the follower details and then the precomputed feed are stored in a fast-access data store, such as a cache or a specialized feed database. When a user requests their feed, it retrieve the precomputed data from the storage and deliver it with minimal processing.</p><h3>Read Service</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gSNzz3P9J1CY-i5ZRTvM-w.png" /><figcaption>Read Service</figcaption></figure><p>Read service usually triggered in case when Instagram fetch user’s feed or search for any particular user’s Instagram account. When the user requests for feed then there will be two parallel threads, one thread that fetch the users feed from non-celebrity users and the second thread fetch the feed from celebrity user which user follows. After that, user feed merge both the feed and returned the merged feeds to the user.</p><h3>Feed Generation</h3><h3>Overview</h3><p>Feed generation involves creating a personalized list of posts for users based on the users they follow and their interactions. The feed should be efficient in terms of data retrieval and should reflect the most relevant and recent posts.</p><h3>Generation Approach</h3><p><strong>Approach 1</strong>:</p><ol><li><strong>Get User IDs</strong>: Retrieve the user IDs of all users followed by the given user.</li><li><strong>Fetch Posts</strong>: For each user ID, get all posts made after a specific timestamp.</li><li><strong>Sort Posts</strong>: Sort these posts based on recency.</li><li><strong>Cache Top K Posts</strong>: Store the top K posts in a cache for quick access.</li><li><strong>Return Paginated Results</strong>: Return the next count number of posts after the specified offset. Support for infinite scrolling provided to fetch more related feed for user.</li></ol><h3>Performance Improvements</h3><p>To improve time complexity and response times:</p><ul><li><strong>Pre-generated Feeds</strong>: Continuously generate feeds on separate servers and store them in a user feed table. This allows quick retrieval without having to compute the feed on every request.</li><li><strong>Incremental Updates</strong>: When generating a user’s feed, query the user feed table for previously generated posts and generate new posts based on the timestamp of the last fetched post.</li></ul><h3>Storage Considerations</h3><ul><li><strong>Feed Size</strong>: If each user has an average of 50 posts in their feed, with each post being approximately 1KB, the storage size per user would be around 50KB. For 1 billion users, the total feed size would be approximately 50TB.</li></ul><h3>Distribution Methods</h3><ul><li><strong>Pull</strong>: Users request their feeds from the server based on actions like scrolling. However, this method may result in empty responses if no new posts have been generated.</li><li><strong>Push</strong>: The server can push new posts to followers using techniques like long polling. This method is useful for active users but may overwhelm the server if a user has many followers.</li><li><strong>Hybrid Approach</strong>: Implement a hybrid model where users with a large follower base use pull methods, while less active users receive updates through push mechanisms.</li></ul><h3>API implemenation</h3><h3>Signup API</h3><p><strong>Endpoint</strong>: /api/signup</p><p><strong>Method</strong>: POST</p><p><strong>Description</strong>: Registers a new user and stores their details in the users table.</p><pre>app.post(&#39;/api/signup&#39;, async (req, res) =&gt; {<br>    const { username, first_name, last_name, salted_password_hash, phone_number, email, bio, photo } = req.body;</pre><pre>    // Store profile photo in Object Storage (e.g., S3)<br>    const photo_url = await objectStorage.upload(photo);</pre><pre>    // Insert user data into the &#39;users&#39; table<br>    const query = `INSERT INTO users (username, first_name, last_name, salted_password_hash, phone_number, email, bio, photo_url)<br>                   VALUES (?, ?, ?, ?, ?, ?, ?, ?)`;<br>    await db.execute(query, [username, first_name, last_name, salted_password_hash, phone_number, email, bio, photo_url]);</pre><pre>    res.status(201).json({ message: &#39;User created successfully&#39; });<br>});</pre><h3>Login API</h3><p><strong>Endpoint</strong>: /api/login</p><p><strong>Method</strong>: POST</p><p><strong>Description</strong>: Authenticates a user and updates their last login time.</p><pre>app.post(&#39;/api/login&#39;, async (req, res) =&gt; {<br>    const { username, salted_password_hash } = req.body;</pre><pre>    // Verify user credentials<br>    const query = `SELECT * FROM users WHERE username = ? AND salted_password_hash = ?`;<br>    const [user] = await db.execute(query, [username, salted_password_hash]);</pre><pre>    if (!user) {<br>        return res.status(401).json({ message: &#39;Invalid credentials&#39; });<br>    }</pre><pre>    // Update last login time<br>    const updateQuery = `UPDATE users SET last_login = NOW() WHERE id = ?`;<br>    await db.execute(updateQuery, [user.id]);</pre><pre>    // Generate auth token (e.g., JWT)<br>    const auth_token = generateAuthToken(user.id);</pre><pre>    res.status(200).json({ auth_token, user });<br>});</pre><h3>Search User API</h3><p><strong>Endpoint</strong>: /api/search_user</p><p><strong>Method</strong>: GET</p><p><strong>Description</strong>: Returns public user data for a given search string.</p><pre>app.get(&#39;/api/search_user&#39;, authenticate, async (req, res) =&gt; {<br>    const { search_string } = req.query;</pre><pre>    // Search users by username, first_name, or last_name<br>    const query = `SELECT id, username, first_name, last_name, bio, photo_url FROM users<br>                   WHERE username LIKE ? OR first_name LIKE ? OR last_name LIKE ?`;<br>    const users = await db.execute(query, [`%${search_string}%`, `%${search_string}%`, `%${search_string}%`]);</pre><pre>    res.status(200).json(users);<br>});</pre><h3>Get User by ID API</h3><p><strong>Endpoint</strong>: /api/get_user_by_id/:id</p><p><strong>Method</strong>: GET</p><p><strong>Description</strong>: Returns public user data for a given user ID.</p><pre>app.get(&#39;/api/get_user_by_id/:id&#39;, authenticate, async (req, res) =&gt; {<br>    const { id } = req.params;</pre><pre>    // Fetch user data by ID<br>    const query = `SELECT id, username, first_name, last_name, bio, photo_url FROM users WHERE id = ?`;<br>    const [user] = await db.execute(query, [id]);</pre><pre>    if (!user) {<br>        return res.status(404).json({ message: &#39;User not found&#39; });<br>    }</pre><pre>    res.status(200).json(user);<br>});</pre><h3>Follow User API</h3><p><strong>Endpoint</strong>: /api/follow_user</p><p><strong>Method</strong>: POST</p><p><strong>Description</strong>: Adds a follow relationship between the user and the target user.</p><pre>app.post(&#39;/api/follow_user&#39;, authenticate, async (req, res) =&gt; {<br>    const { user_id, target_user_id } = req.body;</pre><pre>    // Insert follow relationship into &#39;followers&#39; table<br>    const query = `INSERT INTO followers (follower_id, followee_id) VALUES (?, ?)`;<br>    await db.execute(query, [user_id, target_user_id]);</pre><pre>    res.status(201).json({ message: &#39;User followed successfully&#39; });<br>});</pre><h3>Add Post API</h3><p><strong>Endpoint</strong>: /api/add_post</p><p><strong>Method</strong>: POST</p><p><strong>Description</strong>: Uploads a file to the object storage and adds post data to the posts table.</p><pre>app.post(&#39;/api/add_post&#39;, authenticate, async (req, res) =&gt; {<br>    const { file, caption, user_id } = req.body;</pre><pre>    // Upload file to Object Storage<br>    const file_url = await objectStorage.upload(file);</pre><pre>    // Insert post data into &#39;posts&#39; table<br>    const query = `INSERT INTO posts (user_id, caption, file_url) VALUES (?, ?, ?)`;<br>    await db.execute(query, [user_id, caption, file_url]);</pre><pre>    res.status(201).json({ message: &#39;Post created successfully&#39; });<br>});</pre><h3>Delete Post API</h3><p><strong>Endpoint</strong>: /api/delete_post</p><p><strong>Method</strong>: DELETE</p><p><strong>Description</strong>: Soft deletes a post by marking it as deleted in the posts table.</p><pre>app.delete(&#39;/api/delete_post&#39;, authenticate, async (req, res) =&gt; {<br>    const { user_id, post_id } = req.body;</pre><pre>    // Soft delete the post<br>    const query = `UPDATE posts SET is_deleted = 1 WHERE id = ? AND user_id = ?`;<br>    await db.execute(query, [post_id, user_id]);</pre><pre>    res.status(200).json({ message: &#39;Post deleted successfully&#39; });<br>});</pre><h3>Get Feed API</h3><p><strong>Endpoint</strong>: /api/get_feed</p><p><strong>Method</strong>: GET</p><p><strong>Description</strong>: Returns a list of posts from users followed by the given user.</p><pre>app.get(&#39;/api/get_feed&#39;, authenticate, async (req, res) =&gt; {<br>    const { user_id, count, offset, timestamp } = req.query;</pre><pre>    // Fetch feed posts<br>    const query = `SELECT posts.* FROM posts<br>                   JOIN followers ON posts.user_id = followers.followee_id<br>                   WHERE followers.follower_id = ? AND posts.created_at &gt; ?<br>                   ORDER BY posts.created_at DESC<br>                   LIMIT ? OFFSET ?`;<br>    const posts = await db.execute(query, [user_id, timestamp, count, offset]);</pre><pre>    res.status(200).json(posts);<br>});</pre><h3>Get User Posts API</h3><p><strong>Endpoint</strong>: /api/get_user_posts</p><p><strong>Method</strong>: GET</p><p><strong>Description</strong>: Returns a list of posts from a specific user.</p><pre>app.get(&#39;/api/get_user_posts&#39;, authenticate, async (req, res) =&gt; {<br>    const { user_id, count, offset } = req.query;</pre><pre>    // Fetch posts by user<br>    const query = `SELECT * FROM posts WHERE user_id = ? AND is_deleted = 0 ORDER BY created_at DESC LIMIT ? OFFSET ?`;<br>    const posts = await db.execute(query, [user_id, count, offset]);</pre><pre>    res.status(200).json(posts);<br>});</pre><h3>Post Like API</h3><p><strong>Endpoint</strong>: /api/post_like</p><p><strong>Method</strong>: POST</p><p><strong>Description</strong>: Adds a like to a post by the given user.</p><pre>app.post(&#39;/api/post_like&#39;, authenticate, async (req, res) =&gt; {<br>    const { user_id, post_id } = req.body;</pre><pre>    // Insert like into &#39;likes&#39; table<br>    const query = `INSERT INTO likes (user_id, post_id) VALUES (?, ?)`;<br>    await db.execute(query, [user_id, post_id]);</pre><pre>    res.status(201).json({ message: &#39;Post liked successfully&#39; });<br>});</pre><h3>Post Unlike API</h3><p><strong>Endpoint</strong>: /api/post_unlike</p><p><strong>Method</strong>: POST</p><p><strong>Description</strong>: Removes a like from a post by the given user.</p><pre>app.post(&#39;/api/post_unlike&#39;, authenticate, async (req, res) =&gt; {<br>    const { user_id, post_id } = req.body;</pre><pre>    // Delete like from &#39;likes&#39; table<br>    const query = `DELETE FROM likes WHERE user_id = ? AND post_id = ?`;<br>    await db.execute(query, [user_id, post_id]);</pre><pre>    res.status(200).json({ message: &#39;Post unliked successfully&#39; });<br>});</pre><h3>Add Comment API</h3><p><strong>Endpoint</strong>: /api/add_comment</p><p><strong>Method</strong>: POST</p><p><strong>Description</strong>: Adds a comment to a post.</p><pre>app.post(&#39;/api/add_comment&#39;, authenticate, async (req, res) =&gt; {<br>    const { user_id, post_id, comment } = req.body;</pre><pre>    // Insert comment into &#39;comments&#39; table<br>    const query = `INSERT INTO comments (user_id, post_id, comment) VALUES (?, ?, ?)`;<br>    await db.execute(query, [user_id, post_id, comment]);</pre><pre>    res.status(201).json({ message: &#39;Comment added successfully&#39; });<br>});</pre><h3>Delete Comment API</h3><p><strong>Endpoint</strong>: /api/delete_comment</p><p><strong>Method</strong>: DELETE</p><p><strong>Description</strong>: Deletes a comment from a post.</p><pre>app.delete(&#39;/api/delete_comment&#39;, authenticate,</pre><pre> async (req, res) =&gt; {<br>    const { user_id, comment_id } = req.body;</pre><pre>    // Delete comment from &#39;comments&#39; table<br>    const query = `DELETE FROM comments WHERE id = ? AND user_id = ?`;<br>    await db.execute(query, [comment_id, user_id]);</pre><pre>    res.status(200).json({ message: &#39;Comment deleted successfully&#39; });<br>});</pre><h3>Optimizations</h3><h3>In designing recommendation engine to select candidate.</h3><h3>📌 1. Building the Virtual Interest Graph (Seed Generation)</h3><p>Every user’s behavior — likes, comments, saves, follows — helps Instagram identify what content or creators the user is interested in. These points of interest are referred to as <strong>“seeds.”</strong></p><ul><li>A <strong>seed</strong> can be:</li><li>A <strong>post</strong> you liked or saved.</li><li>An <strong>author (creator)</strong> you follow or interact with.</li><li>Any <strong>media</strong> you engage with repeatedly.</li></ul><p>📍 <em>Think of seeds as the starting points or “anchor interests” for recommendations.</em></p><h3>📌 2. Using Seeds in the Recommendation Engine</h3><p>Once seeds are identified, they are passed into <strong>K-Nearest Neighbors (KNN) pipelines</strong> to find content that is <strong>similar</strong> to those seeds. The goal is to show the user more posts/accounts that align with their interests.</p><p>These KNN pipelines rely on two key machine learning strategies:</p><h3>🔷 A. Embeddings-Based Similarity</h3><h3>What is it?</h3><ul><li>Instagram represents users and accounts as <strong>vectors</strong> (called embeddings) in a multi-dimensional space.</li><li>These embeddings are learned using <strong>engagement data</strong> — like how often users like or view a certain account or content.</li></ul><h3>How it works:</h3><ul><li>The more two accounts are engaged with by similar sets of users, the <strong>closer</strong> their embeddings are.</li><li>So, if you like a post from creator A, and many users who also like A engage with creator B, the model sees A and B as similar.</li><li>The system uses <strong>vector similarity metrics</strong> (like cosine similarity) to find nearest neighbors.</li></ul><p>📍 <em>This lets Instagram recommend similar creators or content based on how they “cluster” together in this embedding space.</em></p><h3>🔷 B. Co-occurrence-Based Similarity</h3><h3>What is it?</h3><ul><li>This method tracks how often <strong>two pieces of content</strong> (or two creators) are engaged with <strong>together</strong> by users.</li></ul><h3>How it works:</h3><ul><li>If a large number of users view or like <strong>post A</strong> and <strong>post B</strong> in the same session or timeline, the model treats them as co-occurred.</li><li>These co-occurrence patterns are stored and used to <strong>build a graph of related content</strong>.</li></ul><h3>Thankyou for Reading!!!</h3><h3>If you found it valuable, hit a like ❤️ and consider subscribing for more such content every week.!!!</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6357ad62d50a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>