<?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 Azhagarasan Shiva on Medium]]></title>
        <description><![CDATA[Stories by Azhagarasan Shiva on Medium]]></description>
        <link>https://medium.com/@s.sivaguru11?source=rss-6508454635b7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*piOdAnHfvGaOgNrMA3YZWA.jpeg</url>
            <title>Stories by Azhagarasan Shiva on Medium</title>
            <link>https://medium.com/@s.sivaguru11?source=rss-6508454635b7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 21:25:57 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@s.sivaguru11/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[Fundamentals of Multi-threading]]></title>
            <link>https://medium.com/@s.sivaguru11/fundamentals-of-multi-threading-53881c081236?source=rss-6508454635b7------2</link>
            <guid isPermaLink="false">https://medium.com/p/53881c081236</guid>
            <category><![CDATA[performance-engineering]]></category>
            <category><![CDATA[multithreading]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[concurrency]]></category>
            <dc:creator><![CDATA[Azhagarasan Shiva]]></dc:creator>
            <pubDate>Tue, 12 May 2026 08:16:19 GMT</pubDate>
            <atom:updated>2026-05-14T11:47:00.508Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zZtfXi3NJkLq2QXNsBuuyw.png" /></figure><ul><li>I was motivated to write this article after interviewing 50+ mobile engineering candidates and noticing recurring gaps in their understanding of multithreading fundamentals. Many engineers lacked clarity about:</li><li>The relationship between cores, threads, and tasks.</li><li>The difference between CPU-bound and I/O-bound work.</li><li>How multithreading improves performance, along with the trade-offs involved, such as synchronization complexity, resource contention, and context-switching overhead.</li><li>How different frameworks implement concurrency, such as Android threads sharing memory while Flutter isolates use independent memory spaces.</li></ul><h4>Goal</h4><ul><li>Explain multithreading and related concepts simply, so engineers can build stronger intuition, make better design decisions, and write better prompts for AI coding tools.</li></ul><h4><strong>Understanding tasks — CPU vs IO vs GPU</strong></h4><p>Before diving into multithreading, it helps to understand the three types of work a computer handles and which hardware runs each one.</p><p><strong>CPU tasks — active computation</strong></p><ul><li>The CPU continuously executes instructions, transforms data, and runs business logic step by step.</li><li>Performance is bound by core count and computation speed.</li></ul><p><strong><em>Examples</em></strong><em>: JSON parsing, encryption/decryption, image decoding, compiling code.</em></p><p><strong>IO tasks — data transfer and waiting</strong></p><ul><li>IO tasks move data between the app and something external — a network, a disk, a database.</li><li>The CPU doesn’t do this work itself. It <strong>delegates</strong> to specialised controllers — Network, Storage, Memory — and <strong>waits for a response.</strong></li><li>This waiting is why IO tasks are the primary target for concurrency: the CPU is free to do other work while the data arrives.</li></ul><p><strong><em>Examples</em></strong><em>: API calls, file reads and writes, database queries, downloading files.</em></p><p><strong>GPU tasks — high-throughput parallel processing</strong></p><ul><li>The GPU runs thousands of small computations simultaneously across its parallel execution units.</li><li>While the CPU manages the overall workflow, <strong>the GPU handles the heavy lifting — processing pixels, frames, or model weights in massive batches.</strong></li><li>Designed for workloads where the same operation needs to happen on a huge amount of data at once.</li></ul><p><em>Examples: Video rendering, gaming graphics, AI/ML inference, image processing.</em></p><h4>From Tasks to Execution</h4><ul><li>A <strong>task</strong> is simply some work that needs to be done — like downloading a file, making an API call, rendering a screen, or processing game logic.</li><li>To execute this task, the computer relies on the <strong>CPU</strong>, which performs computations and executes instructions.</li><li>Inside the CPU are <strong>cores</strong>, the actual workers that perform the computation.</li><li>But applications cannot directly hand work to CPU cores. The operating system uses <strong>processes</strong> and <strong>threads</strong> as execution abstractions to organize and schedule that work.</li></ul><h4>What is a Process?</h4><ul><li>When you launch an app, the OS creates a <strong>process</strong> — think of it as a <strong>military base</strong> that owns everything needed to run that app: memory, resources, and code.</li><li>Just as a military base owns its armoury, a process owns its <strong>private memory space</strong> — completely isolated from other processes.</li><li><strong>Each app gets its own base</strong> — two apps can never share the same process, just like two armies never operate from the same base.</li><li>This is why a crash in one app never brings down another — <strong>two bases never share resources</strong>.</li><li>A process can’t do work on its own — it needs <strong>threads</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XaBYLIILrTAzHJnsCWb4-g.png" /></figure><h4>What is a Thread?</h4><ul><li>A core doesn’t execute tasks directly — the OS uses a <strong>thread</strong> as the actual unit of execution.</li><li>A thread carries everything needed to run: registers, instruction state, execution context, and scheduling information.</li><li>Threads are reusable — the same thread can be assigned different tasks over time, like a <strong>gun that fires different bullets.</strong></li><li><strong>Processes</strong> are created and managed by the OS; <strong>threads</strong> are created and managed by the application, inside a process.</li><li>When a process is terminated, all its threads are terminated too — a thread cannot exist without its parent process.</li><li>Every <strong>thread must ultimately run on a core </strong>— and how many threads a CPU can run at once depends on how many cores it has.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7sdetNcHoXdPGvS3uqhcGg.png" /></figure><h4>Cores &amp; Parallelism</h4><ul><li>Modern computers use a CPU chip containing multiple cores, such as 4, 8, 10, or 16 cores depending on the processor model.</li><li>The <strong>CPU chip</strong> can be thought of as the <strong>commander-in-chief,</strong> while the <strong>cores act as independent captains </strong>executing tasks in <strong>parallel</strong>.</li><li>Each core can independently handle tasks like video playback, email synchronization, notifications, file imports, or code compilation.</li><li>The ability of <strong>multiple cores to execute different tasks</strong> <strong>simultaneously</strong> is called <strong>parallelism</strong>.</li></ul><h4>Cores vs Threads</h4><ul><li>In most CPUs, <strong>1 core can execute 1 thread at a time</strong> → so an <strong>8-core CPU ≈ 8 parallel threads</strong>.</li><li>Technologies like <strong>Intel Hyper-Threading</strong> and <strong>AMD SMT</strong> allow each core to handle multiple logical threads → e.g. <strong>8 cores can appear as 16 threads</strong> to the OS</li><li><strong>The core-to-thread ratio is architecture-dependent</strong> — different CPU designs (desktop, mobile, Apple Silicon, server CPUs) expose different numbers of logical threads per core.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZZLRwzOUrT04_n0ZguGREw.png" /></figure><h4><strong>Main Thread</strong></h4><ul><li>Most applications run a <strong>main thread</strong> responsible for everything the user sees and touches — UI rendering, clicks, scrolling, and animations.</li><li>Because it handles all interaction, the main thread is <strong>latency-sensitive,</strong> any heavy work running on it blocks the UI, causing the app to freeze or drop frames.</li></ul><h4><strong>Worker Threads</strong></h4><ul><li>To keep the main thread free, applications offload heavy work to <strong>worker threads</strong> running in the background.</li><li>Worker threads <strong>handle CPU-intensive tasks</strong> like JSON parsing, image decoding, and video exporting, as well as <strong>IO-bound tasks like API calls, file processing, and database queries.</strong></li><li>Since worker threads run concurrently alongside the main thread, the UI stays responsive while the heavy work completes in parallel.</li><li>Applications can spin up as many worker threads as needed, limited only by workload and available system resources.</li></ul><h4>Concurrency vs Parallelism</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gn9NumvoGXTIz1NSvbxFkA.png" /></figure><h4><strong>Concurrency and parallelism solve different problems.</strong></h4><ul><li><strong>Concurrency</strong> improves responsiveness — it allows multiple tasks to make progress even when some are waiting on slow operations like network calls, disk I/O, or user input.</li><li><strong>Parallelism</strong> improves throughput — it splits CPU-heavy work across multiple cores so <strong>tasks run truly simultaneously.</strong></li></ul><p>Imagine a system needs to <strong>download and decrypt multiple files</strong>.</p><p><strong>Concurrency</strong></p><ul><li>A single worker handles multiple tasks by switching between them.</li><li>It starts downloading File A, pauses while waiting for network data, switches to File B to process its incoming chunk, then resumes File A where it left off.</li><li>Multiple tasks make progress, but they share the same worker — execution happens in turns, <strong>not at the same time</strong>.</li><li>On a single core, only one task is actually running at any moment; the rest is an illusion created by <strong>fast context switching</strong>.</li></ul><p><strong>Parallelism</strong></p><ul><li>Multiple workers handle multiple tasks simultaneously.</li><li>File A and File B are assigned to separate cores, so downloading or decryption can happen at exactly the same time.</li><li>This reduces total completion time, but consumes more CPU resources and power.</li></ul><p><strong>One-line summary</strong></p><ul><li><strong>Concurrency</strong>: one worker, many tasks, taking turns.</li><li><strong>Parallelism</strong>: many workers, many tasks, all at once.</li></ul><h4><strong>How to choose between concurrency and parallelism</strong></h4><ul><li>Choose <strong>parallelism</strong> when speed is the priority and the cost — more memory, higher CPU usage, increased battery drain — is an acceptable trade-off.</li><li>Choose <strong>concurrency</strong> when resource efficiency matters more than raw speed, since a single thread can juggle multiple tasks without the overhead of running them in parallel.</li></ul><h4><strong>True parallelism</strong></h4><ul><li>If machines only have 8 or 16 logical threads, <strong>why do hundreds of threads show up in Activity Monitor or Task Manager</strong>?</li><li><strong>Consider 100 threads created to download 100 files on an 8-core machine. At any given moment, only 8 threads are actively executing — the rest are queued, blocked on IO, or waiting for network data.</strong></li><li>As some downloads stall or complete, the OS scheduler steps in and hands their core time to waiting threads — allowing all 100 downloads to make progress over time.</li><li>This rapid switching of a core between threads is called <strong>context switching</strong>, and it creates the illusion that far more tasks are running simultaneously than the hardware actually supports.</li><li>Context switching isn’t free — saving and restoring thread state consumes time and CPU cycles, so excessive switching can hurt performance rather than help it.</li></ul><h4>Thread Pools</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-SkGeA--Xh_vmNHdlaHVcw.png" /></figure><ul><li>Creating a new thread for every task is expensive — there’s memory allocation, OS registration, and setup overhead each time.</li><li>A <strong>thread pool</strong> solves this by keeping a fixed set of worker threads alive and ready in memory — like a collection of <strong>fully assembled guns</strong> in an armoury, ready to be picked up the moment a new mission appears.</li><li>Instead of spawning a new thread per task, <strong>incoming work is queued and picked up by the next available worker </strong>— then that worker returns to the pool when done, ready for the next task.</li><li>This eliminates repeated creation overhead and caps the total number of threads, preventing uncontrolled growth that could exhaust system resources.</li></ul><p>Further reading: <a href="https://docs.oracle.com/javase/tutorial/essential/concurrency/pools.html">Oracle Java Tutorial — Thread Pools</a> — covers worker threads, task queues, and fixed thread pools.</p><h4><strong>Multithreading trade-offs</strong></h4><p><strong>Gains</strong></p><ul><li>In frontend applications, worker threads keep the UI smooth by offloading heavy work off the main thread and running independent operations in parallel.</li><li>In backend systems, multithreading improves throughput by handling more concurrent requests and workloads efficiently.</li></ul><p><strong>Trade-offs</strong></p><ul><li><strong>More threads don’t automatically mean better performance</strong> — each thread adds CPU usage, memory consumption, context-switching overhead, and battery drain.</li><li>The bigger challenge is <strong>shared mutable state</strong>: when multiple threads read and write the same data at the same time, the results can be unpredictable.</li><li>Imagine your bank account has ₹1 lakh. Two family members simultaneously deposit ₹1 lakh and ₹2 lakh. Both threads read the same opening balance, compute their update independently, and write back — so one deposit overwrites the other, leaving ₹2 lakh or ₹3 lakh instead of the correct ₹4 lakh. This is a <strong>race condition</strong>.</li><li>Avoiding this requires explicit coordination — using <strong>locks</strong>, <strong>mutexes</strong>, or <strong>atomic operations</strong> to ensure only one thread touches shared data at a time — <strong>making the code significantly more complex and bugs harder to reproduce and debug.</strong></li></ul><h4><strong>Profiling before scaling threads</strong></h4><ul><li>Most mobile applications <strong>perform well with a modest thread pool of 2–4 worker threads </strong>— adding more beyond what the workload demands increases CPU usage, memory overhead, battery drain, and context-switching costs.</li><li>Always profile first to understand where the real bottleneck is before reaching for more threads.</li></ul><h4><strong>Conclusion</strong></h4><ul><li>Multithreading is powerful, but the fundamentals matter — understanding tasks, processes, threads, cores, concurrency, and parallelism gives you the mental model to make better decisions in day-to-day development.</li><li>The next article breaks down how Android, iOS, and Flutter implement multithreading behind the scenes, and how that shows up in practice.</li></ul><p>Happy multithreading ⚡⚡</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=53881c081236" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[System Design | Analytics Engine | API & Resource Estimation]]></title>
            <link>https://medium.com/@s.sivaguru11/system-design-analytics-engine-api-resource-estimation-fc50e55fe8cf?source=rss-6508454635b7------2</link>
            <guid isPermaLink="false">https://medium.com/p/fc50e55fe8cf</guid>
            <category><![CDATA[system-architecture]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[high-level-design]]></category>
            <category><![CDATA[system-design-course]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <dc:creator><![CDATA[Azhagarasan Shiva]]></dc:creator>
            <pubDate>Tue, 08 Apr 2025 06:10:18 GMT</pubDate>
            <atom:updated>2025-04-08T09:00:41.077Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xfNfRLEh-sEGKycYI0Hk_A.jpeg" /></figure><ul><li>This article delves into the <strong>API design, data schema, and resource estimation for the analytics engine</strong>, offering insights into system scalability and performance characteristics.</li><li>Before diving into the system estimations, it’s recommended to first go through the “<a href="https://medium.com/@s.sivaguru11/system-design-analytics-engine-78e3e5cc517d"><strong>Analytics Engine | High-Level Architecture</strong></a>” discussion and its real-world use cases for better context.</li></ul><h3>Event Schema</h3><ul><li>Analytics events adhere to a flexible schema but are defined and versioned within a <strong>schema registry</strong>.</li><li>Each schema specifies <strong>Mandatory fields for consistency </strong>(e.g., event_type, user_id) &amp; <strong>Optional fields</strong> (e.g., device_info, ip_address) for additional context</li><li>This structure enables <strong>reliable validation</strong>, <strong>clean schema evolution</strong>, and <strong>efficient storage and processing</strong> on the backend.</li></ul><pre>{<br>  &quot;event_type&quot;: &quot;video_liked&quot;,<br>  &quot;version&quot;: 2,<br>  &quot;schema&quot;: {<br>    &quot;required&quot;: [&quot;video_id&quot;, &quot;user_id&quot;, &quot;event&quot;, &quot;timestamp&quot;],<br>    &quot;properties&quot;: {<br>      &quot;event&quot;: { &quot;type&quot;: &quot;string&quot; },<br>      &quot;timestamp&quot;: { &quot;type&quot;: &quot;integer&quot; },<br>      &quot;user_id&quot;: { &quot;type&quot;: &quot;string&quot; },<br>      &quot;autoplay&quot;: { &quot;type&quot;: &quot;boolean&quot; },<br>      &quot;quality&quot;: { &quot;type&quot;: &quot;string&quot; }<br>    }<br>  }<br>}</pre><h3>Client Database Schema</h3><ul><li>Clients such as web and mobile write events to local storage, adhering to a predefined database schema before uploading them to the server.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/577214e339ec26f70c6f4dd42f800d3f/href">https://medium.com/media/577214e339ec26f70c6f4dd42f800d3f/href</a></iframe><ul><li>The <strong>payload</strong> attribute represents the analytics event to be sent to the server. In case of a failure, the client retries the upload, but only up to a predefined threshold.</li><li>The following is a sample <strong>Event Payload</strong></li></ul><pre>{<br>  &quot;event_type&quot;: &quot;video_liked&quot;,<br>  &quot;timestamp&quot;: 1712476800000,<br>  &quot;user_id&quot;: &quot;user_123&quot;,<br>  &quot;video_id&quot;: &quot;video_83331&quot;,<br>  &quot;schema_version&quot;: 1,<br>  &quot;properties&quot;: {<br>    &quot;device&quot;: &quot;mobile&quot;,<br>    &quot;app_version&quot;: &quot;5.4.0&quot;,<br>    &quot;like_source&quot;: &quot;recommendation_feed&quot;,<br>    &quot;network_type&quot;: &quot;wifi&quot;<br>  }<br>}</pre><h3>API Design</h3><ul><li>The system requires one API for <strong>uploading events</strong> and two APIs for <strong>schema management</strong></li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c7411ed77cdb78ccefd241354129d6e2/href">https://medium.com/media/c7411ed77cdb78ccefd241354129d6e2/href</a></iframe><h3>System Assumptions</h3><ul><li><strong>User Base</strong>: 20 million</li><li><strong>Daily Active Users (DAU)</strong>: 10 million (50% of total users)</li><li><strong>Average Events per User per Day</strong>: 100</li><li><strong>Daily event volume </strong>:<br> DAU = 10 million<br> Average events per user = 100<br> Total events per day = 10 million * 100 = <strong>1 billion events/day</strong></li><li><strong>Average Uncompressed Event Size</strong>: 2 KB per event</li><li><strong>Event Upload Batch size per second : 10 events</strong></li></ul><h3>Resource Estimation</h3><h4>Server Estimation</h4><ul><li>A modern large instance can typically handle around <strong>50,000 concurrent WebSocket connections</strong>.</li><li><strong>Peak Concurrent Connections</strong>: 10 million</li><li><strong>Connections per Server</strong>: 50,000</li><li><strong>Estimated Servers Required</strong>: = 10 million / 50K = 200 servers</li><li>While this is a <strong>peak estimate</strong>, we can start with <strong>50 servers</strong> and <strong>scale horizontally</strong> as traffic grows.</li><li><strong>Note</strong> : <em>Actual capacity should be determined through </em><strong><em>profiling</em></strong><em>, as real-world performance varies based on multiple factors like </em><strong><em>application load</em></strong><em>, </em><strong><em>concurrency model</em></strong><em> (e.g., async vs thread-per-connection), </em><strong><em>connection lifecycle handling &amp; architecture choices</em></strong><em> such as the </em><strong><em>framework.</em></strong></li></ul><h3>Incoming bandwidth</h3><ul><li>To estimate peak bandwidth requirements, we assume <strong>all active users upload their event batches concurrently within a single second</strong>.</li><li>This represents the <strong>worst-case load scenario</strong> and helps us size the system for <strong>maximum ingestion capacity.</strong></li></ul><h4>Calculation</h4><ul><li><strong>DAU (Daily Active Users)</strong>: 10 million</li><li><strong>Batch size per upload</strong>: 10 events</li><li><strong>Compressed event size</strong>: 500 bytes (using Brotli, Gzip)</li><li><strong>Upload per user per batch:</strong><br> 10 events × 500 bytes = 5,000 bytes ≈ 5 KB</li><li><strong>Total upload size:</strong><br> 10 million users × 5 KB = 50 GB</li><li><strong>Peak Incoming bandwidth required (in bits)</strong>:<br> 50 GB × 8 = 400 Gbps</li><li>Let’s start with 100 Gbps capacity and scale horizontally based on metrics like <strong>Ingestion traffic, Throughput metrics</strong>, e.g. ACK rate to clients in WebSocket, Events processed per second by backend systems</li></ul><h4>Event Streamer Storage Calculation</h4><ul><li>Event Streamer (Kafka) is a key component that enables <strong>event replays, crash recovery, and buffering</strong> in case of downstream delays.</li><li>The system uses two Kafka clusters: one before processing (handling raw events) and one after processing (handling cleaned and enriched events).</li><li><strong>Retention period</strong> for both Kafka clusters is <strong>1 day</strong>.</li><li><strong>Raw Stream</strong> (Pre-processed): <strong>Compressed</strong> event size is <strong>500 bytes.</strong></li><li><strong>Daily event volume</strong>: 1 billion events.</li><li><strong>Storage required for raw stream</strong> = 1 billion events × 500 bytes = 500 GB/day.</li><li><strong>Processed Stream</strong> (Post-enrichment): Uncompressed size is 1 KB per event, <strong>compressed</strong> event size reduces to approximately <strong>300 bytes.</strong></li><li><strong>Storage required for processed stream </strong>= 1 billion events × 300 bytes = 300 GB/day.</li></ul><h3>Storage Estimation</h3><p>Before estimating storage requirements, let’s first define the data retention policy.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/99c104d966722620e51835cb264d32b4/href">https://medium.com/media/99c104d966722620e51835cb264d32b4/href</a></iframe><h4>Data Warehouse Storage</h4><ul><li><strong>Average Event Size</strong>: 1 KB (after cleanup and enrichment, ~50% of original)</li><li><strong>Storage per Day</strong>:<strong> Total Events per day</strong> * <strong>Average Event Size</strong><br> 1 billion events * 1 KB = 1 TB/day</li><li><strong>Storage per Year</strong>:<br> 1 TB/day * 365 = 365 TB/year</li><li><strong>Total Warehouse Storage required :</strong><br>Storage per Year<strong> </strong>* 2 <strong>= 730 TB</strong></li></ul><h4>Raw Storage</h4><ul><li>Since raw storage retains the same event data as the data warehouse but in compressed form</li><li>We can derive its size based on warehouse estimates and apply a compression ratio. This helps us estimate long-term archival.</li><li><strong>Warehouse Storage</strong>: 365 TB/year (based on 1 TB/day retention)</li><li><strong>Compression Factor</strong>: Raw events are stored using compression (e.g., Brotli), reducing size by 60%</li><li><strong>Raw Storage Estimate</strong>:<br>Raw storage per year = 40% of warehouse = 0.4 * 365 TB = 146 TB/year<br>For 5 years = 146 TB * 5 = 730 TB</li><li>Raw storage requirement is approximately <strong>730 TB over 5 years</strong> assuming 60% compression efficiency.</li></ul><h4>Time series Database Storage</h4><ul><li>Time Series DB storage is estimated based on the use case discussed in the high-level architecture.</li><li>We’re tracking trending video metrics across multiple regions, aggregated every 10 minutes.</li><li><strong>Regions</strong>: 10,000 approximately (e.g., country + state combinations)</li><li><strong>Trending Videos per Region</strong>: 25</li><li><strong>Aggregation Frequency</strong>: Every 10 minutes</li><li><strong>Time Windows per Day</strong>: 144 (24 * 6)</li><li><strong>Fields per Row</strong>: videoId, regionCode (US-NY), viewCount, likeCount, shareCount, score, region, timestamp</li><li><strong>Estimated Row Size</strong>: 150 bytes approximately</li><li><strong>Rows per 10 Minutes</strong>: 10,000 * 25 = 250,000</li><li><strong>Rows per Day</strong>: 250,000 * 144 = 36,000,000</li><li><strong>Storage per Day</strong>: 36,000,000 * 150 bytes = 5.4 GB</li><li><strong>Storage for 7 Days</strong>: 5.4 GB * 7 = <strong>37.8 GB</strong></li></ul><h3>Resource Estimation Summary</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b67c82706bcb346e8e126dfd1795fa04/href">https://medium.com/media/b67c82706bcb346e8e126dfd1795fa04/href</a></iframe><ul><li>The resource estimation has been calculated for a single instance of the component. Multiply the values by the required replication factor based on business needs to determine the total resource requirement</li><li>Hope this exhaustive calculation gave you a clear picture of the scale and demands of the system we’ve designed.</li><li><strong>Take care!</strong>✋, Catch you in the next design challenge!</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fc50e55fe8cf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[System Design | Analytics Engine]]></title>
            <link>https://medium.com/@s.sivaguru11/system-design-analytics-engine-78e3e5cc517d?source=rss-6508454635b7------2</link>
            <guid isPermaLink="false">https://medium.com/p/78e3e5cc517d</guid>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[analytics]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <dc:creator><![CDATA[Azhagarasan Shiva]]></dc:creator>
            <pubDate>Fri, 04 Apr 2025 11:47:19 GMT</pubDate>
            <atom:updated>2025-04-08T09:00:21.234Z</atom:updated>
            <content:encoded><![CDATA[<h3>System Design | Analytics Engine | High-level Architecture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yFeNYuj8bTJOMdt4MHKqjg.png" /></figure><h4>Introduction</h4><ul><li>Businesses rely on analytics engines to convert data into strategic insights, enabling <strong>smarter decisions</strong> and <strong>continuous performance improvement</strong>.</li><li>To keep the reading experience meaningful and engaging, we’ll walk through the architecture using real-world use cases.</li><li><strong>Trending Videos (Real-Time Processing) : </strong>Detecting trending content as it gains traction.</li><li><strong>Personalised Recommendations (Batch Processing) : </strong>Analysing historical data to refine content recommendations.</li></ul><h4>Functional Requirements</h4><ul><li><strong>Real-time Processing: </strong>Should process large volumes of streaming data with low latency.</li><li><strong>Batch Processing</strong> : Support batch data ingestion and processing for historical analysis</li><li><strong>Scalability: </strong>Scale to handle increasing data volume and velocity.</li><li><strong>Multi-source Ingestion: </strong>Support multiple data sources (Web socket, APIs, databases, etc.).</li><li><strong>Aggregation &amp; Querying: </strong>Support complex aggregations and ad-hoc queries over large datasets.</li></ul><h4>Non-Functional Requirements</h4><ul><li><strong>High Availability:</strong> Ensure <strong>fault tolerance </strong>and minimal downtime through redundancy and failover strategies.</li><li><strong>Scalability</strong>: Support horizontal and vertical scaling to handle growing data volume and user load seamlessly.</li><li><strong>Low Latency: </strong>&lt;100ms latency for real-time path</li><li><strong>Security</strong>: enforce authentication for all external data source and ensure data encryption for stored data</li><li><strong>Data Durability</strong>: Guarantee data persistence and recoverability through persistent storage, replication, and backups.</li><li><strong>Cost Optimisation: </strong>Balance performance and infrastructure costs.</li></ul><h3>System Architecture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Felrng6kBeHWPI8ECumBOg.png" /><figcaption>Analytics Engine Architectire</figcaption></figure><h4><strong>Client</strong></h4><ul><li>Uses <strong>WebSocket</strong> as the primary channel to push analytics data in real-time.</li></ul><h4><strong>Load Balancer (HAProxy)</strong></h4><ul><li>Ensures <strong>even traffic distribution</strong> across services.</li><li>Performs <strong>health checks</strong> and routes traffic only to <strong>healthy backend nodes</strong>.</li></ul><h4><strong>Service Discovery &amp; Routing</strong></h4><ul><li>Continuously <strong>monitors service instances</strong> and their health.</li><li>Supports <strong>dynamic routing</strong> based on availability and performance of downstream services.</li></ul><h4>Ingestion Gateway</h4><ul><li>Manages <strong>authentication, authorisation, rate limiting</strong>, and SSL <strong>termination</strong></li><li>Routes requests to appropriate services based on API or WebSocket.</li></ul><h4><strong>Ingestion Service — </strong>WebSocket</h4><ul><li>Connection initiated via the <strong>gateway</strong>, then <strong>persisted directly</strong> with backend services after a successful handshake.</li><li>This reduces gateway overhead and <strong>improves real-time performance</strong> by eliminating unnecessary network hops.</li></ul><h4>Ingestion Service — API</h4><ul><li>Always routed through the <strong>Ingestion Gateway</strong>, as each request is stateless and independent.</li><li>Acts as a <strong>fallback path</strong> when WebSocket fails due to issues like proxy restrictions, server resource limits, or network instability.</li></ul><h4>Ingestion Service — Database Sync</h4><ul><li>Uses <strong>Change Data Capture (CDC)</strong> (e.g., <strong>Debezium</strong>) to stream analytics-related DB changes via <strong>Kafka</strong>.</li><li>Not used in the current design but relevant for <strong>legacy system integration</strong> scenarios.</li></ul><h4>Design Strategy</h4><ul><li><strong>Low-Latency Design : Directly writes to an event streamer</strong> (e.g., Kafka) to enable high-throughput ingestion.</li><li><strong>High Consistency Design : Writes first to a database</strong> to act as the single source of truth and uses CDC-based sync services (e.g., Debezium) to stream change</li></ul><h4>Design Choice</h4><ul><li><strong>Real-time streaming: </strong>Since we need <strong>high-throughput, low-latency processing</strong>, we ingest data via Kafka for real-time streaming.</li><li><strong>Reliability &amp; Persistence: </strong>A Batch processor writes data to persistent storage, ensuring <strong>long-term durability.</strong></li><li><strong>Design Trade-offs: </strong>Prioritises speed while acknowledging consistency challenges such as <strong>delayed analytics data availability for querying</strong>, duplicate handling and ordering issues.</li></ul><h4>Stream Processor (Validation, Enrichment &amp; Routing)</h4><ul><li><strong>Validation</strong>: Ensures incoming messages from event streamer adhere to the expected schema, <strong>dropping malformed or potentially malicious data</strong> (e.g., to prevent SQL injection or XSS).</li><li><strong>Enrichment</strong>: Cleans data by removing unnecessary fields and appending useful metadata (e.g., inferred location codes) for downstream insights.</li><li><strong>Routing</strong>: Publishes the processed events to another Kafka, making them available for both real-time and batch processors.</li></ul><h4>Raw vs Processed Analytics Event</h4><ul><li>Sample <a href="https://github.com/jeishiva/system-design-metadata/blob/main/analytics/raw_event.json"><strong>Raw Event</strong></a></li><li>Sample <a href="https://github.com/jeishiva/system-design-metadata/blob/main/analytics/processed_event.json"><strong>Processed Event</strong></a><strong> (</strong>post-cleanup and enrichment with state &amp; country codes)</li></ul><h4>Geolocation Enrichment via Geohash</h4><ul><li>During preprocessing, latitude and longitude are converted into <strong>geohashes</strong> with a fixed precision of 5 (eg. t1t89), which serve as<strong> compact spatial identifiers.</strong></li><li>These geohashes are then used to perform fast lookups against a precomputed table that maps them to country and state codes.</li><li>This enables efficient regional aggregation (e.g.,<strong> </strong><strong>US-CA, </strong><strong>IN-MH</strong>) for use cases like <strong>location-based trending analytics</strong> during stream processing.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*azZkiFvC6oy8i1U9c3ONAA.png" /><figcaption>Geo hashing table look up</figcaption></figure><h4>Understanding Trending Videos</h4><ul><li>A video is marked as <strong>trending</strong> when it experiences a <strong>sharp increase in engagement</strong> (views, likes, shares) within a short time window.</li><li>Each user action (e.g., video watch, comment, like) is assigned a score:</li><li><strong>Video Watch</strong> → 5 points , <strong>Comment</strong> → 1 point, <strong>Like</strong> → 2 point</li><li>Every <strong>10 minutes</strong>, we aggregate points by videoId, and videos with the highest scores are considered <strong>trending</strong>.</li></ul><h3>Real-Time Processing</h3><p>To analyse video trends, we perform <strong>aggregation and windowing</strong> on <strong>videoId</strong> using <strong>stream processing frameworks</strong> like <strong>Apache Flink</strong>.</p><ul><li><strong>Sliding window aggregations</strong> are used to measure engagement over recent intervals (e.g., last 10 minutes).</li><li><strong>Aggregation by Country &amp; Region:</strong> Enables localised trending analysis.</li><li><strong>Time-Series Storage: </strong>Processed results are stored in a <strong>time-series database</strong> optimized for <strong>range queries</strong>.</li><li><strong>Querying</strong>: The Content Service fetches trending videos from a <strong>time-series database</strong> (or <strong>ClickHouse</strong> for real-time queries) using filters like time, region, and country.</li><li><strong>Enrichment</strong>: Retrieves video details (title, thumbnail, creator, category) from the <strong>Video Metadata Service</strong>.</li><li><strong>Delivery</strong>: Video is enriched using the metadata service and delivered to clients via <strong>WebSockets (push)</strong> or <strong>APIs (pull)</strong>, tailored to user context.</li></ul><h4>Sample Trending Data</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X_Z9kII12TauRnViNM0hNw.png" /><figcaption>sample trending data</figcaption></figure><h3>Batch Processing &amp; Storage</h3><h4><strong>Batch Processing</strong></h4><ul><li>Our design uses <strong>Apache Spark</strong> as our batch processor for efficient micro-batch processing of data from <strong>Kafka</strong>.</li><li>Spark <strong>cleans, enriches, and transforms</strong> data based on business rules before writing it to <strong>S3</strong> for long-term storage.</li><li>Our system follows a <strong>decoupled architecture</strong> where <strong>compute (Spark)</strong> and <strong>storage (data warehouse)</strong> are separated, allowing better scalability and flexibility.</li><li>In tightly coupled systems (e.g., computing top trending videos during ingestion), <strong>HDFS</strong> can be a better fit as it combines compute and storage.</li></ul><h4><strong>Raw Storage</strong></h4><ul><li><strong>S3</strong> serves as a <strong>cost-effective, raw long-term storage solution</strong> for large-scale data and acts as a <strong>backup and disaster recovery</strong> layer</li><li>Data is moved between <strong>cold and archive tiers</strong> based on <strong>retention policies</strong> to optimise storage costs.</li></ul><h4>Data Warehouse for Analytics</h4><ul><li><strong>ETL tools</strong> (e.g., Airflow, Apache NiFi) extract data from raw storage and load it into a <strong>data warehouse</strong> (e.g., Snowflake)</li><li>Use the warehouse’s native engine (e.g., BigQuery SQL, Snowflake UI) for <strong>ad-hoc, interactive, and complex analytics queries, </strong>ideal for dashboards &amp; explorations.</li></ul><h4><strong>Feature Store</strong></h4><ul><li><strong>Feature</strong> refer to the <strong>preprocessed data</strong> that the model uses to generate video recommendations. Examples of such features include <strong>Weekly trending videos, Close categories, Watch history</strong></li><li><strong>Feature Store</strong> like feast is a <strong>Centralised Storage</strong> that stores and manages features in a single repository, ensuring consistent access across ML models.</li></ul><h4><strong>Data Orchestration</strong></h4><p>To load data into the feature store, we can use either:</p><ul><li><strong>Built-in Jobs</strong>: From data warehouses (e.g., Snowflake Tasks, BigQuery Scheduled Queries) — ideal for simple, SQL-based feature generation.</li><li><strong>External Multi-Step Workflows</strong>: (e.g., Airflow) — suitable for complex pipelines that involve multiple systems. External workflows offer greater control (retries, scheduling, dependency management) but may be overkill for simple tasks.</li></ul><h4><strong>ML-Driven Recommendations</strong></h4><ul><li><strong>Feature Store Sync</strong>: ML models use <strong>Feature Store Sync</strong> to access consistent, preprocessed features for candidate generation.</li><li><strong>Consistency</strong>: Using the same features for both training and inference ensures stable model performance and avoids discrepancies.</li><li><strong>Personalization</strong>: Reusing features across models speeds up recommendations and improves personalization for users.</li></ul><h3><strong>Visualising Candidate Generation</strong></h3><p><strong>Recommendation can be complex</strong>, but we’ll break it down with a simple example to make it easier to understand.</p><p><strong>User watch history</strong> and <strong>precomputed candidate videos</strong> (stored in the Feature Store) work together to generate personalised recommendations:</p><ul><li><strong>Precomputed Candidate Videos</strong>: A curated set of videos generated from trending content, most liked videos, and category-based data, stored in the Feature Store for consistent access.</li><li><strong>Personalisation</strong>: ML models derive user preferences from their watch history and interactions (like, share, etc.), and match them with the precomputed candidates to recommend the most relevant content.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aMuTXYAR32NYZl_rXdD3lw.png" /></figure><h3>Technical Choices and Rationale</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MoqESV-igQ55GWBAQv-C8A.png" /><figcaption>tech stack</figcaption></figure><h3>Key Challenges &amp; Solutions</h3><h4>Client Network failure</h4><ul><li>The client implements an <strong>exponential backoff strategy</strong> for retrying event uploads, <strong>ensuring reliable data delivery by requiring ACK-based confirmation for each batch</strong>, even during temporary failures.</li></ul><h4><strong>Data Flooding Prevention</strong></h4><p>We used a push-based method, which could lead to overload of events or potential attacks. To fix this, let’s add</p><ul><li><strong>Connection Throttling</strong>: <strong>Limit</strong> the number of<strong> active connections</strong> per IP or user to prevent abuse.</li><li><strong>Rate Limiting</strong>: Restrict the <strong>number of analytical or engagement events</strong> per user/connection within a defined time window.</li></ul><h4>Deduplicating User Events</h4><ul><li>Generate a unique hash (<strong>userId + videoId + eventType</strong>) and store the hash in <strong>Redis</strong> with a TTL to identify <strong>duplicate events</strong> within a time window.</li><li>Use <strong>MurmurHash</strong> for speed, or <strong>SHA-256</strong> if avoiding collisions is critical.</li></ul><h4>System Scalability</h4><ul><li><strong>Horizontal Autoscaling:</strong> <strong>Automatically scale instances</strong> or pods based on real-time metrics (e.g.,<strong> CPU, memory, network, Redis connections</strong>) using tools like Kubernetes HPA or AWS Auto Scaling to handle workload fluctuations efficiently.</li><li><strong>Load Balancing :</strong> Use Nginx to evenly distribute incoming requests across multiple instances, preventing bottlenecks, optimising resource usage</li><li><strong>Scalable Event Pipeline</strong>: Batch and compress events before streaming them to downstream components, reducing load and improving system scalability.</li></ul><h4>High Availability &amp; Resilience</h4><ul><li>Replicate and cluster services (e.g., Redis, databases) to eliminate single points of failure.</li><li>Use <strong>containerisation</strong> with Kubernetes for auto-scaling, self-healing, failover, and <strong>multi-zone deployments</strong> to ensure high availability.</li></ul><h4>WebSocket Scalability</h4><ul><li><strong>Async Servers</strong>: Use lightweight, event-driven servers like Go or Netty to efficiently manage many WebSocket connections with low resource usage.</li><li><strong>High-Throughput: Buffer</strong> events in-memory and flush batches every 500 ms or once they reach 1 MB, <strong>compressing</strong> the payload with GZIP or Brotli before sending.</li><li><strong>Load Balancers</strong>: Use <strong>connection-aware load balancers</strong> (like HAProxy or NGINX) with sticky sessions to keep WebSocket connections on the same server and avoid reconnecting.</li><li><strong>Redis TTL with Heartbeats</strong>: Use Redis with time-to-live (TTL) and regular <strong>heartbeats</strong> to manage active WebSocket sessions, automatically removing inactive ones to save resources.</li></ul><h4>Fault Tolerance</h4><ul><li><strong>Checkpointing (Flink)</strong>: Periodically save state to resume from the last consistent point after failures.</li><li><strong>WAL &amp; Offset Tracking (Spark)</strong>: Recover from crashes in micro-batch jobs using write-ahead logs and Kafka offsets.</li><li><strong>Kafka Replay</strong>: Both systems can reprocess data by replaying events from Kafka using committed offsets.</li><li><strong>Exactly-Once Guarantees</strong>: Use <strong>idempotent writes</strong> and <strong>transactional IDs</strong> to prevent duplication during retries and ensure reliable, once-only processing.</li></ul><h4>Security</h4><ul><li><strong>Authentication &amp; Access Control</strong>: Use JWT and role-based permissions.</li><li><strong>Encryption</strong>: <strong>TLS</strong> for data in transit &amp; <strong>AES-256</strong> for data at rest.</li></ul><h4>Disaster Recovery &amp; Long-Term Storage</h4><ul><li>Periodic backups to <strong>S3</strong> and ensure <strong>multi-region and multi-AZ</strong> configurations to ensure durability.</li></ul><h4>Engagement Metric (Recommendations &amp; Trending)</h4><ul><li><strong>A/B Testing</strong>: Experiment with different trending, recommendation strategies to compare performance and optimise user engagement.</li><li><strong>Feedback Loop</strong>: Feed user interactions (likes, watch time, skips) back into ML models to continuously refine and personalize recommendations..</li></ul><h4>Monitoring &amp; Observability</h4><ul><li><strong>Critical Metrics: </strong>Measure<strong> client-to-Kafka latency, processing lag, feature freshness</strong>, and <strong>trending latency</strong> — time taken for events to reflect in trending videos.</li><li><strong>System Metrics</strong>: Track CPU, memory, disk, and network with Prometheus &amp; Grafana; trigger <strong>alerts</strong> on <strong>threshold breaches</strong>.</li><li><strong>Centralised Logging</strong>: Use <strong>Loki</strong> to aggregate logs for <strong>quicker debugging</strong> and system insights.</li><li><strong>Distributed Tracing</strong>: Trace request flows across services using tools like <strong>OpenTelemetry</strong> to <strong>identify bottlenecks</strong> and <strong>latency</strong> issues.</li></ul><h3>Final Thoughts</h3><ul><li>We examined the system architecture through real-world use cases, sample data, technical decisions, and key challenges.</li><li>Hopefully, this gave a clear understanding of the design. <strong>Take care!</strong></li><li><strong>Up next:</strong> <a href="https://medium.com/@s.sivaguru11/system-design-analytics-engine-api-resource-estimation-fc50e55fe8cf"><strong>Resource estimations and API design</strong></a><strong>.</strong></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=78e3e5cc517d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[System Design | Youtube | High-Level Architecture]]></title>
            <link>https://medium.com/@s.sivaguru11/system-design-youtube-part-2-5fdd47b4de25?source=rss-6508454635b7------2</link>
            <guid isPermaLink="false">https://medium.com/p/5fdd47b4de25</guid>
            <category><![CDATA[storage]]></category>
            <category><![CDATA[high-level-design]]></category>
            <category><![CDATA[system-architecture]]></category>
            <dc:creator><![CDATA[Azhagarasan Shiva]]></dc:creator>
            <pubDate>Mon, 31 Mar 2025 07:02:13 GMT</pubDate>
            <atom:updated>2025-04-08T06:37:10.037Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_xOt64-farr2lL_G5qznig.jpeg" /><figcaption>cover image</figcaption></figure><ul><li>This article explores YouTube’s high-level architecture, core data workflows, and storage strategies, along with the rationale behind key design decisions.</li><li><strong>Deep-Dive Analysis:</strong> Each aspect is examined in detail, covering optimisations for <strong>scalability, performance, security and fault-tolerance</strong>.</li></ul><p>Missed the first part? No worries! Catch up here <a href="https://medium.com/p/7db0ae89c95b"><strong>Youtube | Part 1</strong></a></p><h3>Architecture Overview</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TFVEHy-ROV6vX8aUzArQNA.png" /></figure><h4>Load Balancer</h4><ul><li><strong>Request Distribution:</strong> The Load Balancer directs client requests to the API Gateway, ensuring even traffic distribution and preventing bottlenecks.</li><li><strong>High Availability:</strong> HAProxy handles load balancing in Active-Active or Active-Passive modes, routing traffic only to healthy nodes for seamless availability.</li></ul><h4>Service Discovery &amp; Routing</h4><ul><li><strong>Service Tracking:</strong> Monitors available services and instances in real time for dynamic routing.</li><li><strong>Health-Based Routing:</strong> Conducts <strong>regular health checks</strong> and routes requests only to healthy instances.</li></ul><h4>API Gateway</h4><ul><li><strong>Centralised Routing</strong>: API Gateway is <strong>single entry point</strong> for client requests and routes them to the appropriate backend services by interacting with Service Discovery</li><li><strong>Security &amp; Traffic Management</strong>: Handles <strong>authentication, rate limiting, and SSL termination</strong> to ensure secure and efficient traffic handling.</li></ul><h3>Services</h3><ul><li><strong>User &amp; Session Service: </strong>Manages user authentication and session tracking (who the user is)</li><li><strong>Authorisation Service: </strong>Enforces access control using Role-Based Access Control (RBAC). A channel owner can upload, edit, and delete their own videos but not others</li><li><strong>Upload Service: Upload Service: </strong>Responsible for validating and accepting files from users while supporting resumable uploads, retries, and <strong>splitting into GOP (Group of Pictures) chunks</strong></li><li><strong>Video Manager Service</strong> : Provides CRUD operations for video metadata, including title, description, tags, category, location availability, privacy settings, thumbnails, subtitles, content ratings, and publishing status.</li><li><strong>Transcoding Service: </strong>Converts uploaded videos into multiple resolutions <strong>(e.g., 480p, 720p)</strong> and formats (e.g., HLS, VP9) for compatibility and efficient compression.</li><li><strong>Video Publication Service: </strong>Pushes processed videos to the CDN, making them available for streaming.</li><li><strong>Video Streaming Service: </strong>Delivers videos to users using adaptive bitrate streaming (HLS, DASH).</li><li><strong>Connection Service: </strong>Centralizes client connections, enabling backend services to send updates efficiently. It abstracts connection management, ensures stability, and handles retries with backoff.</li><li><strong>Notification Service: </strong>Sends alerts for uploads, comments, subscriptions, and recommendations. Uses the Connection Service for real-time updates, including upload progress.</li></ul><h3>Storage Selection</h3><p>We evaluate storage options based on consistency, scalability, latency, and data model, selecting each for specific use cases.</p><h4>Distributed SQL Storage — User Data &amp; Upload Metadata</h4><p>Combines <strong>NoSQL-like scalability</strong> with <strong>SQL’s strong consistency</strong> and <strong>ACID guarantees</strong>, optimized for <strong>low-latency global reads and writes</strong>.</p><ul><li><strong>Examples:</strong> Google Spanner, CockroachDB, YugabyteDB.</li><li><strong>User Database:</strong> Manages structured user data (roles, permissions, authentication) with <strong>strong consistency for secure authorisation and multi-tenancy</strong>. Supports transactional operations like subscriptions and payments.</li><li><strong>Upload Metadata Database:</strong> Ensures integrity in chunked uploads, preventing duplication and corruption. <strong>ACID guarantees</strong> ensure correct sequencing, storage indexing, and atomic updates for finalizing uploads and <strong>merging chunked data</strong>.</li></ul><h4>NoSQL Storage — Video Metadata</h4><p>Designed for <strong>scalability, flexibility, and high-throughput workloads</strong>, NoSQL efficiently handles dynamic metadata and large-scale queries.</p><ul><li><strong>Schema Flexibility &amp; Scalability:</strong> Supports evolving attributes (e.g., categories, tags, regional availability) without migrations. Stores video metadata, channel details, and comments.</li><li><strong>Distributed Counters:</strong> Many NoSQL databases provide distributed counters for efficiently managing metrics like view counts and like counts, handling <strong>millions of updates per second</strong>.</li><li><strong>High Throughput:</strong> Uses sharding, replication, and eventual consistency to handle massive concurrent operations, such as <strong>users posting millions of comments on a video.</strong></li><li><strong>Optimized Reads:</strong> Enhances performance with denormalisation, materialised views, and distributed indexing for low-latency queries.</li><li><strong>Examples:</strong> Apache Cassandra, DynamoDB, MongoDB.</li></ul><h4>Blob Storage — Raw and Transcoded</h4><p>A <strong>scalable, unstructured storage system for large binary data</strong>, optimized for efficient writes, parallel reads, and cost-effective distribution.</p><ul><li><strong>Massive Scalability:</strong> Supports petabyte-scale storage with automatic sharding and tiered options (hot, cold, archive).</li><li><strong>Raw Video Storage:</strong> Supports <strong>resumable uploads</strong> by fetching only missing chunks, reducing bandwidth usage. Paralleled retrieval allows immediate encoding using distributed processing.</li><li><strong>Transcoded Video Storage: </strong>Integrates with <strong>streaming protocols (HLS, DASH)</strong> to enable concurrent chunk fetching, reducing buffering and supporting adaptive bitrate switching.</li></ul><h4>Column-Family Store — Thumbnail</h4><p>A distributed, scalable system optimized for structured, column-based data, <strong>enabling fast retrieval of small, grouped items like thumbnails.</strong></p><ul><li><strong>Efficient Compression:</strong> Packs thumbnail sizes into column families, leveraging similarities (e.g., patterns, color distribution) across resolutions for optimized storage under 10 MB.</li><li><strong>Scalability:</strong> Distributes column data across nodes to handle growing thumbnail volumes while maintaining speed and efficiency.</li><li><strong>Examples:</strong> Bigtable, HBase</li></ul><p><strong>Sample Column Store Data</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pXK3waCn4wrQ0IG7bCUVRw.png" /></figure><p><strong>Disk Storage Grouping<br></strong>On disk, thumbnail files are grouped by video ID, enabling high-throughput lookups for search, recommendations, previews, feeds, and playlists</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xyDEwb5aRRxOXtz4J-aVLg.png" /></figure><h4>Caching — User Data &amp; Upload Metadata</h4><ul><li><strong>Redis</strong>, a key-value store, for caching frequently accessed data to enable quick lookups and reduce database load.</li><li><strong>Write-through caching</strong> is used for consistency, ensuring data is updated in both cache and storage, while <strong>write-behind</strong> is leveraged for batched updates to optimise write performance.</li><li><strong>Least Recently Used (LRU)</strong> eviction is applied to ensure active data stays in memory while removing stale entries.</li></ul><h3>Core Workflows</h3><h4><strong>Video Upload Process</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NgD41BKeeT98qd0qVnVUbg.png" /></figure><ul><li><strong>Initiate Upload:</strong> Client submits video details (title, description, local path), creating a PENDING entry in the metadata store.</li><li><strong>Obtain Upload Location:</strong> Client requests an upload URL for the videoId, and the service returns a secure, time-limited Pre-Signed URL.</li><li><strong>Chunked Upload:</strong> Video is split into GOP-aligned chunks and uploaded via the Pre-Signed URL.</li><li><strong>Upload Session Tracking:</strong> The service assigns an upload_id (or session URI) for progress tracking and resumable uploads.</li><li><strong>Efficient Resumption:</strong> Upload metadata tracks upload_id, chunk_id, and status, retransmitting only pending chunks.</li><li><strong>Error Handling &amp; Retries:</strong> Enforces retry limits and backoff strategies, with server-side chunking if client-side chunking isn’t possible.</li><li><strong>Encryption &amp; Security:</strong> Uses TLS for in-transit encryption, AES-256 for storage, and integrity checks (MD5/SHA-256) to detect corruption.</li><li><strong>Completion &amp; Processing:</strong> Once all chunks are uploaded, metadata transitions to READY_FOR_PROCESSING, triggering encoding and further workflows.</li></ul><h4>Transcoding Process</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YxU8w7uE91tYjqolrFy_Rg.png" /></figure><ul><li><strong>Processing Queue:</strong> Once the Upload Service detects video completion, it publishes a message to <strong>Pub/Sub layer like Kafka</strong>, ensuring <strong>high-throughput, durable, and ordered processing</strong> by the Transcoding Service.</li><li><strong>Chunking, Encoding :</strong> The video is further <strong>split into 2–5 sec chunks</strong>, encoded with <strong>codecs like H.264, VP9, or AV1</strong>, and transcoded into multiple resolutions (1080p, 720p, 480p).</li><li><strong>Parallel Processing : </strong>Parallel processing across compute nodes speeds up the workflow</li><li><strong>Retry Mechanism &amp; Failure Handling:</strong> If a chunk fails, automatic retries with exponential backoff are triggered, logging persistent failures for manual intervention.</li></ul><h4><strong>Finalisation</strong></h4><ul><li>After transcoding, the video status is set to <strong>PROCESSING_COMPLETE</strong>, and a Pub/Sub message notifies downstream services</li><li>The Publication Service pushes the video to the CDN. Once propagation is successful, the status updates to <strong>PUBLISHED</strong>, and the update is broadcast via Pub/Sub for synchronization.</li></ul><h4><strong>Streaming </strong>Process</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W9ZfUTrANh9W9lgM7IS42Q.png" /></figure><ul><li><strong>Content Request:</strong> Processed through Search, Content Delivery, and Metadata Services to fetch relevant content and recommendations.</li><li><strong>Stream Request:</strong> Handled by the Streaming Service, which delivers media via a CDN connected to Transcoded Storage.</li><li><strong>Adaptive Bitrate &amp; Low-Latency Streaming:</strong> Streams multiple resolutions (e.g., 1080p, 720p) via HLS/DASH, dynamically adjusting quality based on network conditions. Uses LL-HLS and WebRTC to minimise delays for real-time and interactive experiences.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DhyiaMFytxzsr14FHU6Uzw.png" /></figure><ul><li><strong>Multi-Layer CDN Caching:</strong> <strong>Popular videos are cached at edge servers</strong> for instant access, while <strong>long-tail content</strong> is fetched from mid-tier or origin servers only when needed.</li><li><strong>On-Demand Transcoding &amp; Prefetching:</strong> Converts unavailable formats in real time while preloading predicted chunks at edge servers for seamless playback</li><li><strong>Fault-tolerance: </strong>Retries failed chunks with exponential backoff to manage network congestion.</li></ul><h4><strong>Search </strong>Process</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yVcIrS39TTeNJBb-ZrDsYA.png" /></figure><ul><li><strong>Inverted Index Creation:</strong> Video metadata CRUD changes trigger a pub/sub message, processed for cleaning and updating the inverted index for fast lookups.</li><li><strong>Query Execution:</strong> User searches retrieve and filter videos from the inverted index, ranking results based on relevance, view count, and ranking models.</li></ul><h4>Scalable, Reliable, and Secure Video Platform</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UUnuH5R0uYU7wlmW-lRChw.png" /></figure><h4>Conclusion</h4><ul><li>Thank you for your patience in reading this. I hope the diagrams, tables, and detailed explanations helped clarify everything.<strong> </strong>🙌 <strong>Take care!</strong></li><li>If you’re curious about how trending and recommended videos are created, here is the link — <a href="https://medium.com/@s.sivaguru11/system-design-analytics-engine-78e3e5cc517d"><strong>Analytics Engine</strong></a><strong>.</strong></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5fdd47b4de25" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[System Design | Youtube | API & Resource Estimation]]></title>
            <link>https://medium.com/@s.sivaguru11/system-design-youtube-part-1-7db0ae89c95b?source=rss-6508454635b7------2</link>
            <guid isPermaLink="false">https://medium.com/p/7db0ae89c95b</guid>
            <category><![CDATA[high-level-design]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[api-design]]></category>
            <dc:creator><![CDATA[Azhagarasan Shiva]]></dc:creator>
            <pubDate>Wed, 19 Mar 2025 14:10:07 GMT</pubDate>
            <atom:updated>2025-04-08T06:37:48.308Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2Ww6L_5K14WPWF0mwflXdw.jpeg" /></figure><p>In this article, we will cover the <strong>database schema, API design, storage requirements, and bandwidth needs</strong> for building a YouTube-like system.</p><p>My goal is discuss key topics in detail, <strong>diving one level deeper</strong> for better understanding. Stay patient — these insights will not only clarify this design but also serve as <strong>valuable references for designing other systems</strong>.</p><h4><strong>Functional Requirements</strong></h4><ul><li><strong>Uploading: </strong>Support 500 hours of video uploads per minute</li><li><strong>Streaming</strong>: Each uploaded video is streamed 200 times on average.</li><li><strong>Video Discovery: </strong>Users to search videos by title, description, and tags. and can subscribe to a channel</li><li><strong>User Engagements:</strong> Users can like or dislike videos, add comments , allow reply to comments, limited to one level of replies.</li></ul><h4>Non-Functional Requirements</h4><ul><li><strong>Scalability:</strong> Ensure the system efficiently handles increasing video uploads and streaming demands</li><li><strong>Availability:</strong> Maintain uninterrupted service, minimising downtime</li><li><strong>Consistency:</strong> Guarantee strong consistency for critical data, such as user profiles and payments, to prevent data discrepancies.</li><li><strong>Fault Tolerance:</strong> Prevent data loss and system failures</li><li><strong>Reliability:</strong> Ensure the platform remains operational despite component failures</li></ul><h4><strong>Database Schema</strong></h4><p>Let’s start by defining the database schema to better understand entity relationships, assess their effect on storage decisions, and improve the accuracy of our resource estimates.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/09767271d83179e336f7299ce876a98b/href">https://medium.com/media/09767271d83179e336f7299ce876a98b/href</a></iframe><p><strong>Video Metadata </strong>: Since metadata will evolve over time, it should be stored using a flexible schema such as JSON.</p><pre>{<br>  &quot;video_id&quot;: &quot;abcd1234&quot;,<br>  &quot;title&quot;: &quot;GraphQL Basics: Querying Made Simple&quot;,<br>  &quot;description&quot;: &quot;An introductory tutorial on GraphQL, exploring its querying capabilities and how it simplifies API development.&quot;,<br>  &quot;upload_date&quot;: &quot;2025-03-18T14:30:00Z&quot;,<br>  &quot;duration&quot;: &quot;PT15M&quot;,<br>  &quot;uploader&quot;: {<br>    &quot;channel_id&quot;: &quot;UC987654321&quot;,<br>    &quot;channel_name&quot;: &quot;Tech Tutorials Hub&quot;,<br>    &quot;channel_url&quot;: &quot;https://www.youtube.com/channel/UC987654321&quot;<br>  },<br>  &quot;thumbnails&quot;: {<br>    &quot;high&quot;: {<br>      &quot;resolution&quot;: &quot;1920x1080&quot;,<br>      &quot;url&quot;: &quot;https://i.ytimg.com/vi/abcd1234/hqdefault.jpg&quot;<br>    },<br>    &quot;medium&quot;: {<br>      &quot;resolution&quot;: &quot;1280x720&quot;,<br>      &quot;url&quot;: &quot;https://i.ytimg.com/vi/abcd1234/mqdefault.jpg&quot;<br>    },<br>    &quot;low&quot;: {<br>      &quot;resolution&quot;: &quot;640x360&quot;,<br>      &quot;url&quot;: &quot;https://i.ytimg.com/vi/abcd1234/default.jpg&quot;<br>    }<br>  },<br>  &quot;video_urls&quot;: {<br>    &quot;watch_url&quot;: &quot;https://www.youtube.com/watch?v=abcd1234&quot;,<br>    &quot;embed_url&quot;: &quot;https://www.youtube.com/embed/abcd1234&quot;<br>  },<br>  &quot;counts&quot;: {<br>    &quot;views&quot;: 10345678,<br>    &quot;likes&quot;: 789654,<br>    &quot;comments&quot;: 150678<br>  },<br>  &quot;status&quot;: &quot;public&quot;,<br>  &quot;tags&quot;: [&quot;GraphQL&quot;, &quot;API&quot;, &quot;programming&quot;, &quot;tutorial&quot;],<br>  &quot;category_id&quot;: 2,<br>  &quot;content_language&quot;: &quot;en&quot;,<br>  &quot;license&quot;: &quot;YouTube Standard License&quot;,<br>  &quot;is_monetized&quot;: true<br>}</pre><h4><strong>API Design</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n4oUGwOScr_pF9yTYv67AQ.png" /></figure><h4><strong>Assumptions</strong></h4><p>Before we proceed with resource estimations, let’s clarify our assumptions.</p><ul><li><strong>User base :</strong> 1 billion</li><li><strong>Daily Active User</strong> : 500 million</li><li><strong>Videos uploaded per minute</strong>: 30,000 minutes duration of video (500 hours)</li></ul><h4>Resource estimations</h4><ul><li><strong>Estimate storage requirements</strong> for data, raw uploaded videos, encoded videos, and thumbnails.</li><li><strong>Analyse bandwidth needs</strong> for incoming traffic, outgoing traffic, and thumbnail delivery.</li></ul><h4><strong>Estimation for YouTube Data Storage</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WeThuIy4CEh8nuA2YTJMDg.png" /></figure><ul><li>The size per unit is an approximation for all categories</li><li>User data is approximately <strong>350 bytes</strong>, including user ID (8 bytes), name (50 bytes), email (50 bytes), password (60-72 bytes, <strong>bcrypt</strong>), and profile picture URL (100 bytes)</li><li>For video metadata, we assumed <strong>4KB</strong> to account for its evolving nature and growing attributes.</li><li>Each video is assumed to have <strong>100 comments </strong>size of <strong>100 characters</strong> on average</li></ul><h4>Understanding Raw Uploads vs Transcoded Video</h4><ul><li>When a user uploads a raw video, it is initially stored in its original, uncompressed format.</li><li>The system then encodes and transcodes this file, compressing it and converting it into multiple formats —<strong> such as VP9 and HLS — and resolutions — like 480p, 720p, 1080p, and 4K </strong>— optimized for streaming across various devices and network conditions.</li></ul><h4><strong>Storage estimation : Raw video uploads</strong></h4><ul><li>We assume sufficient processing resources to process all raw uploads within 24 hours, ensuring adequate raw storage before transcoding for streaming.</li><li>By calculating the <strong>raw video data uploaded per minute</strong> for all video variants, we can scale up to determine the <strong>total storage required per day</strong>.</li><li><strong>Videos uploaded per minute</strong>: 30,000 minutes per minute</li><li><strong>Total videos per minute</strong> : 11,800</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4dWuSgsQAi1K0lCo9VaXoA.png" /></figure><p>Take a moment to understand each column thoroughly, and then we can discuss the <strong>720p variant.</strong></p><ul><li><strong>Step 1: Calculate Total File Size in Megabits</strong><br><strong> </strong>File size = Bitrate × Duration (in seconds)<strong><br></strong>5 Mbps × 300 seconds = 1,500 Megabits<br>Convert to Megabytes: 1,500 Megabits ÷ 8 (1 Byte = 8 bits) = 187.5 MB</li><li><strong>Step 2: Calculate Per-Minute Storage<br></strong>Per-minute size = Total file size ÷ Video duration<strong><br></strong>187.5 MB ÷ 5 minutes = 37.5 MB per minute</li><li><strong>Step 3: Calculate Raw video Storage </strong><br>Total per-minute storage for all video variants is <strong>270MB</strong><br>(Shorts is 7.5 MB + 720p is 37.5 MB + 1080p is 75 MB + 4K is 150 MB)</li></ul><p>Since, we have resources to process within 24 hours (1440 minutes)<br><strong>Storage required = 270 MB × 1,440 minutes = 388,800 MB = 388.8 TB</strong></p><h4>Understanding Video Encodings</h4><p>Raw videos are encoded in formats like <strong>VP9, AV1, and H.264</strong>, then transcoded into multiple resolutions (360p, 480p, etc) to provide smooth streaming across various devices and network conditions.</p><ul><li><strong>VP9</strong> → offers excellent compression with high quality at lower bitrates and is widely used.</li><li><strong>AV1</strong> → provides 30% better compression than VP9 but has limited adoption.</li><li><strong>H.264</strong> → maximises compatibility on older devices.</li></ul><p>For a 10 GB raw 4K video, the table below shows the expected file sizes after compression using VP9, AV1, and H.264 at different resolutions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tQ-7jn-gfiEZ4kEZK_8eFQ.png" /></figure><h4>Storage estimation: Transcoded Videos</h4><ul><li>To simplify calculations, we assume all videos are encoded only in <strong>VP9 format </strong>with a <strong>uniform</strong> <strong>70% compression rate</strong> across all variants, though in reality, compression varies (e.g. <strong>50% for 4K, 90% for 360p</strong>).</li><li><strong>Raw video Storage Per Day:</strong> 338.8 TB</li><li><strong>Encoded video Storage Per Day:</strong> 338.8 TB × 0.30 = 101.64 TB</li><li><strong>Encoded video Storage Per Year: </strong>101.64 TB × 365 days<strong> = 37.1 PB</strong></li></ul><h4><strong>Understand Thumbnail Formats</strong></h4><ul><li><strong>JPEG</strong> is chosen for thumbnails due to its <strong>universal device compatibility</strong> and efficient compression, balancing quality and file size for fast web delivery.</li><li><strong>WebP</strong> and <strong>AVIF</strong>, despite 25-50% better compression, are less viable due to <strong>limited support</strong> on older devices and <strong>increased processing demands</strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AlkgLHFxtRpj3Trqs7-f0w.png" /></figure><h4>Storage estimation: <strong>Thumbnail</strong></h4><ul><li><strong>Videos Uploaded Per Minute:</strong> 11,800</li><li><strong>Total Thumbnail Size Per Video:</strong> 1 MB (JPEG)</li><li><strong>Daily Storage Requirement:<br> = </strong>11,800 videos × 1 MB × 1,440 minutes<br> = 16,992,000 MB = <strong>16.6 TB</strong></li><li><strong>Yearly Storage Requirement:<br> </strong>16.6 TB × 365 days = 6,059 TB ≈ <strong>6 PB per year</strong></li></ul><h4>Incoming Bandwidth (Uploading Bandwidth)</h4><p>Referencing the <strong>Video Data Table</strong>, which includes incoming bandwidth calculations for all video variants.</p><p>To understand the calculation, let’s take the <strong>360p</strong> variant as an example.</p><ul><li><strong>Bitrate:</strong> <strong>1 Mbps</strong></li><li><strong>Total Duration of 360p Videos Per Minute</strong> : <br>30% of 30000 minutes = 9000 minutes</li><li><strong>Duration:</strong> <strong>1 minute</strong></li><li><strong>Total Videos:<br></strong> Total Duration of 360p Videos Per Minute ÷ Duration <br>9,000 minutes ÷ 1 minute = <strong>9,000 videos</strong></li><li><strong>Incoming Bandwidth for 360p videos :<br></strong> Total Videos × Bitrate = 9,000 videos × 1 Mbps = 9,000 Mbps</li><li><strong>Total Incoming Bandwidth: 196,000 Mbps = 196 Gbps<br></strong>9,000 Mbps (480p) + 37,500 Mbps (720p) + 120,000 Mbps (1080p)<br>+ 30,000 Mbps (4K )</li></ul><h4>Outgoing Bandwidth Calculation (Streaming Bandwidth)</h4><p>Since the raw video is compressed by <strong>70%</strong>, only <strong>30%</strong> of the incoming bandwidth is required for outgoing bandwidth, but each video is watched <strong>200 times</strong>:</p><ul><li><strong>Effective Bandwidth Required:</strong> 196 Gbps × 0.30 = 58.8 Gbps</li><li><strong>Total Outgoing Bandwidth:</strong> 58.8 Gbps × 200 = 11,760 Gbps = <strong>11.8 Tbps</strong></li></ul><h4>Thumbnail Delivery Bandwidth Calculation</h4><ul><li><strong>Videos uploaded per minute</strong>: 11,800</li><li><strong>Videos uploaded per second</strong>: 11,800 ÷ 60 = 196</li><li><strong>Videos streamed per second</strong>: 196 × 200 = 39,200</li><li><strong>Total data streamed per second</strong>: 39,200 × 1 MB = 39.2 GB</li><li><strong>Converted to Gbps</strong>: 39.2 × 8 = <strong>314 Gbps</strong></li></ul><h4>Storage and Bandwidth Summary</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-AkKnaHqN2C2_00XBYHISQ.png" /></figure><h3>Conclusion</h3><ul><li>This section provided insights into the system’s scale and how video and image encoding decisions impact storage.</li><li>We classified videos into distinct variants to demonstrate how resolution impacts bitrate and bandwidth consumption.</li><li>Next, we’ll explore storage options, system architecture, and key challenges.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7db0ae89c95b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>