<?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 Dinakaran on Medium]]></title>
        <description><![CDATA[Stories by Dinakaran on Medium]]></description>
        <link>https://medium.com/@theena18?source=rss-e6bb5de386b9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*55YR2r1PdPsK9sUVps6uwg.jpeg</url>
            <title>Stories by Dinakaran on Medium</title>
            <link>https://medium.com/@theena18?source=rss-e6bb5de386b9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 05:47:45 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@theena18/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[Trivox AI: Building a Local RAG-Powered AI Assistant for Technical Knowledge]]></title>
            <link>https://theena18.medium.com/trivox-ai-building-a-local-rag-powered-ai-assistant-for-technical-knowledge-012658fdd7fd?source=rss-e6bb5de386b9------2</link>
            <guid isPermaLink="false">https://medium.com/p/012658fdd7fd</guid>
            <category><![CDATA[ollama]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Dinakaran]]></dc:creator>
            <pubDate>Sat, 28 Nov 2026 16:33:04 GMT</pubDate>
            <atom:updated>2026-11-28T16:33:04.818Z</atom:updated>
            <content:encoded><![CDATA[<p><em>From document ingestion and hybrid retrieval to reranking and grounded AI responses — building a personal AI knowledge assistant with FastAPI, Ollama, ChromaDB, and Next.js.</em></p><h3>Introduction</h3><p>Large Language Models (LLMs) are incredibly useful for learning, exploring ideas, debugging problems, and understanding complex technical concepts. But they have a limitation that becomes noticeable when you want to use them with your own knowledge.</p><p>They don’t automatically know the contents of your personal documents, technical notes, PDFs, architecture designs, or study materials. Even when they provide a confident answer, you may not know whether it is based on your source material or the model’s general knowledge.</p><p>I wanted to solve this problem by building something of my own.</p><p>Instead of simply creating another chatbot interface connected to an LLM API, I wanted to build an AI assistant that could:</p><ul><li>Understand and search my own technical documents.</li><li>Retrieve relevant information instead of sending entire documents to an LLM.</li><li>Combine semantic search with keyword search.</li><li>Maintain conversational context.</li><li>Generate responses using retrieved knowledge.</li><li>Show the sources used to generate an answer.</li><li>Run using locally hosted AI models.</li></ul><p>That idea became <strong>Trivox AI</strong>.</p><p>Trivox is a local AI assistant designed primarily for technical knowledge, including system design, DevOps, cloud computing, software architecture, Linux, Kubernetes, and programming.</p><p>This article explains how I designed and built it, how the complete RAG pipeline works, and the engineering decisions behind the system.</p><h3>1. What Is Trivox AI?</h3><p>Trivox AI is a Retrieval-Augmented Generation (RAG) based conversational AI assistant that allows users to upload their own documents and ask questions based on that knowledge.</p><p>Instead of relying exclusively on an LLM’s pre-trained knowledge, Trivox retrieves relevant information from uploaded documents and uses that information as context when generating a response.</p><p>The system combines:</p><ul><li><strong>Next.js</strong> for the frontend</li><li><strong>FastAPI</strong> for the backend</li><li><strong>Ollama</strong> for locally hosted AI models</li><li><strong>Qwen 2.5 1.5B</strong> for text generation</li><li><strong>nomic-embed-text</strong> for embeddings</li><li><strong>ChromaDB</strong> for vector storage and semantic retrieval</li><li><strong>BM25</strong> for keyword-based retrieval</li><li><strong>Reciprocal Rank Fusion (RRF)</strong> for combining search results</li><li><strong>SQLite</strong> for conversation persistence</li></ul><p>The goal is to make technical knowledge searchable, reusable, and conversational.</p><h3>What can Trivox do?</h3><p>Users can upload PDF and TXT documents, ask questions, receive context-aware answers, continue conversations, retrieve relevant document chunks, and inspect source references.</p><p>For example, I can upload documents related to Docker, Kubernetes, Linux, and system design, then ask:</p><blockquote><em>Explain Docker architecture and how Docker components communicate with each other.</em></blockquote><p>Instead of searching through multiple PDFs manually, Trivox retrieves relevant chunks and uses them to generate an answer.</p><h3>2. Why I Built Trivox AI</h3><p>While learning technical subjects, information often becomes scattered across different sources:</p><ul><li>PDF documentation</li><li>Notes</li><li>Technical guides</li><li>Books</li><li>Architecture diagrams</li><li>Interview preparation materials</li><li>System design documents</li></ul><p>Reading these materials is useful, but finding the exact information later can become difficult.</p><p>Traditional search is based primarily on matching words. If I search for a question using different terminology than the document uses, I may miss relevant information.</p><p>For example:</p><p><strong>My question:</strong></p><blockquote><em>How does an application remain isolated from other applications?</em></blockquote><p><strong>My document:</strong></p><blockquote><em>Containers provide isolated execution environments with their own filesystem, process space, and networking configuration.</em></blockquote><p>A traditional keyword search may not recognize the relationship between these two statements.</p><p>Semantic search, on the other hand, can identify similarities in meaning.</p><p>I wanted to build a system that combines these approaches and makes my knowledge base feel like a conversation rather than a collection of files.</p><p>That led me to RAG.</p><h3>3. Understanding the Architecture</h3><p>Before discussing the implementation, let’s look at the overall architecture.</p><p>Trivox consists of a frontend, backend, AI services, vector storage, and conversation persistence.</p><h3>High-Level Architecture</h3><pre>flowchart TD<br>    U[User] --&gt; F[Next.js Frontend]</pre><pre>    F --&gt; B[FastAPI Backend]</pre><pre>    B --&gt; C[Chat API]<br>    B --&gt; D[Document API]<br>    B --&gt; E[Search API]<br>    B --&gt; G[Evaluation API]</pre><pre>    C --&gt; R[RAG Pipeline]</pre><pre>    R --&gt; EM[Embedding Model]<br>    R --&gt; V[ChromaDB]<br>    R --&gt; BM[BM25 Search]<br>    R --&gt; RR[Reranker]<br>    R --&gt; LLM[Qwen via Ollama]</pre><pre>    D --&gt; IN[Document Ingestion Pipeline]<br>    IN --&gt; EM<br>    IN --&gt; V</pre><pre>    B --&gt; DB[SQLite]<br>    DB --&gt; H[Conversation History]</pre><h3>Component Responsibilities</h3><p>Component Responsibility Next.js User interface and chat experience FastAPI API layer and orchestration Ollama Local model runtime Qwen 2.5 1.5B</p><p>Answer generation nomic-embed-text . Text embedding generation ChromaDBVector storage and retrieval BM25 Keyword-based retrieval. RRFFusion of retrieval rankings Reranker Relevance-based reordering. SQLite Conversation and message persistence.</p><p>The backend is the central orchestration layer. It coordinates document processing, retrieval, embeddings, model generation, and conversation management.</p><h3>4. Why Retrieval-Augmented Generation?</h3><p>RAG stands for <strong>Retrieval-Augmented Generation</strong>.</p><p>It combines two capabilities:</p><ol><li>Retrieval — finding relevant information from an external knowledge source.</li><li>Generation — using an LLM to produce a natural-language response.</li></ol><p>Without RAG, an LLM answers using the information it learned during training and whatever context is provided in the current prompt.</p><p>With RAG, we can provide additional relevant information at inference time.</p><h3>Traditional LLM</h3><pre>User Question<br>     |<br>     v<br>    LLM<br>     |<br>     v<br>Generated Answer</pre><h3>RAG-Based LLM</h3><pre>User Question<br>     |<br>     v<br>Search Knowledge Base<br>     |<br>     v<br>Retrieve Relevant Information<br>     |<br>     v<br>Build Context<br>     |<br>     v<br>    LLM<br>     |<br>     v<br>Context-Aware Answer</pre><p>This approach allows Trivox to answer questions using documents that were not part of the model’s original training data.</p><p>The LLM does not need to retrain whenever I add a new document.</p><p>I can upload a document, process it, store its embeddings, and make its knowledge searchable.</p><h3>5. Document Ingestion: Building the Knowledge Base</h3><p>Before Trivox can answer questions using documents, those documents must be processed and stored in a searchable format.</p><p>This process is called <strong>document ingestion</strong>.</p><p>The ingestion pipeline transforms raw files into searchable knowledge.</p><h3>Supported Formats</h3><p>Currently, Trivox supports:</p><ul><li>PDF</li><li>TX</li></ul><p>The upload endpoint also validates file size, with a maximum limit of 10 MB.</p><h3>Document Ingestion Pipeline</h3><pre>flowchart LR<br>    A[Upload PDF / TXT] --&gt; B[Validate File]<br>    B --&gt; C[Extract Text]<br>    C --&gt; D[Split into Chunks]<br>    D --&gt; E[Generate Embeddings]<br>    E --&gt; F[Store in ChromaDB]</pre><p>Let’s understand each stage.</p><h3>Step 1: Upload</h3><p>The frontend sends a document to the backend using:</p><pre>POST /api/documents/upload</pre><p>The backend validates:</p><ul><li>File extension</li><li>Empty file</li><li>Maximum file size</li></ul><p>Each uploaded document receives a unique document ID.</p><p>This identifier allows Trivox to associate multiple chunks with the original uploaded document.</p><h3>Step 2: Text Extraction</h3><p>The uploaded file is temporarily stored on disk so that the document extraction service can process it.</p><p>The extraction service converts the document into plain text.</p><pre>PDF / TXT<br>    |<br>    v<br>Text Extraction<br>    |<br>    v<br>Raw Text</pre><p>For example, a PDF containing Docker documentation may produce text such as:</p><pre>Docker is a platform for developing,<br>shipping, and running applications.</pre><pre>Docker containers provide isolated<br>environments for applications.</pre><p>The extracted text becomes the input for the next stage.</p><p>Temporary files are cleaned up after processing, including when an error occurs.</p><h3>Step 3: Chunking</h3><p>Sending an entire document to an LLM for every question would be inefficient.</p><p>Imagine uploading a 100-page document. Most questions will require only a small portion of that document.</p><p>Instead, Trivox divides the extracted text into smaller chunks.</p><pre>Document<br>   |<br>   ├── Chunk 0<br>   ├── Chunk 1<br>   ├── Chunk 2<br>   ├── Chunk 3<br>   └── Chunk N</pre><p>Each chunk represents a smaller piece of the original document.</p><p>Chunking helps with:</p><ul><li>More precise retrieval</li><li>Smaller context windows</li><li>Reduced irrelevant information</li><li>Efficient embedding generation</li><li>Better control over retrieved knowledge</li></ul><p>Trivox uses a dedicated chunking service to split the document before embedding and storage.</p><h3>Step 4: Embedding Generation</h3><p>After chunking, each chunk is converted into a numerical representation called an embedding.</p><p>Trivox uses:</p><p><strong>nomic-embed-text</strong></p><p>The embedding model runs through Ollama.</p><p>For example:</p><pre>Text:</pre><pre>&quot;Docker containers provide isolated environments.&quot;</pre><pre>             |<br>             v</pre><pre>      Embedding Model</pre><pre>             |<br>             v</pre><pre>[0.12, -0.43, 0.87, 0.21, ...]</pre><p>An embedding represents semantic information about the text.</p><p>Texts with similar meanings can have similar vector representations, even when they use different words.</p><p>This is what makes semantic retrieval possible.</p><p>For example:</p><p><strong>Query:</strong></p><blockquote><em>How does Docker isolate applications?</em></blockquote><p><strong>Stored chunk:</strong></p><blockquote><em>Containers provide isolated execution environments for processes.</em></blockquote><p>These texts may have different words but share similar meaning.</p><p>The embedding model helps Trivox identify that relationship.</p><h3>Step 5: Store in ChromaDB</h3><p>The generated embeddings, chunk text, and metadata are stored in ChromaDB.</p><p>Each chunk contains information such as:</p><pre>{<br>  &quot;document_id&quot;: &quot;document-uuid&quot;,<br>  &quot;filename&quot;: &quot;Docker.pdf&quot;,<br>  &quot;chunk_index&quot;: 0<br>}</pre><p>The stored information includes:</p><ul><li>Chunk text</li><li>Embedding vector</li><li>Document ID</li><li>Filename</li><li>Chunk index</li></ul><p>The document ID groups all chunks belonging to the same original file.</p><p>This structure also makes it possible to list uploaded documents and delete an entire document along with its associated chunks.</p><p>At this point, the document has become searchable knowledge.</p><h3>6. The RAG Pipeline: From Question to Answer</h3><p>Document ingestion builds the knowledge base.</p><p>The RAG pipeline uses that knowledge to answer questions.</p><p>This is the most important part of Trivox AI.</p><p>When a user submits a question, the system does not immediately send it to Qwen.</p><p>Instead, the question passes through several retrieval and processing stages.</p><pre>flowchart LR<br>    A[User Question] --&gt; B[Contextualization]<br>    B --&gt; C[Query Rewriting]<br>    C --&gt; D[Multi-Query Generation]<br>    D --&gt; E[Embedding Generation]<br>    E --&gt; F[Hybrid Retrieval]<br>    F --&gt; G[RRF Fusion]<br>    G --&gt; H[Filtering and Deduplication]<br>    H --&gt; I[Reranking]<br>    I --&gt; J[Context Building]<br>    J --&gt; K[LLM Generation]<br>    K --&gt; L[Final Answer]</pre><p>The pipeline is designed to improve the quality of retrieved information before the LLM generates the response.</p><h3>7. Query Contextualization</h3><p>Users don’t always ask complete questions.</p><p>In a conversation, someone might ask:</p><blockquote><em>What is Docker?</em></blockquote><p>Then:</p><blockquote><em>How does it work?</em></blockquote><p>Then:</p><blockquote><em>What is the difference between it and a virtual machine?</em></blockquote><p>The second and third questions depend on the previous conversation.</p><p>Searching for the literal query:</p><blockquote><em>How does it work?</em></blockquote><p>would be ineffective because it lacks context.</p><p>Trivox includes contextual query generation.</p><p>It uses the conversation history to transform the latest question into a standalone query.</p><h3>Example</h3><p>Conversation:</p><pre>User:<br>What is Docker?</pre><pre>Assistant:<br>Docker is a containerization platform...</pre><p>Follow-up:</p><pre>User:<br>How does it work?</pre><p>Contextualized query:</p><pre>How does Docker work and how does its<br>containerization architecture operate?</pre><p>This gives the retrieval pipeline a more meaningful query.</p><p>Trivox uses the recent conversation history to generate a contextual query and falls back to the original question if contextualization fails.</p><h3>8. Query Rewriting and Multi-Query Retrieval</h3><p>A single query may not capture every aspect of the user’s question.</p><p>For example:</p><blockquote><em>Explain Docker architecture.</em></blockquote><p>This query might retrieve documents discussing Docker generally, but it may miss specific content about the Docker daemon, container runtime, containerd, or runc.</p><p>To improve retrieval coverage, Trivox generates multiple search queries.</p><p>Example:</p><h3>Original Question</h3><pre>Explain Docker architecture.</pre><h3>Generated Queries</h3><pre>1. Docker architecture and its components</pre><pre>2. How Docker client, daemon, and container<br>   runtime communicate</pre><pre>3. Docker container lifecycle and execution<br>   architecture</pre><p>These queries explore the same question from different perspectives.</p><p>The objective is to improve the probability of finding relevant chunks distributed across different parts of the knowledge base.</p><p>Instead of searching for information using only one query, Trivox searches using multiple variations.</p><p>This is particularly useful when documents use different terminology from the user’s question.</p><h3>9. Embedding the Search Queries</h3><p>Once the queries are generated, Trivox converts them into embeddings.</p><p>The embedding model used is:</p><pre>nomic-embed-text</pre><p>The generated vectors represent the semantic meaning of the queries.</p><p>Conceptually:</p><pre>Query 1 ──&gt; Embedding 1<br>Query 2 ──&gt; Embedding 2<br>Query 3 ──&gt; Embedding 3</pre><p>These embeddings are used for vector retrieval.</p><p>Trivox also generates embeddings in batches for the query retrieval workflow, reducing the need to make separate embedding requests for every search query.</p><h3>10. Hybrid Retrieval: Vector Search + BM25</h3><p>One of the important design decisions in Trivox was not relying exclusively on vector search.</p><p>Semantic search is useful, but keyword search is also valuable.</p><p>For technical documentation, exact terms matter.</p><p>Examples:</p><ul><li>containerd</li><li>runc</li><li>kubelet</li><li>kube-proxy</li><li>EC2</li><li>IAM</li><li>TCP</li><li>JDBC</li><li>HPA</li></ul><p>A query may contain an exact technical identifier that should be matched directly.</p><p>This is why Trivox uses hybrid retrieval.</p><p>Hybrid retrieval combines:</p><ul><li>Vector search</li><li>BM25 keyword search</li></ul><h3>Vector Search</h3><p>Vector search compares the embedding of the user’s query against stored document embeddings.</p><p>It is useful for finding semantically similar content.</p><p>Example:</p><pre>Query:<br>How do applications remain isolated?</pre><pre>Document:<br>Containers provide isolated execution<br>environments.</pre><p>The terms may differ, but the meaning is similar.</p><h3>BM25 Search</h3><p>BM25 is a lexical or keyword-based ranking algorithm.</p><p>It evaluates how relevant documents are to a query based on the terms appearing in the document.</p><p>BM25 is particularly useful when exact technical terms are important.</p><p>Example:</p><pre>Query:<br>Explain containerd and runc.</pre><p>A document containing:</p><pre>containerd<br>runc<br>runtime</pre><p>may receive a strong keyword-based ranking.</p><p>Trivox implements BM25 using rank_bm25.</p><p>The index is constructed from the available knowledge base and used to retrieve chunks based on lexical relevance.</p><h3>Why Hybrid Retrieval?</h3><p>Vector search understands meaning. BM25 understands exact words. Combining both helps cover different retrieval scenarios.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/683/1*AU7mWigjhJttZYjjJwo0Ig.png" /></figure><p>This combination is particularly useful for a technical knowledge assistant.</p><h3>11. Reciprocal Rank Fusion (RRF)</h3><p>Vector search and BM25 return different rankings.</p><p>The next challenge is combining those results into a unified ranking.</p><p>Trivox uses <strong>Reciprocal Rank Fusion (RRF)</strong>.</p><p>RRF combines rankings from multiple retrieval systems without requiring their raw scores to be directly comparable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/731/1*NnGK9t0D8w2SGmzwmpI16A.png" /></figure><h3>Why is RRF useful?</h3><p>Imagine a chunk appears in both vector search and BM25 results.</p><p>Even if it isn’t ranked first in either list, consistently appearing near the top of multiple retrieval lists can indicate that it is relevant.</p><p>RRF rewards chunks that perform well across different retrieval approaches.</p><h3>Example</h3><pre>Vector Search</pre><pre>1. Chunk A<br>2. Chunk B<br>3. Chunk C<br>4. Chunk D</pre><pre>BM25</pre><pre>1. Chunk C<br>2. Chunk A<br>3. Chunk E<br>4. Chunk B</pre><p>After fusion:</p><pre>Combined Ranking</pre><pre>1. Chunk A<br>2. Chunk C<br>3. Chunk B<br>4. Chunk E<br>5. Chunk D</pre><p>The exact ranking depends on the RRF scores.</p><p>The important idea is that Trivox combines the retrieval rankings instead of blindly trusting a single retrieval method.</p><h3>12. Filtering and Deduplication</h3><p>After retrieval and fusion, the pipeline still needs to clean the results.</p><p>The knowledge base may return:</p><ul><li>Duplicate chunks</li><li>Multiple chunks containing nearly identical content</li><li>Weakly relevant chunks</li><li>Different chunks from the same document</li></ul><p>Trivox applies filtering and deduplication before final context construction.</p><h3>Distance Filtering</h3><p>The current implementation uses:</p><pre>SIMILARITY_DISTANCE_THRESHOLD = 0.75<br>MAX_DISTANCE_FROM_BEST = 0.15</pre><p>It calculates a threshold based on the best retrieved distance:</p><pre>threshold = min(<br>    0.75,<br>    best_distance + 0.15<br>)</pre><p>Because the retrieval distance is a distance metric, a smaller distance generally represents a closer match.</p><p>This allows the pipeline to remove chunks that are substantially weaker than the best retrieved result, while also maintaining a maximum distance boundary.</p><h3>Deduplication</h3><p>Trivox deduplicates chunks using document identity and chunk position:</p><pre>(document_id, chunk_index)</pre><p>It also removes duplicate content after normalization.</p><p>This prevents the same chunk from appearing multiple times in the final context.</p><p>The goal is to make the context cleaner and more useful for the LLM.</p><h3>13. Reranking: Improving Relevance</h3><p>Retrieval finds candidate chunks.</p><p>But candidate retrieval and final relevance are not the same thing.</p><p>A chunk may be retrieved because it shares semantic similarity or keywords, but it may not be the most useful chunk for answering the question.</p><p>This is where reranking comes in.</p><p>The reranker evaluates the relationship between the question and the retrieved chunks and reorders them based on relevance.</p><pre>Retrieved Candidates<br>        |<br>        v<br>    Reranker<br>        |<br>        v<br>Relevance Scoring<br>        |<br>        v<br>Reordered Chunks<br>        |<br>        v<br>Select Top-K</pre><p>Instead of directly using the original retrieval ranking, Trivox can apply a reranking stage to prioritize chunks that are more relevant to the query.</p><h3>Retrieval vs. Reranking</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/575/1*Gdh3Nmhk5GOMKuJw5iDilg.png" /></figure><p>Retrieval focuses on recall — finding relevant candidates.</p><p>Reranking focuses on improving the relevance of the final selected context.</p><p>This is an important distinction in RAG systems.</p><h3>14. Context Building</h3><p>After retrieval, filtering, deduplication, and reranking, Trivox prepares the final context.</p><p>The system selects the most relevant chunks and combines them into a context block.</p><p>The current implementation limits the context to approximately <strong>6,000 characters</strong>.</p><p>This helps control the amount of retrieved information passed to the model.</p><p>The context contains relevant document information that the LLM can use to answer the question.</p><pre>User Question<br>      +<br>Retrieved Chunk 1<br>Retrieved Chunk 2<br>Retrieved Chunk 3<br>      |<br>      v<br>Context Builder<br>      |<br>      v<br>Final Prompt</pre><p>The system does not need to include the entire knowledge base.</p><p>It only needs the most relevant information for the current question.</p><p>This is one of the main advantages of RAG.</p><h3>15. Answer Generation with Qwen</h3><p>Once the retrieval pipeline has prepared the context, Trivox sends the question and retrieved information to the LLM.</p><p>The model used for generation is:</p><pre>Qwen 2.5 1.5B</pre><p>It runs locally through Ollama.</p><p>The generation stage receives:</p><ul><li>System instructions</li><li>User question</li><li>Conversation history</li><li>Retrieved context</li></ul><p>Conceptually, the prompt looks like this:</p><pre>System Instructions</pre><pre>You are Trivox, a technical AI assistant.</pre><pre>Answer clearly and accurately.</pre><pre>User Question</pre><pre>Explain Docker architecture.</pre><pre>Retrieved Context</pre><pre>[Relevant Chunk 1]</pre><pre>[Relevant Chunk 2]</pre><pre>[Relevant Chunk 3]</pre><pre>Generate Answer</pre><p>The retrieved context gives the model additional information to use when answering.</p><p>Instead of relying only on general knowledge, the model can reference information retrieved from the user’s documents.</p><p>This is the <strong>Augmentation</strong> stage of RAG.</p><h3>16. Streaming Responses</h3><p>Generating an answer can take time, especially when running a local model.</p><p>Instead of waiting for the entire response to finish, Trivox supports streaming.</p><p>The backend uses Server-Sent Events (SSE).</p><p>The streaming endpoint is:</p><pre>POST /api/chat/stream</pre><p>The response is delivered incrementally.</p><p>Conceptually:</p><pre>LLM Generation<br>       |<br>       v<br>Token 1 ──&gt; Frontend<br>Token 2 ──&gt; Frontend<br>Token 3 ──&gt; Frontend<br>Token 4 ──&gt; Frontend<br>   ...</pre><p>The backend sends events such as:</p><pre>event: token</pre><pre>event: sources</pre><pre>event: done</pre><h3>Why Streaming?</h3><p>Streaming improves the perceived responsiveness of the application.</p><p>The user sees the answer gradually instead of waiting for the entire generation process to complete.</p><p>Trivox also accumulates the generated text during streaming so the completed exchange can be persisted to SQLite.</p><h3>17. Conversation History with SQLite</h3><p>Trivox is designed for conversations rather than isolated questions.</p><p>Conversation history is stored in SQLite.</p><p>The database contains two main entities:</p><pre>conversations<br>messages</pre><h3>Conversations</h3><p>Stores information about a conversation, including its identifier, title, and timestamps.</p><h3>Messages</h3><p>Stores individual user and assistant messages associated with a conversation.</p><p>The relationship is:</p><pre><br>    CONVERSATIONS || --o{ MESSAGES : contains</pre><pre>    CONVERSATIONS {<br>        string id<br>        string title<br>        datetime created_at<br>        datetime updated_at<br>    }</pre><pre>    MESSAGES {<br>        integer id<br>        string conversation_id<br>        string role<br>        text content<br>        datetime created_at<br>    }</pre><p>Each conversation can contain multiple messages.</p><p>The conversation ID allows Trivox to load the correct history when a user continues a previous conversation.</p><p>The history is used for contextual query generation and conversational responses.</p><p>SQLite was a practical choice for this project because it is lightweight, requires no separate database server, and is suitable for a locally running application.</p><h3>18. Source References</h3><p>One of the most important features of a knowledge assistant is the ability to understand where its answer came from.</p><p>Trivox tracks the source metadata of retrieved chunks.</p><p>Source information can include:</p><ul><li>Filename</li><li>Document ID</li><li>Chunk index</li><li>Retrieval distance</li></ul><p>The API returns source information to the frontend.</p><p>This makes the answer more transparent because users can identify the documents that contributed relevant context.</p><p>Instead of receiving only:</p><blockquote><em>Docker uses a client-server architecture.</em></blockquote><p>The user can also see that the answer was generated using retrieved chunks from a document such as:</p><pre>Docker.pdf</pre><pre>Chunk 0<br>Chunk 1</pre><p>This is particularly useful when working with technical documentation.</p><p>The user can return to the original material instead of blindly trusting the generated answer.</p><h3>19. Document Management</h3><p>Trivox includes APIs for managing uploaded documents.</p><h3>Upload</h3><pre>POST /api/documents/upload</pre><p>Uploads and processes PDF or TXT files.</p><h3>List Documents</h3><pre>GET /api/documents</pre><p>Returns the uploaded documents and their associated chunk information.</p><h3>Delete Document</h3><pre>DELETE /api/documents/{document_id}</pre><p>Deletes the document and its associated chunks from the vector store.</p><p>The document ID is stored in the metadata of every chunk, allowing the backend to identify and remove all chunks belonging to a document.</p><p>This makes the knowledge base manageable rather than simply allowing files to accumulate permanently.</p><h3>20. API Structure</h3><p>The backend is organized around separate responsibilities.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*37SFzWhapWGgzxIvf3fknw.png" /></figure><p>This separation keeps the API layer organized and allows the different capabilities to evolve independently.</p><p>FastAPI provides the backend routing and orchestration layer for these services.</p><h3>21. Docker Deployment</h3><p>Trivox is containerized using Docker.</p><p>The application runs as separate frontend and backend containers.</p><pre>flowchart TD<br>    U[User Browser]</pre><pre>    U --&gt; F[Frontend Container]<br>    F --&gt; B[Backend Container]</pre><pre>    B --&gt; O[Ollama on Host]<br>    B --&gt; C[ChromaDB]<br>    B --&gt; S[SQLite]</pre><pre>    P[Docker Volume: trivox-data] --&gt; C<br>    P --&gt; S</pre><h3>Frontend</h3><pre>Next.js</pre><pre>Port: 3000</pre><h3>Backend</h3><pre>FastAPI</pre><pre>Port: 8000</pre><h3>Ollama</h3><p>Ollama runs locally and provides the model inference API.</p><pre>Port: 11434</pre><h3>Persistent Storage</h3><p>The backend uses persistent storage mounted through the Docker volume:</p><pre>trivox-data:/data</pre><p>Persistent storage is important because container recreation should not erase the knowledge base and conversation data.</p><p>The vector database and SQLite data are maintained outside the disposable container filesystem.</p><p>This allows the application containers to be rebuilt without intentionally deleting stored data.</p><h3>22. Evaluation: How Do We Know Retrieval Is Working?</h3><p>Building a RAG system is only half of the work.</p><p>The other half is evaluating whether it retrieves the correct information.</p><p>A response can sound convincing while the retrieval pipeline has selected the wrong chunks.</p><p>Therefore, retrieval quality needs to be measured separately from answer quality.</p><p>I started exploring retrieval evaluation using questions with known relevant document chunks.</p><p>The evaluation focuses on metrics such as:</p><h3>I recommend using these four metrics for your evaluation framework:</h3><ol><li><strong>Precision@K</strong></li><li><strong>Recall@K</strong></li><li><strong>Hit Rate@K</strong></li><li><strong>Correct Rejection Rate</strong></li></ol><p>Use <strong>K = 3</strong> for your current evaluation if you’re measuring the top 3 retrieved chunks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/808/1*VKYGCoAq0eJnsdqIkx5mEA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/610/1*SKzfXIqvnaVbk9qkf0M0Qg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/695/1*NkFCcTx5K3LBb0cYX-C5bg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/1*wiqbwwjQfG1R5jaxC8G6Nw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*5w1Xw7yCqy4jXeRJhlAM-g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/781/1*neQ_MjgjbO_0C99x0JGKxA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/830/1*TV1LPQOOApuZKiUGYiOt1Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*gQIlquwewfdjNufJjjPZyw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/830/1*o-viGIc7f6Y58ncWf9EcrQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*Qh1r_PeWPKWXqUMXU5rvAg.png" /></figure><h3>23. Engineering Decisions and Trade-Offs</h3><p>Trivox is a local AI project, so several engineering decisions were made to keep the architecture practical and manageable.</p><h3>Why Ollama?</h3><p>Ollama makes it possible to run LLMs locally without integrating directly with a hosted inference API.</p><p>It provides a convenient local model runtime and API for both text generation and embeddings.</p><h3>Why ChromaDB?</h3><p>The project needed a vector database capable of storing document embeddings and retrieving semantically relevant chunks.</p><p>ChromaDB provides a straightforward persistent vector store suitable for this use case.</p><h3>Why SQLite?</h3><p>Conversation history does not require a separate database server for the current scale of the project.</p><p>SQLite provides local persistence with minimal infrastructure.</p><h3>Why Hybrid Retrieval?</h3><p>Vector search is useful for semantic similarity, while BM25 is useful for exact terms.</p><p>Combining both is particularly valuable for technical documents.</p><h3>Why RRF?</h3><p>Different retrieval systems produce different scores.</p><p>RRF combines their rankings without requiring their raw scores to be directly comparable.</p><h3>Why Reranking?</h3><p>The retrieval stage finds candidates. Reranking helps prioritize the most relevant candidates before they are sent to the LLM.</p><h3>Why Local Models?</h3><p>Local inference provides:</p><ul><li>No dependency on a hosted inference provider for core generation</li><li>Greater control over the model runtime</li><li>A potentially more private local workflow</li><li>An opportunity to experiment with AI infrastructure</li></ul><p>The trade-off is that local model performance and speed depend on available hardware and model size.</p><h3>24. What I Learned Building Trivox</h3><p>Building Trivox helped me understand that an AI application is much more than connecting a frontend to an LLM.</p><p>The model is only one component of the complete system.</p><p>The quality of a RAG application depends on the entire pipeline:</p><ul><li>Document extraction</li><li>Chunking strategy</li><li>Embedding model</li><li>Retrieval design</li><li>Keyword search</li><li>Query transformation</li><li>Ranking</li><li>Context selection</li><li>Prompt construction</li><li>Model generation</li><li>Source tracking</li><li>Persistence</li><li>Evaluation</li></ul><p>A model may generate an excellent response, but if the retrieval stage provides irrelevant context, the quality of the overall application can suffer.</p><p>I also learned the importance of separating responsibilities.</p><p>The document ingestion pipeline prepares knowledge.</p><p>The retrieval pipeline finds knowledge.</p><p>The context builder prepares the information.</p><p>The LLM generates the response.</p><p>The database maintains conversational state.</p><p>The API coordinates the entire process.</p><p>Understanding these boundaries makes the system easier to debug, improve, and extend.</p><h3>25. Current Limitations and Future Improvements</h3><p>Trivox is an evolving project. There are several areas I want to improve as the system develops.</p><h3>Retrieval Evaluation</h3><p>Expand the evaluation dataset and systematically measure retrieval precision, recall, and hit rate across different types of technical questions.</p><h3>Batch and Parallel Processing</h3><p>The current document ingestion process generates embeddings sequentially for individual chunks.</p><p>Batch embedding and controlled parallel processing could improve ingestion performance for larger documents.</p><h3>Background Document Processing</h3><p>Large document uploads could eventually be processed asynchronously, allowing the API to return a processing status instead of waiting for the complete ingestion pipeline.</p><h3>Retrieval Optimization</h3><p>BM25 currently builds its index from the stored document corpus during search operations. Optimizing index reuse and retrieval execution could reduce repeated work.</p><h3>Better Context Management</h3><p>The current context limit is based on characters. Token-aware context management could provide more precise control over the model’s context window.</p><h3>Improved Source Navigation</h3><p>Allow users to navigate directly to the relevant document sections or page locations when source metadata is available.</p><h3>Better Knowledge Management</h3><p>Potential future improvements include document categories, tags, document versioning, and improved knowledge base organization.</p><h3>Model Experimentation</h3><p>Experiment with different embedding models, rerankers, and local LLMs to compare quality, performance, and resource consumption.</p><p>These improvements are not just feature additions. They are opportunities to measure how different architectural choices affect retrieval and answer quality.</p><h3>26. The Complete Trivox Workflow</h3><p>Let’s put everything together.</p><h3>Phase 1: Knowledge Ingestion</h3><pre>Upload PDF/TXT<br>      ↓<br>Validate File<br>      ↓<br>Extract Text<br>      ↓<br>Chunk Text<br>      ↓<br>Generate Embeddings<br>      ↓<br>Store in ChromaDB</pre><h3>Phase 2: Question Processing</h3><pre>User Question<br>      ↓<br>Load Conversation History<br>      ↓<br>Contextualize Question<br>      ↓<br>Generate Multiple Queries<br>      ↓<br>Generate Query Embeddings</pre><h3>Phase 3: Retrieval</h3><pre>Query Embeddings<br>      ↓<br>Vector Search ──────┐<br>                    ├── Hybrid Retrieval<br>BM25 Search ────────┘<br>      ↓<br>Reciprocal Rank Fusion<br>      ↓<br>Filtering<br>      ↓<br>Deduplication<br>      ↓<br>Reranking<br>      ↓<br>Top-K Relevant Chunks</pre><h3>Phase 4: Generation</h3><pre>User Question<br>      +<br>Conversation History<br>      +<br>Retrieved Context<br>      ↓<br>Prompt Construction<br>      ↓<br>Qwen 2.5 via Ollama<br>      ↓<br>Streaming Response<br>      ↓<br>Source References<br>      ↓<br>Save Conversation in SQLite</pre><p>This is the complete journey from uploaded knowledge to a context-aware answer.</p><h3>Conclusion</h3><p>Trivox AI started as an idea: make my own technical knowledge searchable through conversation.</p><p>But building it required understanding much more than an LLM.</p><p>It required designing a document ingestion pipeline, working with embeddings, implementing semantic search, combining retrieval methods, building a ranking system, managing context, handling streaming responses, maintaining conversation history, and thinking about evaluation.</p><p>The most important lesson from this project is that <strong>retrieval quality is a fundamental part of building useful AI applications</strong>.</p><p>A good RAG system is not simply:</p><blockquote><em>Upload a document → Ask a question → Call an LLM.</em></blockquote><p>It is a carefully designed pipeline that prepares knowledge, finds relevant information, filters and ranks it, and then gives the model the right context to generate a useful answer.</p><p>Trivox is still evolving, and there is much more to improve.</p><p>But building it has given me hands-on experience with how modern AI applications are structured beyond the model itself — from data processing and retrieval engineering to backend orchestration and local AI infrastructure.</p><p>The goal is not just to build another chatbot.</p><p>The goal is to build an AI system that can actually work with knowledge.</p><h3>Tech Stack</h3><p><strong>Frontend:</strong> Next.js, React, TypeScript, Tailwind CSS</p><p><strong>Backend:</strong> Python, FastAPI</p><p><strong>LLM Runtime:</strong> Ollama</p><p><strong>Generation Model:</strong> Qwen 2.5 1.5B</p><p><strong>Embedding Model:</strong> nomic-embed-text</p><p><strong>Vector Database:</strong> ChromaDB</p><p><strong>Retrieval:</strong> Vector Search, BM25, Hybrid Retrieval</p><p><strong>Ranking:</strong> Reciprocal Rank Fusion (RRF), Reranking</p><p><strong>Database:</strong> SQLite</p><p><strong>Deployment:</strong> Docker</p><p><em>Trivox AI — Local AI for technical knowledge, powered by retrieval and your own documents.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e0ucd59JuQ5QBuEO_y6dhg.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ez4E27JZM6aEY1qDyijN6A.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5YqDuu56LQEy62QrK-8LZQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vt2-7l9zS6-YaNYY2J8tyQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rr2s5dGSFsP4J2Kv22Fw4g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o8SDJuFUS7QqoaS3O6l_Rg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2Z7EBNoVbtDsinA76iBfOQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jPcr3PzfvXmZIG0DWvKA5w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/782/1*_RYokFkp47zqDk39ZY8AVQ.png" /></figure><p><strong>Trivox doesn’t send the entire knowledge base to the LLM. It processes documents into searchable chunks, retrieves relevant knowledge using hybrid search, ranks the results, builds context, and then uses that context to generate an answer.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AMqZHxvMoxsi7pIzCKcMiQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0Mxp2J4BAl7upK-lakjjdw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A7npff_EwniUpMRzKAttDg.png" /></figure><p>Example of Backend Logs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CrhUQRsL0ngCJGDU5_-90Q.png" /></figure><p>#AI #RAG #ArtificialIntelligence #LLM #GenerativeAI #Python #FastAPI #Ollama #ChromaDB #SystemDesign #SoftwareEngineering #DevOps #LocalAI #MachineLearning</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=012658fdd7fd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[System Design: Uber  | A Complete Architecture Case Study]]></title>
            <link>https://theena18.medium.com/system-design-uber-a-complete-architecture-case-study-277ed0b61b36?source=rss-e6bb5de386b9------2</link>
            <guid isPermaLink="false">https://medium.com/p/277ed0b61b36</guid>
            <category><![CDATA[uber]]></category>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[software-architecture]]></category>
            <dc:creator><![CDATA[Dinakaran]]></dc:creator>
            <pubDate>Sat, 24 Oct 2026 05:22:27 GMT</pubDate>
            <atom:updated>2026-10-24T05:22:27.106Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>How to design a scalable, real-time ride-hailing platform</strong></p><p>Uber is more than a ride-booking application. Behind its simple interface is a distributed system that continuously processes driver locations, finds nearby vehicles, matches riders with drivers, and manages trips in real time.</p><p>In this system design case study, we’ll explore how to design an Uber-like platform, from the initial requirements to a scalable architecture.</p><h3>1. Understanding the Problem</h3><p>Imagine a rider opens the application, enters a pickup location and destination, and requests a ride.</p><p>The system must:</p><ul><li>Estimate the fare and arrival time.</li><li>Find nearby available drivers.</li><li>Select the most suitable driver.</li><li>Notify the driver and handle acceptance or rejection.</li><li>Track the driver’s location in real time.</li><li>Manage the ride lifecycle reliably.</li></ul><p>The main challenge is coordinating riders and moving drivers while maintaining low latency, high availability, and correctness.</p><h3>2. Functional and Non-Functional Requirements</h3><h3>Functional Requirements</h3><ol><li>Fare estimation based on pickup, destination, distance, and time.</li><li>Ride creation and cancellation.</li><li>Real-time driver location tracking.</li><li>Nearby driver discovery and matching.</li><li>Driver acceptance or rejection.</li><li>Ride status updates and trip completion.</li></ol><h3>Non-Functional Requirements</h3><ul><li><strong>Low latency:</strong> Find and notify drivers quickly.</li><li><strong>High availability:</strong> Keep ride booking operational during failures.</li><li><strong>Scalability:</strong> Handle millions of location updates and ride requests.</li><li><strong>Consistency:</strong> Prevent a driver from being assigned to conflicting rides.</li><li><strong>Fault tolerance:</strong> Recover from service failures and retry interrupted workflows.</li></ul><h3>3. High-Level Architecture</h3><p>The architecture separates real-time location processing, ride management, matching, and durable storage.</p><pre>            Rider App                Driver App<br>               |                        |<br>               |                        | GPS Updates<br>               v                        v<br>         API Gateway              Location Service<br>               |                        |<br>               v                        v<br>          Ride Service            Redis Geo Index<br>               |<br>               v<br>          Ride Request<br>               |<br>               v<br>          Message Queue<br>               |<br>               v<br>        Matching Service<br>               |<br>               v<br>       Nearby Driver Search<br>               |<br>               v<br>        Driver Reservation<br>               |<br>               v<br>      Notification Service<br>               |<br>               v<br>       Driver Accepts Ride<br>               |<br>               v<br>        Ride State Updates<br>               |<br>               v<br>          PostgreSQL</pre><p><strong>Core components:</strong></p><ul><li><strong>API Gateway:</strong> Authentication, request routing, and rate limiting.</li><li><strong>Ride Service:</strong> Manages fare estimates, ride requests, and trip states.</li><li><strong>Location Service:</strong> Receives and processes driver GPS updates.</li><li><strong>Redis:</strong> Stores frequently changing driver locations and temporary reservations.</li><li><strong>Matching Service:</strong> Finds, ranks, and assigns candidate drivers.</li><li><strong>Message Queue:</strong> Buffers ride requests and supports asynchronous processing.</li><li><strong>Notification Service:</strong> Sends ride requests and status notifications.</li><li><strong>PostgreSQL:</strong> Stores durable ride records, users, fares, and trip history.</li></ul><p>This is a logical architecture for a scalable ride-hailing system, not a claim that every component exactly matches Uber’s internal production implementation.</p><h3>4. Designing the Ride Request Flow</h3><p>When a rider confirms a ride, the system follows this sequence:</p><ol><li>The client sends a ride request to the API Gateway.</li><li>The Ride Service validates the request and fare estimate.</li><li>A ride record is created with the REQUESTED state.</li><li>A matching workflow begins.</li><li>The Matching Service discovers nearby available drivers.</li><li>The system reserves a candidate driver and sends a request.</li><li>The driver accepts or rejects the request.</li><li>On acceptance, the ride is assigned and the rider is notified.</li></ol><p>Example API:</p><pre>POST /rides</pre><p>Request:</p><pre>{<br>  &quot;fareId&quot;: &quot;fare_123&quot;,<br>  &quot;pickup&quot;: {<br>    &quot;lat&quot;: 11.6643,<br>    &quot;lng&quot;: 78.1460<br>  },<br>  &quot;destination&quot;: {<br>    &quot;lat&quot;: 11.5880,<br>    &quot;lng&quot;: 77.8380<br>  }<br>}</pre><p>The backend must authenticate the rider and validate all important values. It should not blindly trust a fare or user identity supplied by the client.</p><h3>5. The Biggest Challenge: Real-Time Driver Locations</h3><p>Suppose 10 million drivers each send a location update every five seconds.</p><p>The approximate update rate is:</p><p><strong>10,000,000 ÷ 5 = 2,000,000 updates per second.</strong></p><p>Writing every GPS update directly to a traditional relational database would create enormous write pressure.</p><p>The solution is to separate rapidly changing location data from durable business records.</p><h3>Using Redis Geospatial Indexing</h3><pre>Driver App<br>    |<br>    v<br>Location Service<br>    |<br>    v<br>Redis Geospatial Index<br>    |<br>    v<br>Nearby Driver Search</pre><p>Redis supports geospatial operations such as GEOADD and GEOSEARCH.</p><p>Conceptually, the system maintains the latest location of each driver and searches for drivers near the rider’s pickup coordinates.</p><p>For example:</p><pre>Rider Location<br>      |<br>      v<br>Search within a radius<br>      |<br>      v<br>Driver A: 0.8 km<br>Driver B: 1.2 km<br>Driver C: 1.9 km<br>      |<br>      v<br>Rank candidates</pre><p>The system must also reject stale locations. A driver who has not sent a recent heartbeat should not be treated as reliably available.</p><p>Redis replication, failover, and appropriate persistence can improve resilience. Because location data is continuously refreshed, lost recent coordinates can often be rebuilt from driver updates.</p><h3>6. Scaling Geospatial Search</h3><p>Searching every driver in a city is inefficient.</p><p>A spatial index partitions geographic space into searchable regions. Technologies and approaches can include geohash, S2, or Uber’s H3 hierarchical hexagonal grid system.</p><p>With geographic partitioning:</p><ol><li>Determine the rider’s geographic cell.</li><li>Search that cell and relevant neighboring cells.</li><li>Filter drivers by availability and freshness.</li><li>Rank candidates using estimated driving time and other factors.</li></ol><pre>            Geographic Region<br>                     |<br>              Rider&#39;s Cell<br>                     |<br>          +----------+----------+<br>          |          |          |<br>       Cell A      Cell B      Cell C<br>          |          |          |<br>          +----------+----------+<br>                     |<br>              Candidate Drivers</pre><p>The search can expand to additional cells or a larger radius if no suitable driver is found.</p><p>Geographic partitioning reduces unnecessary searches and supports horizontal scaling. However, cell boundaries, uneven driver density, and busy urban areas require careful handling.</p><h3>7. Preventing Double Booking with Atomic Reservation</h3><p>Consider two riders requesting rides at almost the same time.</p><p>Both requests identify Driver A as the nearest available driver. If both matching workers assign the driver independently, the system can create conflicting assignments.</p><p>Finding a driver and reserving a driver are two different operations.</p><p>The system needs an atomic reservation mechanism.</p><p>For example, Redis supports conditional lock creation:</p><pre>SET driver:A:lock ride123 NX EX 10</pre><p>Conceptually:</p><ul><li>NX creates the lock only if it doesn&#39;t already exist.</li><li>EX 10 gives the lock a ten-second expiry.</li><li>Only one competing request should acquire that particular lock.</li></ul><p>If the reservation fails, the matching process tries another candidate.</p><p><strong>Important:</strong> A Redis lock alone is not a complete correctness guarantee. Production systems must also handle lock expiry, retries, stale workers, and failures during database updates. The durable ride state should enforce assignment invariants, using transactions and, where appropriate, conditional updates or optimistic concurrency control.</p><h3>8. Handling Driver Acceptance, Rejection, and Timeout</h3><p>A driver may accept, reject, or ignore a ride request.</p><p>The matching workflow must support all three outcomes.</p><pre>Find Driver A<br>     |<br>Reserve Driver A<br>     |<br>Send Notification<br>     |<br>Wait for Response<br>     |<br>  +--+----------+<br>  |             |<br>Accept        Timeout/<br>  |           Reject<br>  v             |<br>Assign          v<br>Ride         Try Driver B</pre><p>A short-lived reservation prevents the driver from being offered conflicting rides while the request is pending.</p><p>For more complex workflows, a durable workflow engine such as Temporal can manage timers, retries, and recovery after worker failures.</p><p>This is more reliable than keeping the entire matching process inside a single application thread or in-memory timer.</p><h3>9. Why Use a Message Queue?</h3><p>During peak demand, many riders may request rides simultaneously.</p><p>Sending every request directly into a limited number of matching workers can overload the service.</p><p>A queue such as Kafka or Amazon SQS can absorb traffic spikes and allow workers to process requests asynchronously.</p><pre>Ride Service<br>     |<br>     v<br>Message Queue<br>     |<br>     +--------+--------+<br>     |        |        |<br>     v        v        v<br>  Worker 1 Worker 2 Worker 3<br>     |        |        |<br>     +--------+--------+<br>              |<br>              v<br>       Matching Service</pre><p>Workers can scale horizontally as traffic increases.</p><p>Queue-based systems also need idempotent processing, retry policies, dead-letter handling where appropriate, and careful ordering of ride-state changes. A queue does not automatically guarantee that every business operation executes exactly once.</p><p>For geographic workloads, requests and workers can be partitioned by region or spatial cell, provided cross-region requests and overloaded partitions are handled correctly.</p><h3>10. Real-Time Driver Tracking</h3><p>After the driver accepts, the rider expects live location updates.</p><p>A possible flow is:</p><pre>Driver GPS<br>    |<br>    v<br>Location Service<br>    |<br>    v<br>Latest Location / Events<br>    |<br>    v<br>Real-Time Gateway<br>    |<br>    v<br>Rider App</pre><p>WebSockets, Server-Sent Events, or other push mechanisms can deliver updates without requiring the rider to poll constantly.</p><p>The system should limit update frequency, handle reconnects, and ensure that a delayed location update doesn’t overwrite a newer one.</p><h3>11. Database Design</h3><p>Different kinds of data need different storage strategies.</p><p>DataSuitable StorageRider and driver profilesPostgreSQLDurable ride recordsPostgreSQLFare estimates and trip historyPostgreSQLLatest driver locationsRedis geospatial indexTemporary driver reservationsRedis or another atomic coordination mechanismAsynchronous ride eventsKafka or SQSFrequently accessed reference dataCache, where appropriate</p><p>The key principle is that not every piece of data needs the same consistency, latency, or durability guarantees.</p><p><strong>Ephemeral data</strong> such as recent GPS coordinates can be refreshed.</p><p><strong>Durable data</strong> such as accepted rides and trip history must survive service restarts and infrastructure failures.</p><h3>12. Handling Failures</h3><p>A robust design must anticipate failures.</p><p><strong>Redis fails:</strong> Use replication and failover where appropriate. Rebuild location indexes from fresh driver updates, and avoid assigning drivers based on unreliable stale data.</p><p><strong>Matching worker crashes:</strong> Retry queued work safely and make processing idempotent.</p><p><strong>Driver doesn’t respond:</strong> Expire the reservation and try another candidate.</p><p><strong>Two requests compete for a driver:</strong> Use atomic reservation plus durable assignment validation.</p><p><strong>Traffic spikes:</strong> Buffer requests, apply backpressure, and scale workers horizontally.</p><p><strong>Notification delivery fails:</strong> Retry delivery and allow the driver application to reconnect or retrieve pending requests through an appropriate recovery flow.</p><h3>13. Ride Lifecycle</h3><p>A ride can move through the following states:</p><pre>REQUESTED<br>    |<br>    v<br>MATCHING<br>    |<br>    v<br>DRIVER_ASSIGNED<br>    |<br>    v<br>DRIVER_ARRIVING<br>    |<br>    v<br>IN_PROGRESS<br>    |<br>    v<br>COMPLETED</pre><p>Other valid terminal outcomes include CANCELLED and MATCH_FAILED.</p><p>Transitions should be validated by the backend. For example, a ride must not become COMPLETED before it has started, and a cancelled ride must not be silently reassigned without a defined recovery process.</p><h3>14. Key Trade-Offs</h3><h3>Redis vs. PostgreSQL for locations</h3><p>Redis provides fast, frequently updated geospatial data access. PostgreSQL provides durable relational storage and transactional operations. A production system may also use additional location-history storage for analytics.</p><h3>Nearest driver vs. best driver</h3><p>The closest driver by straight-line distance may not arrive first. Ranking should consider estimated driving time, traffic, availability, and other business constraints.</p><h3>Strong consistency vs. availability</h3><p>Location updates can tolerate some temporary staleness. Driver assignment requires stronger coordination because conflicting assignments directly affect riders and drivers.</p><h3>One global system vs. geographic partitioning</h3><p>A single deployment is simpler initially. Geographic partitioning can improve latency and scale, but introduces operational complexity and uneven workload challenges.</p><h3>15. Final Architecture Summary</h3><pre>Rider App                    Driver App<br>    |                            |<br>    v                            v<br>API Gateway                 GPS Updates<br>    |                            |<br>    v                            v<br>Ride Service              Location Service<br>    |                            |<br>    v                            v<br>Message Queue               Redis Geo<br>    |                            |<br>    v                            |<br>Matching Service &lt;---------------+<br>    |<br>    v<br>Nearby Driver Search<br>    |<br>    v<br>Atomic Reservation<br>    |<br>    v<br>Notification Service<br>    |<br>    v<br>Driver Acceptance<br>    |<br>    v<br>Durable Ride State<br>    |<br>    v<br>PostgreSQL</pre><p>This architecture combines real-time location processing, spatial search, asynchronous work, atomic reservations, and durable state management.</p><h3>Conclusion</h3><p>Designing Uber is fundamentally about coordinating moving resources with incoming demand.</p><p>The most important lessons are:</p><ol><li><strong>Real-time location:</strong> Use an efficient location index rather than writing every GPS update directly to a relational database.</li><li><strong>Geospatial search:</strong> Search nearby geographic cells instead of scanning every driver.</li><li><strong>Atomic reservation:</strong> Prevent a driver from being assigned to conflicting rides.</li><li><strong>Durable workflows:</strong> Handle acceptance, rejection, timeouts, and retries reliably.</li><li><strong>Asynchronous processing:</strong> Use queues and horizontally scalable workers to absorb traffic spikes.</li><li><strong>Storage separation:</strong> Distinguish refreshable location data from durable business records.</li></ol><p>The goal isn’t to choose the largest number of technologies. It’s to select the right tools for each problem and explain why the trade-offs make sense.</p><p><strong>That is the essence of designing a scalable, real-time ride-hailing system.</strong></p><p><em>System Design Series | Uber Architecture Case Study</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vcgzOMg8qQc1-OpsXD9x3Q.png" /></figure><p>#SystemDesign #Uber #SystemDesignInterview #DistributedSystems #Redis #Kafka #Scalability #BackendEngineering #SoftwareArchitecture</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=277ed0b61b36" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[YouTube System Design: Designing a Scalable Video Streaming Platform]]></title>
            <link>https://theena18.medium.com/youtube-system-design-designing-a-scalable-video-streaming-platform-f9e4723c814a?source=rss-e6bb5de386b9------2</link>
            <guid isPermaLink="false">https://medium.com/p/f9e4723c814a</guid>
            <category><![CDATA[cdn]]></category>
            <category><![CDATA[youtube-system-design]]></category>
            <category><![CDATA[aws-s3]]></category>
            <category><![CDATA[youtube-video-upload]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <dc:creator><![CDATA[Dinakaran]]></dc:creator>
            <pubDate>Mon, 05 Oct 2026 07:03:20 GMT</pubDate>
            <atom:updated>2026-10-05T07:03:20.731Z</atom:updated>
            <content:encoded><![CDATA[<p>YouTube looks simple from a user’s perspective:</p><p><strong>Upload a video → Click Play → Watch.</strong></p><p>But behind that simple experience is a massive distributed system handling large video files, video processing, global traffic, caching, content delivery, and millions of concurrent viewers.</p><p>In this article, we’ll design a simplified <strong>YouTube-like video platform</strong> from scratch and understand the key system design concepts involved.</p><h3>1. What Are We Building?</h3><p>For this system design, we’ll focus on two core features:</p><ul><li>Upload a video</li><li>Watch/stream a video</li></ul><p>We’ll keep features such as recommendations, comments, subscriptions, likes, monetization, and live streaming outside the initial scope.</p><p>The goal is to understand the architecture that makes <strong>large-scale video upload and streaming</strong> possible.</p><h3>2. Functional Requirements</h3><h3>Video Upload</h3><p>Users should be able to:</p><ul><li>Upload large video files</li><li>Provide title and description</li><li>Resume an interrupted upload</li></ul><h3>Video Playback</h3><p>Users should be able to:</p><ul><li>Search/select a video</li><li>Start playback quickly</li><li>Watch the video without frequent buffering</li><li>Automatically switch video quality depending on network conditions</li></ul><h3>Video Metadata</h3><p>We need to store:</p><pre>videoId<br>userId<br>title<br>description<br>duration<br>thumbnail<br>status<br>createdAt</pre><h3>3. Non-Functional Requirements</h3><p>Our system should provide:</p><h3>High Availability</h3><p>Videos should remain available even if individual servers fail.</p><h3>Scalability</h3><p>The system should support a huge number of uploads and, more importantly, an enormous number of video views.</p><h3>Low Latency</h3><p>Video playback should start quickly.</p><h3>Reliability</h3><p>An interrupted upload shouldn’t require the user to start from zero.</p><h3>High Throughput</h3><p>The system needs to transfer enormous amounts of video data.</p><h3>4. The Biggest Challenge</h3><p>The most important thing to understand is that <strong>video files are very different from normal application data</strong>.</p><p>A normal API request might contain:</p><pre>JSON<br>{<br>    &quot;title&quot;: &quot;My Video&quot;<br>}</pre><p>A video could be:</p><pre>500 MB<br>1 GB<br>5 GB<br>10 GB+</pre><p>So we should not design:</p><pre>Client<br>   ↓<br>Backend Server<br>   ↓<br>Database</pre><p>for storing the actual video.</p><p>Instead, we separate:</p><p><strong>Metadata</strong> from <strong>Video Data</strong>.</p><h3>5. High-Level Architecture</h3><p>The system can be divided into two major flows:</p><h3>Upload</h3><pre>Client<br>   ↓<br>Video API<br>   ↓<br>Pre-signed URL<br>   ↓<br>Object Storage<br>   ↓<br>Message Queue<br>   ↓<br>Video Processing<br>   ↓<br>Processed Video</pre><h3>Playback</h3><pre>Client<br>   ↓<br>Video API<br>   ↓<br>Metadata<br>   ↓<br>Manifest<br>   ↓<br>CDN<br>   ↓<br>Video Segments</pre><p>This separation is one of the most important ideas in the entire design.</p><h3>6. Why Object Storage?</h3><p>We should store video files in object storage such as:</p><ul><li>Amazon S3</li><li>Google Cloud Storage</li><li>Azure Blob Storage</li></ul><p>Instead of putting videos inside PostgreSQL/MySQL, we use:</p><pre>Object Storage<br>    │<br>    ├── Original video<br>    ├── Processed videos<br>    ├── Video segments<br>    ├── Audio<br>    ├── Thumbnails<br>    └── Manifests</pre><p>Databases are designed for structured data.</p><p>Object storage is designed for massive amounts of unstructured data such as videos, images, backups, and documents.</p><h3>7. Direct Upload Using Pre-Signed URLs</h3><p>One of the most important design decisions is:</p><blockquote><strong><em>Don’t send the entire video through our application servers.</em></strong></blockquote><p>Instead:</p><pre>Request upload<br>Client ─────────────────────→ Video API<br>                                 │<br>                                 │ Generate<br>                                 │ pre-signed URL<br>                                 ▼<br>Client ─────────────────────→ Object Storage<br>          Video bytes</pre><p>The backend only handles authorization and metadata.</p><p>The large file travels directly from the client to object storage.</p><p>This prevents our application servers from becoming a bandwidth bottleneck.</p><h3>8. Multipart Upload</h3><p>What happens when a user uploads a 5 GB video?</p><p>We can divide it into multiple parts:</p><pre>5 GB Video<br>    │<br>    ├── Part 1<br>    ├── Part 2<br>    ├── Part 3<br>    ├── Part 4<br>    ├── Part 5<br>    └── ...</pre><p>These parts can be uploaded independently and potentially in parallel.</p><h3>Why is this useful?</h3><p>Suppose:</p><pre>Part 1 ✓<br>Part 2 ✓<br>Part 3 ✓<br>Part 4 ✗<br>Part 5 ✗</pre><p>The network fails.</p><p>We don’t need to restart the entire 5 GB upload.</p><p>We simply retry:</p><pre>Part 4<br>Part 5</pre><p>This provides <strong>resumable uploads</strong>.</p><h3>9. Upload Flow</h3><p>The complete upload flow looks like this:</p><pre>                 Client<br>                   │<br>                   │ 1. Create upload<br>                   ▼<br>             ┌─────────────┐<br>             │  Video API  │<br>             └──────┬──────┘<br>                    │<br>                    │ 2. Pre-signed URL<br>                    ▼<br>                Object Storage<br>                    │<br>                    │ 3. Upload video<br>                    ▼<br>                Video Stored</pre><p>The database can initially store:</p><pre>videoId = v123<br>status = UPLOADING</pre><p>After the upload completes:</p><pre>status = PROCESSING</pre><h3>10. Why Do We Need Video Processing?</h3><p>Suppose a user uploads:</p><pre>1080p.mp4</pre><p>But the viewer has a slow mobile connection.</p><p>Sending the original 1080p video could cause buffering.</p><p>Instead, we create multiple versions:</p><pre>1080p<br>720p<br>480p<br>360p<br>240p</pre><p>This process is called <strong>transcoding</strong>.</p><h3>11. Video Transcoding</h3><p>The original video goes into a processing pipeline:</p><pre>Original Video<br>      │<br>      ▼<br>   Transcoding<br>      │<br>      ├── 1080p<br>      ├── 720p<br>      ├── 480p<br>      ├── 360p<br>      └── 240p</pre><p>Different resolutions can have different bitrates.</p><p>For example:</p><pre>1080p → High bitrate<br>720p  → Medium-high bitrate<br>480p  → Medium bitrate<br>360p  → Low bitrate</pre><p>The player can then select an appropriate version.</p><h3>12. Why Use a Message Queue?</h3><p>Video processing can be expensive and slow.</p><p>We don’t want:</p><pre>Upload<br>   ↓<br>Wait for transcoding<br>   ↓<br>Response</pre><p>Instead, we make processing asynchronous:</p><pre>Object Storage<br>      │<br>      ▼<br> Message Queue<br>      │<br>      ▼<br>Processing Workers</pre><p>For example:</p><pre>                 Queue<br>                   │<br>        ┌──────────┼──────────┐<br>        ▼          ▼          ▼<br>     Worker 1   Worker 2   Worker 3</pre><p>If uploads increase, we can add more workers.</p><p>This allows the processing layer to scale independently.</p><h3>13. Video Processing Pipeline</h3><p>A simplified pipeline looks like:</p><pre>Original Video<br>      │<br>      ▼<br>    Validate<br>      │<br>      ▼<br>   Transcode<br>      │<br>      ▼<br>   Segment Video<br>      │<br>      ▼<br>Generate Manifest<br>      │<br>      ▼<br>Generate Thumbnail<br>      │<br>      ▼<br>Store Outputs<br>      │<br>      ▼<br>Mark Video READY</pre><p>If a worker fails, the job can be retried.</p><p>The original video remains safely stored, so we can process it again.</p><h3>14. Video Segmentation</h3><p>We shouldn’t necessarily deliver one giant MP4 file to the viewer.</p><p>Instead, we divide the video into small segments.</p><p>For example:</p><pre>Video<br> │<br> ├── Segment 1 → 0–4 sec<br> ├── Segment 2 → 4–8 sec<br> ├── Segment 3 → 8–12 sec<br> ├── Segment 4 → 12–16 sec<br> └── ...</pre><p>And we do this for each quality:</p><pre>1080p<br> ├── segment1<br> ├── segment2<br> └── segment3</pre><pre>720p<br> ├── segment1<br> ├── segment2<br> └── segment3</pre><pre>480p<br> ├── segment1<br> ├── segment2<br> └── segment3</pre><p>Now the player can request only the segments it needs.</p><h3>15. Adaptive Bitrate Streaming</h3><p>This is one of the most important concepts in YouTube system design.</p><p>Imagine you’re watching a video at:</p><pre>1080p</pre><p>Suddenly your internet becomes slow.</p><p>The player can switch:</p><pre>1080p<br>   ↓<br>720p<br>   ↓<br>480p</pre><p>When the network improves:</p><pre>480p<br>   ↓<br>720p<br>   ↓<br>1080p</pre><p>This is called:</p><blockquote><strong><em>Adaptive Bitrate Streaming (ABR)</em></strong></blockquote><p>The player continuously considers factors such as:</p><ul><li>Network bandwidth</li><li>Current buffer</li><li>Device capabilities</li><li>Available video qualities</li></ul><p>and selects an appropriate quality.</p><h3>16. HLS and DASH</h3><p>Two common technologies used for adaptive streaming are:</p><h3>HLS</h3><p>HTTP Live Streaming.</p><p>A manifest can look conceptually like:</p><pre>master.m3u8</pre><h3>MPEG-DASH</h3><p>Uses a manifest such as:</p><pre>manifest.mpd</pre><p>The manifest tells the player:</p><pre>Available qualities<br>       ↓<br>1080p<br>720p<br>480p<br>360p</pre><pre>Available segments<br>       ↓<br>segment1<br>segment2<br>segment3<br>...</pre><p>The player then requests the appropriate segments.</p><h3>17. Why Do We Need a CDN?</h3><p>Now imagine one video becomes extremely popular.</p><p>Suppose:</p><pre>10 million users<br>        ↓<br>watch the same video</pre><p>We shouldn’t make all those users request the original video from our backend or object storage.</p><p>Instead:</p><pre>                    Object Storage<br>                          │<br>                          ▼<br>                         CDN<br>                    /     |     \<br>                   /      |      \<br>                Edge A  Edge B  Edge C<br>                  │       │       │<br>                Users   Users   Users</pre><p>The CDN caches video segments at edge locations closer to users.</p><h3>18. CDN Cache Hit</h3><p>Suppose a user requests:</p><pre>segment-100</pre><p>If the CDN already has it:</p><pre>User<br>  │<br>  ▼<br> CDN<br>  │<br>  └── Cache HIT<br>        │<br>        ▼<br>       User</pre><p>No request needs to reach the origin.</p><p>If it isn’t cached:</p><pre>User<br>  │<br>  ▼<br> CDN<br>  │<br>  └── Cache MISS<br>        │<br>        ▼<br> Object Storage<br>        │<br>        ▼<br>      CDN<br>        │<br>        ▼<br>      User</pre><p>The CDN can then cache that segment for subsequent users.</p><h3>19. Playback Flow</h3><p>Now let’s put everything together.</p><p>When a user opens a video:</p><pre>Client<br>  │<br>  │ GET /videos/{videoId}<br>  ▼<br>Video API<br>  │<br>  ▼<br>Metadata DB</pre><p>The API returns information such as:</p><pre>{<br>    &quot;videoId&quot;: &quot;v123&quot;,<br>    &quot;title&quot;: &quot;My Trip&quot;,<br>    &quot;duration&quot;: 600,<br>    &quot;manifestUrl&quot;: &quot;...&quot;<br>}</pre><p>The player then retrieves the manifest and starts requesting video segments through the CDN.</p><pre>Client<br>   │<br>   ▼<br>Manifest<br>   │<br>   ▼<br>CDN<br>   │<br>   ├── Segment 1<br>   ├── Segment 2<br>   ├── Segment 3<br>   └── Segment 4</pre><h3>20. Metadata Database</h3><p>We don’t need to put video bytes into our database.</p><p>The database stores metadata:</p><pre>Video<br>----------------<br>videoId<br>userId<br>title<br>description<br>duration<br>thumbnailUrl<br>manifestUrl<br>status<br>createdAt</pre><p>For example:</p><pre>videoId: v123<br>title: My Trip<br>status: READY<br>duration: 600</pre><p>A horizontally scalable database can partition records using videoId.</p><h3>21. Complete Architecture</h3><p>Here’s the complete high-level design:</p><pre>                         ┌──────────────┐<br>                         │    CLIENT    │<br>                         └──────┬───────┘<br>                                │<br>                  ┌─────────────┴─────────────┐<br>                  │                           │<br>                UPLOAD                      WATCH<br>                  │                           │<br>                  ▼                           ▼<br>           ┌─────────────┐             ┌─────────────┐<br>           │ Video API   │             │ Video API   │<br>           └──────┬──────┘             └──────┬──────┘<br>                  │                           │<br>           Pre-signed URL                Metadata DB<br>                  │                           │<br>                  ▼                           │<br>             ┌─────────┐                      │<br>             │ Object  │                      │<br>             │ Storage │                      │<br>             └────┬────┘                      │<br>                  │                           │<br>             Upload Event                     │<br>                  │                           │<br>                  ▼                           │<br>             ┌─────────┐                      │<br>             │  Queue  │                      │<br>             └────┬────┘                      │<br>                  │                           │<br>                  ▼                           │<br>        ┌──────────────────┐                  │<br>        │ Video Processing │                  │<br>        │     Workers      │                  │<br>        └────────┬─────────┘                  │<br>                 │                            │<br>                 ▼                            │<br>          ┌───────────────┐                   │<br>          │ Segments +    │                   │<br>          │ Manifests     │                   │<br>          └───────┬───────┘                   │<br>                  │                           │<br>                  └────────────┬──────────────┘<br>                               ▼<br>                           ┌───────┐<br>                           │  CDN  │<br>                           └───┬───┘<br>                               │<br>                               ▼<br>                            CLIENT</pre><h3>22. Handling Viral Videos</h3><p>A common interviewer question is:</p><blockquote><em>“What happens if one video suddenly gets 10 million views?”</em></blockquote><p>The main problem is a <strong>hot object</strong>.</p><p>Without caching:</p><pre>10M users<br>    ↓<br>Origin</pre><p>With CDN:</p><pre>10M users<br>    ↓<br>   CDN<br>    ↓<br>Cached video segments</pre><p>The CDN absorbs most of the read traffic.</p><p>We can also cache frequently requested metadata using a distributed cache such as Redis.</p><h3>23. Scaling the System</h3><p>Each layer can scale independently.</p><h3>API Servers</h3><p>Make them stateless:</p><pre>Load Balancer<br>   │<br>   ├── API 1<br>   ├── API 2<br>   ├── API 3<br>   └── API N</pre><h3>Processing Workers</h3><pre>Queue<br> │<br> ├── Worker 1<br> ├── Worker 2<br> ├── Worker 3<br> └── Worker N</pre><p>Add more workers as the queue grows.</p><h3>Metadata Database</h3><p>Use:</p><ul><li>Replication</li><li>Partitioning/sharding</li><li>Read replicas where appropriate</li></ul><h3>Video Storage</h3><p>Use scalable object storage.</p><h3>Video Delivery</h3><p>Use a global CDN.</p><h3>24. Basic Capacity Estimation</h3><p>Let’s assume:</p><pre>1 million uploads/day<br>100 million video watches/day</pre><h3>Upload QPS</h3><pre>1,000,000 / 86,400<br>≈ 12 uploads/sec</pre><p>Average upload rate is approximately:</p><p><strong>12 uploads/sec</strong></p><p>If we assume a 10× peak:</p><pre>≈ 120 uploads/sec</pre><h3>Watch QPS</h3><pre>100,000,000 / 86,400<br>≈ 1,157 watches/sec</pre><p>At 10× peak:</p><pre>≈ 11,570 watches/sec</pre><p>The important observation is:</p><blockquote><strong><em>The system is heavily read-oriented.</em></strong></blockquote><p>Therefore, CDN caching and efficient video delivery are critical.</p><h3>25. Storage Estimation</h3><p>Suppose the average uploaded video is:</p><pre>500 MB</pre><p>With:</p><pre>1 million uploads/day</pre><p>We get:</p><pre>1,000,000 × 500 MB<br>≈ 500 TB/day</pre><p>And this is only the original videos.</p><p>After transcoding, additional storage is required for:</p><ul><li>Multiple resolutions</li><li>Different bitrates</li><li>Audio</li><li>Segments</li><li>Thumbnails</li><li>Manifests</li></ul><p>This demonstrates why object storage is essential.</p><h3>26. What Happens If Transcoding Fails?</h3><p>Suppose:</p><pre>Upload<br>  ↓<br>Queue<br>  ↓<br>Worker<br>  ↓<br>Transcoding FAILED</pre><p>We shouldn’t lose the video.</p><p>The original remains in object storage.</p><p>We can:</p><pre>Retry Job<br>   ↓<br>Another Worker<br>   ↓<br>Process Again</pre><p>For repeatedly failing jobs, we can use a dead-letter queue for investigation.</p><h3>27. Search</h3><p>Search can be added later.</p><p>Instead of querying the main database with:</p><pre>WHERE title LIKE &#39;%football%&#39;</pre><p>we can create a search pipeline:</p><pre>Video Metadata<br>      │<br>      ▼<br>Event Stream<br>      │<br>      ▼<br>Search Index<br>      │<br>      ▼<br>OpenSearch / Elasticsearch</pre><p>Then:</p><pre>GET /search?q=football</pre><p>queries the search index.</p><h3>28. Recommendations</h3><p>Recommendations are another large distributed system.</p><p>A simplified architecture could be:</p><pre>User Watch Events<br>       │<br>       ▼<br>Event Stream<br>       │<br>       ▼<br>Analytics / ML Pipeline<br>       │<br>       ▼<br>Recommendation Model<br>       │<br>       ▼<br>Recommendation Store<br>       │<br>       ▼<br>User</pre><p>We don’t need to include this in the core YouTube design unless the interviewer asks.</p><h3>29. View Count System</h3><p>Updating the database for every single view can create a hot row.</p><p>Instead of:</p><pre>Every View<br>   ↓<br>UPDATE video<br>SET views = views + 1</pre><p>we can use an event-based architecture:</p><pre>Views<br>  ↓<br>Event Stream<br>  ↓<br>Aggregation<br>  ↓<br>Counter Store</pre><p>Views can be aggregated in batches.</p><p>This improves scalability at the cost of some eventual consistency.</p><h3>30. Key Trade-offs</h3><h3>Consistency vs Availability</h3><p>Video playback should prioritize availability.</p><p>It’s better for a view count to be slightly delayed than for video playback to fail.</p><h3>Storage vs Cost</h3><p>Keeping multiple video resolutions increases storage cost but improves playback quality.</p><h3>Latency vs Cost</h3><p>More CDN edge caching improves latency but increases cache/storage cost.</p><h3>Processing Speed vs Cost</h3><p>More transcoding workers reduce processing time but increase compute cost.</p><h3>31. The Most Important Interview Concepts</h3><p>If you’re preparing for a system design interview, focus on these concepts:</p><h3>1. Object Storage</h3><p>Large video files belong in object storage.</p><h3>2. Pre-Signed URLs</h3><p>Allow clients to upload directly to object storage.</p><h3>3. Multipart Upload</h3><p>Makes large uploads resumable and efficient.</p><h3>4. Message Queues</h3><p>Decouple upload from video processing.</p><h3>5. Transcoding</h3><p>Create multiple video resolutions and bitrates.</p><h3>6. Video Segmentation</h3><p>Break videos into small chunks.</p><h3>7. Adaptive Bitrate Streaming</h3><p>Automatically switch quality based on network conditions.</p><h3>8. HLS / DASH</h3><p>Protocols/formats used to describe and deliver segmented streams.</p><h3>9. CDN</h3><p>Deliver video content close to users and reduce origin load.</p><h3>10. Horizontal Scaling</h3><p>Scale API servers, workers, databases, and delivery independently.</p><h3>32. The One Sentence You Should Remember</h3><p>If an interviewer asks:</p><blockquote><strong><em>“Design YouTube.”</em></strong></blockquote><p>A strong summary is:</p><blockquote><strong><em>“I would upload large videos directly to object storage using multipart pre-signed URLs, asynchronously process them through a distributed transcoding pipeline, generate multiple resolutions and small streaming segments with manifests, store those outputs in object storage, and distribute them globally through a CDN using adaptive bitrate streaming.”</em></strong></blockquote><p>That single sentence captures the heart of the design.</p><h3>33. Final Architecture to Remember</h3><pre>                        USER<br>                          │<br>                ┌─────────┴─────────┐<br>                │                   │<br>             UPLOAD                WATCH<br>                │                   │<br>                ▼                   ▼<br>           Video API            Video API<br>                │                   │<br>        Pre-signed URL         Metadata DB<br>                │                   │<br>                ▼                   │<br>          Object Storage             │<br>                │                   │<br>           Upload Event              │<br>                │                   │<br>                ▼                   │<br>              Queue                  │<br>                │                   │<br>                ▼                   │<br>       Transcoding Workers           │<br>                │                   │<br>                ▼                   │<br>        Segments + Manifest          │<br>                │                   │<br>                ▼                   │<br>          Object Storage             │<br>                │                   │<br>                └─────────┬─────────┘<br>                          ▼<br>                         CDN<br>                          │<br>                          ▼<br>                         USER</pre><h3>Conclusion</h3><p>Designing YouTube is not primarily about creating a complicated database.</p><p>The biggest challenge is handling <strong>massive video files and massive read traffic</strong> efficiently.</p><p>The core architecture is:</p><p><strong>Direct Upload → Object Storage → Async Processing → Transcoding → Segmentation → Manifest → CDN → Adaptive Streaming</strong></p><p>Once you understand these concepts, many large-scale media systems become easier to reason about.</p><p>The key lesson is:</p><blockquote><strong><em>Don’t make your application servers carry the video traffic. Let specialized infrastructure — object storage, processing workers, and CDNs — handle the heavy work.</em></strong></blockquote><p>That’s the foundation of a scalable YouTube-like architecture.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mr8KyV4PZkxHr5HLnnd1hg.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f9e4723c814a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[WhatsApp System Design: Designing a Scalable Real-Time Messaging System]]></title>
            <link>https://theena18.medium.com/whatsapp-system-design-designing-a-scalable-real-time-messaging-system-7fce55d5d2f9?source=rss-e6bb5de386b9------2</link>
            <guid isPermaLink="false">https://medium.com/p/7fce55d5d2f9</guid>
            <category><![CDATA[websocket]]></category>
            <category><![CDATA[design-whatsapp]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <dc:creator><![CDATA[Dinakaran]]></dc:creator>
            <pubDate>Wed, 23 Sep 2026 10:23:54 GMT</pubDate>
            <atom:updated>2026-09-23T10:23:54.614Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><strong><em>How would you design a messaging platform like WhatsApp for millions of concurrent users?</em></strong></blockquote><p>Messaging looks simple from the outside.</p><p>You type:</p><blockquote><em>“Hey!”</em></blockquote><p>You press send.</p><p>The message appears almost instantly on your friend’s phone.</p><p>But behind that simple experience lies a distributed system dealing with <strong>millions of persistent connections, message delivery, offline users, retries, ordering, multi-device synchronization, media storage, encryption, and failures</strong>.</p><p>In this article, we’ll design a simplified WhatsApp-like system from scratch and gradually evolve it into a scalable distributed architecture.</p><h3>1. What Are We Building?</h3><p>Our system should allow users to:</p><ul><li>Send and receive text messages</li><li>Create one-to-one conversations</li><li>Create group conversations</li><li>Receive messages in real time</li><li>Receive messages after being offline</li><li>Send images, videos, and documents</li><li>Use multiple devices</li><li>Maintain reliable message delivery</li><li>Protect message contents with end-to-end encryption</li></ul><p>We won’t initially design voice/video calling, payments, status, or business features.</p><h3>2. Functional Requirements</h3><p>Let’s define the core requirements.</p><h3>Users</h3><p>A user should be able to:</p><ul><li>Register</li><li>Log in</li><li>Manage devices</li></ul><h3>Messaging</h3><p>Users should be able to:</p><ul><li>Send messages</li><li>Receive messages</li><li>View conversation history</li><li>See delivery status</li><li>See read status</li></ul><h3>Groups</h3><p>Users should be able to:</p><ul><li>Create groups</li><li>Add/remove members</li><li>Send messages to groups</li></ul><h3>Offline messaging</h3><p>If the recipient is offline:</p><pre>Sender<br>   ↓<br>Server<br>   ↓<br>Durable Storage<br>   ↓<br>Recipient comes online<br>   ↓<br>Message delivered</pre><h3>Media</h3><p>Users should be able to send:</p><ul><li>Images</li><li>Videos</li><li>Documents</li></ul><h3>3. Non-Functional Requirements</h3><p>The system should provide:</p><h3>Low latency</h3><p>Messages between online users should be delivered with very low latency.</p><h3>High availability</h3><p>A single server failure shouldn’t bring down the entire system.</p><h3>Scalability</h3><p>The system should support:</p><ul><li>Millions of users</li><li>Millions of concurrent connections</li><li>Large message volumes</li></ul><h3>Reliability</h3><p>Messages shouldn’t disappear just because a network connection fails.</p><h3>Durability</h3><p>Messages for offline users should remain available until successful delivery.</p><h3>Security</h3><p>Message contents should be protected using end-to-end encryption.</p><h3>4. High-Level Architecture</h3><p>Let’s start with the basic architecture.</p><pre>                    ┌──────────────┐<br>                    │   Clients    │<br>                    │ Phone / Web  │<br>                    └──────┬───────┘<br>                           │<br>                       WebSocket<br>                           │<br>                           ▼<br>                  ┌─────────────────┐<br>                  │  Load Balancer  │<br>                  └────────┬────────┘<br>                           │<br>             ┌─────────────┼─────────────┐<br>             ▼             ▼             ▼<br>        Chat Server 1  Chat Server 2  Chat Server 3<br>             │             │             │<br>             └─────────────┼─────────────┘<br>                           ▼<br>                      Pub/Sub Layer<br>                           │<br>                ┌──────────┴──────────┐<br>                ▼                     ▼<br>          Message Store            Inbox<br>                │<br>                ▼<br>          Chat Metadata<br></pre><pre>Media:</pre><pre>Client ───────→ Object Storage ───────→ CDN</pre><p>Now let’s understand each component.</p><h3>5. Why WebSocket?</h3><p>A chat application needs <strong>real-time bidirectional communication</strong>.</p><p>With normal HTTP:</p><pre>Client → Server<br>        ↓<br>      response</pre><p>The server cannot simply push a new message whenever it wants.</p><p>We could use polling:</p><pre>Client → &quot;Any new messages?&quot;<br>Client → &quot;Any new messages?&quot;<br>Client → &quot;Any new messages?&quot;<br>Client → &quot;Any new messages?&quot;</pre><p>This creates unnecessary traffic.</p><p>Instead, we use WebSocket.</p><pre>Client ═════════════ Server<br>       persistent<br>       connection</pre><p>Once the connection is established, both sides can communicate over the same connection.</p><p>For chat:</p><pre>Sender<br>   │<br>   │ message<br>   ▼<br>Server<br>   │<br>   │ push<br>   ▼<br>Receiver</pre><p>This provides the low-latency communication we need.</p><h3>6. Sending a Message</h3><p>Suppose Alice sends:</p><pre>&quot;Hello Bob&quot;</pre><p>The flow is:</p><pre>Alice<br>  │<br>  │ WebSocket<br>  ▼<br>Chat Server<br>  │<br>  ├── Store message<br>  │<br>  ├── Update inbox<br>  │<br>  └── Publish event<br>           │<br>           ▼<br>        Pub/Sub<br>           │<br>           ▼<br>      Bob&#39;s Server<br>           │<br>           │ WebSocket<br>           ▼<br>          Bob</pre><p>Let’s break this down.</p><h3>7. Step 1 — Client Sends Message</h3><p>Alice’s client creates a message:</p><pre>{<br>  &quot;messageId&quot;: &quot;M123&quot;,<br>  &quot;chatId&quot;: &quot;C100&quot;,<br>  &quot;senderId&quot;: &quot;Alice&quot;,<br>  &quot;content&quot;: &quot;...&quot;,<br>  &quot;timestamp&quot;: 1727000000<br>}</pre><p>In a production E2EE system, the actual content sent to the server is encrypted rather than plaintext.</p><p>The client sends it through the WebSocket connection.</p><h3>8. Step 2 — Authenticate and Validate</h3><p>The Chat Server verifies:</p><ul><li>Is Alice authenticated?</li><li>Is Alice a member of the chat?</li><li>Is the request valid?</li><li>Is the message format valid?</li></ul><p>If valid, the server accepts the message.</p><h3>9. Step 3 — Generate a Unique Message ID</h3><p>Every message needs a unique identifier.</p><p>For example:</p><pre>M123</pre><p>This is important for:</p><ul><li>ACKs</li><li>Retries</li><li>Deduplication</li><li>Synchronization</li><li>Debugging</li></ul><p>Suppose the same message is delivered twice:</p><pre>M123<br>M123</pre><p>The client can recognize that both are the same logical message.</p><h3>10. Step 4 — Persist the Message</h3><p>This is one of the most important design decisions.</p><p>We should <strong>persist before relying on real-time delivery</strong>.</p><pre>Client<br>  ↓<br>Chat Server<br>  ↓<br>Message Store<br>  ↓<br>Pub/Sub<br>  ↓<br>Recipient</pre><p>Why?</p><p>Because WebSocket delivery isn’t durable.</p><p>The connection could fail at any moment.</p><p>If the message has already been stored, we can recover.</p><h3>11. Message Store vs Inbox</h3><p>These are two different concepts.</p><h3>Message Store</h3><p>Contains the actual message.</p><pre>Message Store</pre><pre>M123<br> ├── chatId<br> ├── senderId<br> ├── timestamp<br> └── encryptedPayload</pre><h3>Inbox</h3><p>Tracks messages that still need to be delivered.</p><pre>Bob&#39;s Inbox</pre><pre>M123<br>M124<br>M125</pre><p>Think of the Inbox as:</p><blockquote><strong><em>A durable pending-delivery queue.</em></strong></blockquote><h3>12. What If Bob Is Offline?</h3><p>This is one of the most important parts of the design.</p><p>Suppose:</p><pre>Alice<br>  │<br>  ▼<br>Server<br>  │<br>  ▼<br>Bob ❌ Offline</pre><p>We can’t deliver the message immediately.</p><p>Instead:</p><pre>Message Store<br>      │<br>      └────→ Bob&#39;s Inbox</pre><p>The message remains pending.</p><p>Later:</p><pre>Bob comes online<br>       │<br>       ▼<br>WebSocket connection<br>       │<br>       ▼<br>Chat Server<br>       │<br>       ▼<br>Bob&#39;s Inbox<br>       │<br>       ▼<br>M123<br>       │<br>       ▼<br>Bob</pre><p>After Bob acknowledges the message, the pending delivery state can be cleared.</p><p>This gives us reliable offline messaging.</p><h3>13. Why Do We Need Pub/Sub?</h3><p>Now imagine we have multiple Chat Servers.</p><pre>Alice → Server 1</pre><pre>Bob → Server 3</pre><p>Alice sends a message.</p><p>Server 1 receives it.</p><p>But Bob’s WebSocket connection exists on Server 3.</p><p>How does Server 1 tell Server 3?</p><p>We introduce a Pub/Sub layer.</p><pre>Server 1<br>   │<br>   │ publish<br>   ▼<br> Pub/Sub<br>   │<br>   ▼<br>Server 3<br>   │<br>   ▼<br> Bob</pre><p>This allows our Chat Servers to communicate without tightly coupling them together.</p><h3>14. Why Not Send the Message to Every Server?</h3><p>Suppose we have:</p><pre>1,000 Chat Servers</pre><p>We don’t want:</p><pre>Server 1<br> ├──→ Server 2<br> ├──→ Server 3<br> ├──→ Server 4<br> ├──→ ...<br> └──→ Server 1000</pre><p>That creates unnecessary network traffic.</p><p>Instead, the system determines which server currently owns Bob’s connection and routes the event there.</p><h3>15. Redis Pub/Sub</h3><p>For an interview architecture, Redis Pub/Sub is a simple example.</p><p>Conceptually:</p><pre>user:bob</pre><p>could represent Bob’s delivery channel.</p><p>Bob’s Chat Server subscribes to the relevant channel.</p><p>Then:</p><pre>Alice<br>  ↓<br>Server 1<br>  ↓<br>Redis Pub/Sub<br>  ↓<br>Server 3<br>  ↓<br>Bob</pre><p>However, there is an important distinction:</p><blockquote><strong><em>Pub/Sub is not the source of truth.</em></strong></blockquote><p>It is a real-time transport mechanism.</p><p>The durable Message Store and Inbox are what allow recovery when Pub/Sub or a connection fails.</p><h3>16. What If Pub/Sub Fails?</h3><p>Suppose:</p><pre>Message Store     ✅<br>Inbox             ✅<br>Pub/Sub           ❌</pre><p>We haven’t lost the message.</p><p>Bob may not receive it immediately, but the pending delivery state remains.</p><p>When Bob reconnects:</p><pre>Bob<br> ↓<br>Reconnect<br> ↓<br>Sync Inbox<br> ↓<br>M123<br> ↓<br>ACK</pre><p>This is why durable storage is more important than the real-time transport layer.</p><h3>17. Message Acknowledgement</h3><p>After Bob receives the message:</p><pre>Server ───── Message ─────→ Bob<br>Server ←──── ACK ────────── Bob</pre><p>The ACK tells the server:</p><blockquote><em>“Bob’s device successfully received this message.”</em></blockquote><p>The system can then mark the message as delivered.</p><p>This leads to delivery states such as:</p><pre>SENT<br>  ↓<br>DELIVERED<br>  ↓<br>READ</pre><h3>18. What If the ACK Is Lost?</h3><p>This is a classic distributed-systems problem.</p><pre>Server ───── M123 ─────→ Bob<br>                           │<br>                         received<br>                           │<br>Server ←──── ACK ───────── X<br>                       lost</pre><p>The server doesn’t know Bob received it.</p><p>So it may retry:</p><pre>Server ───── M123 ─────→ Bob</pre><p>Now Bob receives the same message again.</p><p>This is why we need unique message IDs.</p><p>Bob checks:</p><pre>Is M123 already processed?</pre><pre>YES → Ignore duplicate<br>NO  → Process message</pre><p>Therefore:</p><blockquote><strong><em>At-least-once delivery + idempotent processing = reliable delivery.</em></strong></blockquote><h3>19. At-Least-Once Delivery</h3><p>In distributed systems, trying to guarantee exactly-once delivery everywhere can be complicated and expensive.</p><p>A practical approach is:</p><pre>At-least-once delivery<br>        +<br>Unique message ID<br>        +<br>Deduplication</pre><p>If the network retries:</p><pre>M123<br>M123<br>M123</pre><p>the recipient still processes:</p><pre>M123</pre><p>only once logically.</p><h3>20. Handling Message Ordering</h3><p>Suppose Alice sends:</p><pre>Message 1<br>Message 2<br>Message 3</pre><p>The network might deliver:</p><pre>Message 1<br>Message 3<br>Message 2</pre><p>To detect this, messages can have sequence numbers.</p><pre>M1 → seq 101<br>M2 → seq 102<br>M3 → seq 103</pre><p>If the client receives:</p><pre>101<br>103</pre><p>it knows:</p><pre>102 is missing</pre><p>and can synchronize with the server.</p><p>We generally don’t need global ordering across every message in the entire system. Ordering requirements are usually scoped to a conversation or message stream.</p><h3>21. Scaling WebSocket Connections</h3><p>A single Chat Server can’t maintain connections for millions of users.</p><p>We horizontally scale:</p><pre>                    Load Balancer<br>                         │<br>            ┌────────────┼────────────┐<br>            ▼            ▼            ▼<br>        Server 1      Server 2      Server 3</pre><p>When one server reaches its connection capacity, new connections can be routed to other servers.</p><p>The servers should avoid storing critical persistent state locally.</p><p>Persistent state belongs in distributed storage.</p><h3>22. User-to-Server Routing</h3><p>We need to know:</p><blockquote><em>“Which Chat Server currently holds Bob’s WebSocket?”</em></blockquote><p>There are multiple ways to solve this.</p><p>One approach is maintaining connection ownership information:</p><pre>User       Server<br>-------------------<br>Alice      Server 1<br>Bob        Server 3<br>Charlie    Server 2</pre><p>Another approach is consistent hashing:</p><pre>hash(userId) → server</pre><p>The exact strategy depends on the infrastructure and how connection ownership is managed.</p><p>The key requirement is:</p><blockquote><strong><em>Given a recipient, efficiently locate the server holding their active connection.</em></strong></blockquote><h3>23. Handling User Presence</h3><p>We also need to know:</p><pre>Online<br>Offline<br>Last seen</pre><p>The WebSocket connection provides the primary signal.</p><pre>WebSocket connected<br>        ↓<br>      ONLINE</pre><p>When it disconnects:</p><pre>WebSocket disconnected<br>        ↓<br>      OFFLINE</pre><p>We shouldn’t write to the database on every heartbeat because that could create enormous write traffic.</p><p>Instead, presence can be maintained using an in-memory or distributed presence layer, while durable storage is reserved for meaningful state changes.</p><h3>24. Heartbeats</h3><p>Connections can silently fail.</p><p>Therefore, we use heartbeats.</p><pre>Server ───── ping ─────→ Client<br>Server ←──── pong ────── Client</pre><p>If the client doesn’t respond for a configured period:</p><pre>No pong<br>  ↓<br>Connection considered dead<br>  ↓<br>Clean up connection state</pre><p>The client can then reconnect.</p><h3>25. Multi-Device Support</h3><p>Modern messaging systems need to support:</p><pre>User<br> ├── Phone<br> ├── Laptop<br> ├── Tablet<br> └── Desktop</pre><p>Each device may have its own connection.</p><p>Therefore, delivery and synchronization need to consider the device level.</p><pre>User<br> │<br> ├── Device 1<br> │     └── WebSocket<br> │<br> ├── Device 2<br> │     └── WebSocket<br> │<br> └── Device 3<br>       └── WebSocket</pre><p>Modern WhatsApp’s multi-device architecture allows companion devices to operate independently instead of requiring the primary phone to relay every operation.</p><h3>26. End-to-End Encryption</h3><p>Security is fundamental to a messaging system.</p><p>The desired model is:</p><pre>Sender<br>  │<br>  │ Encrypt<br>  ▼<br>Ciphertext<br>  │<br>  ▼<br>WhatsApp Servers<br>  │<br>  │ Route/store ciphertext<br>  ▼<br>Recipient<br>  │<br>  │ Decrypt<br>  ▼<br>Plaintext</pre><p>The server doesn’t need the plaintext to route the message.</p><p>WhatsApp uses the Signal Protocol family of cryptographic mechanisms for end-to-end encrypted messaging.</p><h3>27. Group Encryption</h3><p>One-to-one encryption is relatively straightforward conceptually:</p><pre>Alice ↔ Bob</pre><p>Groups are more complicated:</p><pre>Group<br> ├── Alice<br> ├── Bob<br> ├── Charlie<br> └── David</pre><p>Encrypting independently for every participant can become expensive.</p><p>WhatsApp uses mechanisms including <strong>Sender Keys</strong> to make group end-to-end encryption more scalable.</p><p>For system-design interviews, the important point is:</p><blockquote><strong><em>Group messaging requires an encryption strategy that scales with group membership and multiple devices.</em></strong></blockquote><h3>28. Handling Images and Videos</h3><p>We shouldn’t send a 50 MB video through our Chat Server.</p><p>Instead:</p><pre>Client<br>  │<br>  │ request upload URL<br>  ▼<br>Media Service<br>  │<br>  │ pre-signed URL<br>  ▼<br>Client<br>  │<br>  │ direct upload<br>  ▼<br>Object Storage</pre><p>Then the chat message contains metadata such as:</p><pre>mediaId<br>mediaType<br>size<br>encryption metadata</pre><p>rather than the entire file.</p><h3>29. Why Object Storage?</h3><p>Object storage is optimized for large blobs.</p><p>Examples include:</p><ul><li>Amazon S3</li><li>Google Cloud Storage</li><li>Azure Blob Storage</li></ul><p>The architecture becomes:</p><pre>Client<br>   │<br>   ├──────────────→ Object Storage<br>   │<br>   │<br>   └──────────────→ Chat Server<br>                     │<br>                     ▼<br>                  Message</pre><p>The Chat Server doesn’t become a media bandwidth bottleneck.</p><h3>30. Why Use a CDN?</h3><p>Suppose a popular image is downloaded by thousands of users.</p><p>Without a CDN:</p><pre>Users<br>  ↓<br>Object Storage</pre><p>With a CDN:</p><pre>Users<br>  ↓<br>CDN Edge<br>  ↓<br>Object Storage</pre><p>The CDN can serve cached content from locations closer to users.</p><p>This reduces:</p><ul><li>latency</li><li>origin traffic</li><li>bandwidth pressure</li></ul><h3>31. Database Design</h3><p>We can start with entities such as:</p><h3>User</h3><pre>User<br>----<br>userId<br>phoneNumber<br>name<br>createdAt</pre><h3>Chat</h3><pre>Chat<br>----<br>chatId<br>type<br>createdAt</pre><h3>Participant</h3><pre>ChatParticipant<br>---------------<br>chatId<br>userId<br>joinedAt</pre><h3>Message</h3><pre>Message<br>-------<br>messageId<br>chatId<br>senderId<br>sequenceNumber<br>timestamp<br>encryptedPayload</pre><h3>Device</h3><pre>Device<br>------<br>deviceId<br>userId<br>deviceType<br>lastSeen</pre><h3>Inbox</h3><pre>Inbox<br>-----<br>userId<br>deviceId<br>messageId<br>createdAt</pre><h3>32. Database Choice</h3><p>At massive scale, a distributed NoSQL database can be a good fit for message storage.</p><p>Possible choices:</p><pre>DynamoDB<br>Cassandra<br>ScyllaDB</pre><p>The important part isn’t the brand.</p><p>The important requirements are:</p><ul><li>Horizontal scalability</li><li>High write throughput</li><li>Partitioning</li><li>Replication</li><li>High availability</li><li>Predictable key-based access</li></ul><h3>33. Message Partitioning</h3><p>Suppose we have billions of messages.</p><p>We can’t keep them in one database partition.</p><p>A simple strategy is:</p><pre>partitionKey = chatId</pre><p>Then:</p><pre>Chat A → Partition 1<br>Chat B → Partition 2<br>Chat C → Partition 3</pre><p>For very high-volume chats, we may introduce time buckets:</p><pre>chatId + day</pre><p>or another partitioning strategy to prevent hot partitions.</p><h3>34. Hot Partition Problem</h3><p>Suppose one conversation generates an enormous number of messages.</p><p>If every message goes to:</p><pre>chatId = C100</pre><p>the same partition could become overloaded.</p><p>This is called a <strong>hot partition</strong>.</p><p>Possible solutions include:</p><ul><li>Time-based partitioning</li><li>Hash-based sub-partitioning</li><li>Better distribution of write traffic</li><li>Special handling for very large groups</li></ul><h3>35. Group Message Fan-Out</h3><p>Suppose a group has:</p><pre>100 members</pre><p>Alice sends:</p><pre>&quot;Hello everyone&quot;</pre><p>We may need to deliver it to:</p><pre>Alice<br>Bob<br>Charlie<br>...</pre><p>This is called:</p><blockquote><strong><em>Fan-out</em></strong></blockquote><p>For smaller groups:</p><pre>Fan-out on write</pre><p>can work well.</p><p>For extremely large groups, we may need:</p><pre>Fan-out on read</pre><p>or a hybrid design to reduce write amplification.</p><h3>36. Fan-Out on Write</h3><p>The message is written to recipient delivery state immediately.</p><pre>Message<br>   │<br>   ├──→ User A Inbox<br>   ├──→ User B Inbox<br>   ├──→ User C Inbox<br>   └──→ User D Inbox</pre><h3>Advantage</h3><p>Fast reads.</p><h3>Disadvantage</h3><p>Many writes.</p><h3>37. Fan-Out on Read</h3><p>The message is stored once:</p><pre>Message<br>   ↓<br>Group Conversation</pre><p>When users read:</p><pre>User<br> ↓<br>Fetch messages</pre><h3>Advantage</h3><p>Fewer writes.</p><h3>Disadvantage</h3><p>More work during reads.</p><h3>38. Failure Handling</h3><p>A production messaging system must assume components will fail.</p><h3>Chat Server failure</h3><pre>Client<br>  ↓<br>Server 1 ❌<br>  ↓<br>Reconnect<br>  ↓<br>Server 2</pre><h3>Pub/Sub failure</h3><pre>Message DB ✅<br>Inbox ✅<br>Pub/Sub ❌</pre><pre>→ Message is still recoverable</pre><h3>Recipient offline</h3><pre>Inbox<br> ↓<br>Wait<br> ↓<br>Reconnect<br> ↓<br>Deliver</pre><h3>ACK lost</h3><pre>Retry<br> ↓<br>Duplicate detection</pre><h3>Network failure</h3><pre>Reconnect<br> ↓<br>Synchronize from last known position</pre><h3>39. The Complete Message Flow</h3><p>Let’s put everything together.</p><pre>                         Alice<br>                           │<br>                           │ WebSocket<br>                           ▼<br>                   ┌────────────────┐<br>                   │ Load Balancer  │<br>                   └───────┬────────┘<br>                           │<br>                           ▼<br>                    ┌─────────────┐<br>                    │ Chat Server │<br>                    └──────┬──────┘<br>                           │<br>                  ┌────────┴────────┐<br>                  │                 │<br>                  ▼                 ▼<br>            Message Store        Inbox<br>                  │<br>                  │<br>                  ▼<br>               Pub/Sub<br>                  │<br>                  ▼<br>            Bob&#39;s Server<br>                  │<br>                  │ WebSocket<br>                  ▼<br>                  Bob<br>                  │<br>                  │ ACK<br>                  ▼<br>             Delivery State</pre><p>The key principle is:</p><blockquote><strong><em>Durability first, real-time delivery second.</em></strong></blockquote><h3>40. Complete Architecture</h3><p>Our final architecture looks like this:</p><pre>                         ┌─────────────────────┐<br>                         │       Clients       │<br>                         │ Phone / Web / Tablet│<br>                         └──────────┬──────────┘<br>                                    │<br>                              WebSocket<br>                                    │<br>                                    ▼<br>                         ┌─────────────────────┐<br>                         │    Load Balancer    │<br>                         └──────────┬──────────┘<br>                                    │<br>                  ┌─────────────────┼─────────────────┐<br>                  │                 │                 │<br>                  ▼                 ▼                 ▼<br>           ┌────────────┐   ┌────────────┐   ┌────────────┐<br>           │ Chat Server│   │ Chat Server│   │ Chat Server│<br>           │     A      │   │     B      │   │     C      │<br>           └─────┬──────┘   └─────┬──────┘   └─────┬──────┘<br>                 │                │                │<br>                 └────────────────┼────────────────┘<br>                                  │<br>                                  ▼<br>                         ┌─────────────────┐<br>                         │     Pub/Sub     │<br>                         └─────────────────┘<br>                                  │<br>                   ┌──────────────┴──────────────┐<br>                   ▼                             ▼<br>          ┌─────────────────┐          ┌─────────────────┐<br>          │  Message Store  │          │      Inbox      │<br>          └─────────────────┘          └─────────────────┘<br>                   │<br>                   ▼<br>          ┌─────────────────┐<br>          │ Chat Metadata   │<br>          │ Participants    │<br>          └─────────────────┘<br></pre><pre>              MEDIA PIPELINE</pre><pre>Client ─────→ Media Service<br>                  │<br>                  ▼<br>            Object Storage<br>                  │<br>                  ▼<br>                 CDN<br></pre><pre>              SECURITY</pre><pre>Sender<br>  │<br>  │ Encrypt<br>  ▼<br>Ciphertext<br>  │<br>  ▼<br>Server<br>  │<br>  │ Route / Store<br>  ▼<br>Recipient<br>  │<br>  │ Decrypt<br>  ▼<br>Plaintext</pre><h3>41. Key Design Decisions</h3><p>Let’s summarize the important choices.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/571/1*r1ARbRukdfChmtrhRjthkw.png" /></figure><h3>42. The Most Important Mental Model</h3><p>If you remember only one diagram from this article, remember this:</p><pre>WHATSAPP</pre><pre>                     Client<br>                       │<br>                 WebSocket<br>                       │<br>                       ▼<br>                Load Balancer<br>                       │<br>          ┌────────────┼────────────┐<br>          ▼            ▼            ▼<br>       Chat 1        Chat 2        Chat 3<br>          │            │            │<br>          └────────────┼────────────┘<br>                       ▼<br>                    Pub/Sub<br>                       │<br>              ┌────────┴────────┐<br>              ▼                 ▼<br>        Message Store         Inbox<br>              │                 │<br>              └────────┬────────┘<br>                       │<br>                       ▼<br>                     Client<br></pre><pre>      Media → Object Storage → CDN</pre><pre>      Encrypt → Server → Decrypt</pre><p>The architecture can be remembered using five words:</p><blockquote><strong><em>Connect → Persist → Publish → Deliver → Acknowledge</em></strong></blockquote><pre>Connect<br>   ↓<br>Persist<br>   ↓<br>Publish<br>   ↓<br>Deliver<br>   ↓<br>Acknowledge</pre><p>That’s the core of a scalable messaging system.</p><h3>43. What I Learned From This System Design</h3><p>The interesting part of designing WhatsApp isn’t actually the chat UI.</p><p>It’s understanding how distributed systems behave when things go wrong.</p><p>A WebSocket connection can disappear.</p><p>A server can crash.</p><p>A Pub/Sub message can be lost.</p><p>An ACK can disappear.</p><p>A message can arrive twice.</p><p>A user can be offline for hours.</p><p>A device can reconnect from another network.</p><p>A database partition can become hot.</p><p>And yet the user expects:</p><blockquote><strong><em>“My message should still be there.”</em></strong></blockquote><p>That’s the real challenge of WhatsApp system design.</p><p>The solution is not a single technology.</p><p>It’s the combination of:</p><p><strong>WebSockets + Durable Storage + Inbox + Pub/Sub + ACKs + Retries + Idempotency + Partitioning + Object Storage + CDN + End-to-End Encryption.</strong></p><h3>Final Takeaway</h3><p>When designing a WhatsApp-like system, think in layers:</p><pre>Real-time<br>    ↓<br>WebSocket</pre><pre>Reliability<br>    ↓<br>ACK + Retry + Deduplication</pre><pre>Durability<br>    ↓<br>Message Store + Inbox</pre><pre>Scalability<br>    ↓<br>Horizontal Scaling + Partitioning</pre><pre>Distributed Routing<br>    ↓<br>Pub/Sub</pre><pre>Media<br>    ↓<br>Object Storage + CDN</pre><pre>Security<br>    ↓<br>End-to-End Encryption</pre><pre>Multi-device<br>    ↓<br>Device-level Synchronization</pre><p>Once you understand these building blocks, WhatsApp stops looking like one huge complicated application and starts looking like a collection of familiar distributed-system problems.</p><p>And that’s exactly what makes it such a valuable system-design interview question.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XIwXTFSouToKrXIQnv8U1A.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7fce55d5d2f9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Designing a Distributed Rate Limiter — System Design Case Study]]></title>
            <link>https://theena18.medium.com/designing-a-distributed-rate-limiter-system-design-case-study-d27b00a30313?source=rss-e6bb5de386b9------2</link>
            <guid isPermaLink="false">https://medium.com/p/d27b00a30313</guid>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[rate-limiting]]></category>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[distributed-rate-limiter]]></category>
            <dc:creator><![CDATA[Dinakaran]]></dc:creator>
            <pubDate>Wed, 23 Sep 2026 04:22:05 GMT</pubDate>
            <atom:updated>2026-09-23T04:22:05.521Z</atom:updated>
            <content:encoded><![CDATA[<p>Modern applications expose APIs to millions of users. Without protection, a single client can send thousands or even millions of requests and potentially overwhelm the backend.</p><p>A <strong>Rate Limiter</strong> solves this problem by controlling how frequently a client can access an API.</p><p>In this article, we’ll design a <strong>Distributed Rate Limiter</strong> that can operate at large scale while providing low-latency decisions.</p><h3>What Is a Rate Limiter?</h3><p>A rate limiter controls the number of requests a client can make within a specific period.</p><p>For example:</p><pre>100 requests / minute / user</pre><p>If a user sends 100 requests within the allowed limit:</p><pre>Request 1   → ALLOW<br>Request 2   → ALLOW<br>...<br>Request 100 → ALLOW</pre><p>But the next request is rejected:</p><pre>Request 101 → HTTP 429 Too Many Requests</pre><p>Rate limiting protects systems from:</p><ul><li>API abuse</li><li>Traffic spikes</li><li>Accidental infinite loops</li><li>Denial-of-service attacks</li><li>Resource exhaustion</li><li>Unfair resource consumption</li></ul><h3>1. Requirements</h3><p>Before designing the system, let’s define our requirements.</p><h3>Functional Requirements</h3><p>The system should:</p><ol><li>Identify the client.</li><li>Apply configurable rate limits.</li><li>Allow requests within the limit.</li><li>Reject requests exceeding the limit.</li><li>Return appropriate rate-limit information.</li><li>Support different limits for different clients or APIs.</li></ol><p>A client could be identified using:</p><pre>User ID<br>API Key<br>IP Address</pre><p>For example:</p><pre>user:123 → 100 requests/minute<br>user:456 → 500 requests/minute</pre><h3>Non-Functional Requirements</h3><p>Our system should provide:</p><ul><li>High availability</li><li>Low latency</li><li>Horizontal scalability</li><li>Shared state across multiple servers</li><li>Atomic rate-limit decisions</li><li>Efficient memory usage</li></ul><p>For our design, let’s assume:</p><pre>Peak traffic      → ~1M requests/second<br>Rate-limit latency → &lt;10 ms<br>High availability<br>Large number of clients</pre><p>The exact numbers can vary depending on the product.</p><h3>2. High-Level Architecture</h3><p>A simple architecture looks like this:</p><pre>                          Clients<br>                            │<br>                            ▼<br>                    ┌───────────────┐<br>                    │ Load Balancer │<br>                    └───────┬───────┘<br>                            │<br>                            ▼<br>                    ┌───────────────┐<br>                    │ API Gateway   │<br>                    │ Rate Limiter  │<br>                    └───────┬───────┘<br>                            │<br>                      Rate Limit Check<br>                            │<br>                            ▼<br>                    ┌───────────────┐<br>                    │     Redis     │<br>                    │    Cluster    │<br>                    └───────┬───────┘<br>                            │<br>                      Allow / Reject<br>                       /           \<br>                      /             \<br>                  Reject           Allow<br>                    │                │<br>                    ▼                ▼<br>              HTTP 429         Application Servers<br>                                    │<br>                                    ▼<br>                                Database</pre><p>The important design decision is:</p><blockquote><strong><em>Perform rate limiting at the API Gateway before requests reach the application servers.</em></strong></blockquote><p>This prevents rejected traffic from unnecessarily consuming backend resources.</p><h3>3. Choosing a Rate-Limiting Algorithm</h3><p>There are several popular algorithms.</p><h3>Fixed Window Counter</h3><p>Divide time into fixed intervals.</p><pre>10:00:00 ───────── 10:01:00</pre><p>Count requests inside each window.</p><p>Simple, but it has a boundary problem.</p><p>A client could send:</p><pre>5 requests at 10:00:59<br>5 requests at 10:01:00</pre><p>effectively sending 10 requests within a few seconds even though the limit is 5 requests/minute.</p><h3>Sliding Window Log</h3><p>Store the timestamp of every request.</p><pre>[10:00:10]<br>[10:00:20]<br>[10:00:30]<br>[10:00:40]</pre><p>This is accurate, but storing every request timestamp can consume significant memory at very high traffic.</p><h3>Sliding Window Counter</h3><p>Maintain counters for the current and previous windows and estimate the number of requests in the current sliding period.</p><p>It provides a good balance between accuracy and memory usage.</p><h3>Token Bucket</h3><p>The Token Bucket algorithm models a bucket containing tokens.</p><p>For example:</p><pre>Bucket capacity = 10<br>Refill rate     = 2 tokens/sec</pre><p>Every request consumes one token.</p><pre>Request<br>   │<br>   ▼<br>Consume 1 token<br>   │<br>   ├── Token available → ALLOW<br>   │<br>   └── No token         → REJECT</pre><p>Tokens are continuously replenished.</p><h3>4. Why Token Bucket?</h3><p>Token Bucket is a strong choice for a distributed API rate limiter because it supports both:</p><h3>Sustained traffic</h3><p>The refill rate controls how quickly requests can continue.</p><pre>Refill rate = 10 tokens/sec</pre><p>Approximately 10 requests per second can be sustained.</p><h3>Bursty traffic</h3><p>The bucket capacity determines how many requests can be handled as a burst.</p><pre>Bucket capacity = 100</pre><p>A client can consume up to 100 available tokens immediately when the bucket is full.</p><p>So:</p><pre>Refill rate    → sustained traffic<br>Bucket capacity → burst capacity</pre><p>This makes Token Bucket particularly useful for APIs where short traffic bursts are acceptable.</p><h3>5. How Token Bucket Works</h3><p>Suppose we have:</p><pre>Bucket capacity = 10<br>Refill rate     = 2 tokens/sec</pre><p>Initially:</p><pre>Tokens = 10</pre><p>The client sends five requests:</p><pre>10 → 9 → 8 → 7 → 6 → 5</pre><p>Five tokens remain.</p><p>If the client sends five more:</p><pre>5 → 4 → 3 → 2 → 1 → 0</pre><p>The next request is rejected:</p><pre>0 tokens</pre><pre>Request → HTTP 429</pre><p>After one second:</p><pre>0 + 2 = 2 tokens</pre><p>Two requests can now proceed.</p><h3>6. Token Bucket Formula</h3><p>We don’t need a background process constantly adding tokens.</p><p>Instead, we calculate the tokens when a request arrives.</p><p>We maintain:</p><pre>tokens<br>last_refill_time</pre><p>When a request arrives:</p><pre>elapsed_time =<br>current_time - last_refill_time</pre><p>Then:</p><pre>new_tokens =<br>elapsed_time × refill_rate</pre><p>And:</p><pre>tokens =<br>min(bucket_capacity,<br>    tokens + new_tokens)</pre><p>Then:</p><pre>if tokens &gt;= 1:<br>    tokens -= 1<br>    ALLOW<br>else:<br>    REJECT</pre><p>This makes the algorithm memory efficient.</p><h3>7. Why Redis?</h3><p>Now we have another problem.</p><p>Imagine we have three API Gateway instances:</p><pre>              API Gateway<br>             /     |     \<br>            /      |      \<br>        Server A Server B Server C</pre><p>If each server stores its own rate-limit counter:</p><pre>Server A → user123 = 40<br>Server B → user123 = 30<br>Server C → user123 = 30</pre><p>There is no shared global state.</p><p>The user could potentially bypass the intended limit simply because requests are distributed across multiple servers.</p><p>We therefore need a <strong>shared state store</strong>.</p><p>Redis is a good fit because rate limiting requires:</p><ul><li>Very low latency</li><li>High throughput</li><li>Atomic operations</li><li>Temporary state</li><li>TTL support</li><li>Horizontal scaling</li></ul><p>Our architecture becomes:</p><pre>Gateway A ──┐<br>Gateway B ──┼──► Redis<br>Gateway C ──┘</pre><p>All gateway instances access the same rate-limit state.</p><h3>8. Redis Data Model</h3><p>For every client, we can maintain a small state object.</p><p>For example:</p><pre>rate_limit:user:123</pre><p>Containing:</p><pre>tokens          = 82<br>last_refill     = 1727000000</pre><p>We can also configure a TTL so inactive clients don’t consume Redis memory forever.</p><p>For example:</p><pre>TTL = 1 hour</pre><p>If a client becomes inactive, Redis eventually removes its rate-limit state.</p><h3>9. The Race Condition Problem</h3><p>This is one of the most important distributed-system concepts in this design.</p><p>Suppose only <strong>one token</strong> remains.</p><pre>tokens = 1</pre><p>Two requests arrive simultaneously:</p><pre>Request A<br>Request B</pre><p>Both gateway instances might read:</p><pre>tokens = 1</pre><p>Then both might conclude:</p><pre>1 token available → ALLOW</pre><p>Now two requests have consumed one token.</p><p>That’s incorrect.</p><p>This is a classic <strong>race condition</strong>.</p><h3>10. Atomic Operations</h3><p>We need these operations to happen as one atomic operation:</p><pre>1. Read current state<br>2. Calculate refill<br>3. Check token availability<br>4. Decrement token<br>5. Update timestamp</pre><p>Redis Lua scripts are a good solution.</p><p>Conceptually:</p><pre>if tokens &gt;= 1:<br>    tokens = tokens - 1<br>    return ALLOW<br>else:<br>    return REJECT</pre><p>Because the logic executes atomically in Redis, another request cannot modify the same bucket halfway through the operation.</p><p>This is critical for correctness.</p><h3>11. Complete Request Flow</h3><p>Let’s follow a request from beginning to end.</p><h3>Step 1 — Client sends request</h3><pre>GET /api/products<br>Authorization: Bearer &lt;token&gt;</pre><p>The client identity could be:</p><pre>userId = 123</pre><h3>Step 2 — Load Balancer</h3><p>The load balancer routes the request to an API Gateway instance.</p><pre>Client<br>   │<br>   ▼<br>Load Balancer<br>   │<br>   ▼<br>API Gateway</pre><h3>Step 3 — Identify the client</h3><p>The gateway extracts:</p><pre>userId = 123</pre><p>and constructs a Redis key:</p><pre>rate_limit:user:123</pre><h3>Step 4 — Check Redis</h3><p>The gateway executes the token-bucket logic.</p><p>Redis:</p><pre>tokens = 82<br>last_refill = ...</pre><p>It calculates any newly available tokens.</p><h3>Step 5 — Atomic decision</h3><p>If a token is available:</p><pre>tokens = 81</pre><pre>→ ALLOW</pre><p>Otherwise:</p><pre>tokens = 0</pre><pre>→ REJECT</pre><h3>12. Allowed Request</h3><p>If the request is allowed:</p><pre>Client<br>   │<br>   ▼<br>Load Balancer<br>   │<br>   ▼<br>API Gateway<br>   │<br>   ├──────► Redis<br>   │          │<br>   │       ALLOW<br>   │          │<br>   ◄──────────┘<br>   │<br>   ▼<br>Application Server<br>   │<br>   ▼<br>Database</pre><p>The application processes the request normally.</p><h3>13. Rejected Request</h3><p>If no token is available:</p><pre>Client<br>   │<br>   ▼<br>Load Balancer<br>   │<br>   ▼<br>API Gateway<br>   │<br>   ▼<br>Redis<br>   │<br>   └── No token<br>          │<br>          ▼<br>       HTTP 429</pre><p>The request <strong>never reaches the application server</strong>.</p><p>This is important.</p><p>We reject the request as early as possible.</p><h3>14. HTTP 429 Response</h3><p>The server can return:</p><pre>HTTP/1.1 429 Too Many Requests</pre><pre>X-RateLimit-Limit: 100<br>X-RateLimit-Remaining: 0<br>Retry-After: 5</pre><p>The client now knows that it exceeded the allowed rate and can retry later.</p><h3>15. Scaling Redis</h3><p>At very high traffic, one Redis instance may not be enough.</p><p>For example:</p><pre>1M requests/sec</pre><p>We can use Redis Cluster:</p><pre>                  Redis Cluster<br>                /      |       \<br>               /       |        \<br>          Shard 1   Shard 2   Shard 3</pre><p>Client keys can be distributed using hashing:</p><pre>user:101 → Shard 1<br>user:102 → Shard 3<br>user:103 → Shard 2<br>user:104 → Shard 1</pre><p>This distributes the rate-limit workload across multiple Redis nodes.</p><h3>16. Hot Key Problem</h3><p>There is an interesting scaling problem.</p><p>Imagine a celebrity API key receives millions of requests.</p><p>All those requests may access:</p><pre>rate_limit:celebrity</pre><p>The same Redis key becomes extremely hot.</p><p>This is called the <strong>hot-key problem</strong>.</p><p>At very large scale, possible approaches include:</p><ul><li>Hierarchical rate limiting</li><li>Local approximate limits</li><li>Distributed/global limits</li><li>Specialized handling for extremely high-volume clients</li><li>Better traffic partitioning</li></ul><p>The exact solution depends on the application’s requirements.</p><p>For most interviews, it is enough to identify the problem and explain the trade-offs.</p><h3>17. What Happens If Redis Fails?</h3><p>This is another important design decision.</p><p>Suppose:</p><pre>API Gateway<br>      │<br>      X<br>    Redis</pre><p>is unavailable.</p><p>We have two major strategies.</p><h3>Fail Open</h3><pre>Redis unavailable<br>       ↓<br>Allow request</pre><p>Advantages:</p><ul><li>Better availability</li><li>Users can continue using the application</li></ul><p>Disadvantage:</p><ul><li>Backend may receive uncontrolled traffic</li></ul><h3>Fail Closed</h3><pre>Redis unavailable<br>       ↓<br>Reject request</pre><p>Advantages:</p><ul><li>Protects backend resources</li></ul><p>Disadvantage:</p><ul><li>Legitimate users may be blocked</li></ul><p>The correct choice depends on the application.</p><p>For a critical security-sensitive API, protecting the backend may be more important.</p><p>For a general consumer application, availability may be prioritized.</p><h3>18. Why Not Use a SQL Database?</h3><p>We could theoretically store counters in MySQL or PostgreSQL.</p><p>For example:</p><pre>UPDATE rate_limits<br>SET tokens = tokens - 1<br>WHERE user_id = 123;</pre><p>But rate limiting is a very high-frequency operation.</p><p>At millions of requests per second, putting this workload directly on a relational database would create significant contention and unnecessary database load.</p><p>Redis is better suited because the rate-limit state is:</p><pre>Small<br>Temporary<br>Frequently accessed<br>Frequently updated<br>Latency-sensitive</pre><h3>19. Why Put the Rate Limiter at the API Gateway?</h3><p>Consider:</p><pre>Client<br>   ↓<br>Application<br>   ↓<br>Rate Limiter</pre><p>The application server has already spent resources processing the request before discovering that it should be rejected.</p><p>Instead:</p><pre>Client<br>   ↓<br>API Gateway<br>   ↓<br>Rate Limiter<br>   ↓<br>Application</pre><p>Now rejected traffic stops at the edge.</p><p>This protects:</p><pre>Application servers<br>Databases<br>Internal services<br>Network resources</pre><h3>20. Supporting Different Limits</h3><p>A production system may need multiple limits.</p><p>For example:</p><pre>Per user:<br>100 requests/minute</pre><pre>Per IP:<br>1,000 requests/minute</pre><pre>Per API key:<br>10,000 requests/minute</pre><p>A request can pass through multiple checks:</p><pre>                Request<br>                   │<br>        ┌──────────┼──────────┐<br>        ▼          ▼          ▼<br>     User limit  IP limit  API limit<br>        │          │          │<br>        └──────────┼──────────┘<br>                   │<br>             All checks pass?<br>               /          \<br>             YES            NO<br>              │              │<br>            ALLOW           429</pre><p>This provides more control over traffic.</p><h3>21. Rate Limit vs Quota</h3><p>These concepts are often confused.</p><h3>Rate Limit</h3><p>Controls request frequency.</p><pre>100 requests/minute</pre><h3>Quota</h3><p>Controls total usage over a longer period.</p><pre>1,000,000 requests/month</pre><p>A system can have both:</p><pre>Rate limit:<br>100 requests/minute</pre><pre>Quota:<br>1M requests/month</pre><h3>22. Important Design Decisions</h3><p>Our final design uses:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/492/1*Nzke51uOyhrH8I6Lfb8XPA.png" /></figure><h3>23. Final Architecture</h3><p>Putting everything together:</p><pre>                         ┌──────────────┐<br>                         │   Clients    │<br>                         └──────┬───────┘<br>                                │<br>                                ▼<br>                       ┌─────────────────┐<br>                       │  Load Balancer  │<br>                       └────────┬────────┘<br>                                │<br>                                ▼<br>                  ┌──────────────────────────┐<br>                  │       API Gateway        │<br>                  │                          │<br>                  │   Token Bucket Limiter   │<br>                  └────────────┬─────────────┘<br>                               │<br>                        Rate Limit Check<br>                               │<br>                               ▼<br>                       ┌────────────────┐<br>                       │ Redis Cluster  │<br>                       │                │<br>                       │ tokens         │<br>                       │ lastRefillTime │<br>                       │ TTL            │<br>                       └───────┬────────┘<br>                               │<br>                      ┌────────┴────────┐<br>                      │                 │<br>                   REJECT             ALLOW<br>                      │                 │<br>                      ▼                 ▼<br>                 HTTP 429         Application<br>                                    Servers<br>                                       │<br>                                       ▼<br>                                   Database</pre><p>The critical path is:</p><pre>Client<br>  ↓<br>Load Balancer<br>  ↓<br>API Gateway<br>  ↓<br>Redis<br>  ↓<br>ALLOW / REJECT<br>  ↓<br>Application</pre><h3>24. Key Takeaways</h3><p>If you remember only a few things from this system-design problem, remember these:</p><h3>1. Token Bucket</h3><pre>Bucket capacity → burst traffic<br>Refill rate     → sustained traffic</pre><h3>2. Redis</h3><p>Use Redis as the shared state store across distributed gateway instances.</p><h3>3. Atomicity</h3><p>The following must happen atomically:</p><pre>Refill<br>  ↓<br>Check<br>  ↓<br>Decrement<br>  ↓<br>Update</pre><p>Redis Lua scripts are a good solution.</p><h3>4. API Gateway</h3><p>Rate-limit requests before they reach backend services.</p><h3>5. Redis Cluster</h3><p>Shard rate-limit state to scale horizontally.</p><h3>6. HTTP 429</h3><p>Use:</p><pre>429 Too Many Requests</pre><p>when the client exceeds its limit.</p><h3>Conclusion</h3><p>A distributed rate limiter may look like a simple counter at first, but designing one at scale introduces several interesting distributed-system challenges.</p><p>The final design combines:</p><pre>Token Bucket<br>      +<br>API Gateway<br>      +<br>Redis<br>      +<br>Atomic Operations<br>      +<br>Redis Cluster<br>      +<br>Horizontal Scaling</pre><p>The most important lesson is that <strong>rate limiting isn’t just about counting requests</strong>.</p><p>It’s about making a fast, correct, distributed decision:</p><blockquote><strong><em>Should this request be allowed to continue?</em></strong></blockquote><p>Once that decision needs to happen across thousands of gateway instances and millions of requests per second, shared state, atomicity, low latency, and scalability become the core design challenges.</p><h3>Interview Summary</h3><p>If an interviewer asks:</p><p><strong>“Design a distributed rate limiter.”</strong></p><p>A concise answer is:</p><blockquote><em>“I’d place the rate limiter at the API Gateway and use a Token Bucket algorithm. The gateway identifies the client and checks its bucket state in Redis. Redis stores the token count and last refill timestamp. The refill, check, and decrement operations would execute atomically, for example using a Lua script, to avoid race conditions. Redis Cluster can horizontally scale the state across shards, and TTLs can clean up inactive clients. Requests with available tokens are forwarded to the application, while requests exceeding the limit receive HTTP 429. For Redis failures, I’d choose fail-open or fail-closed based on the application’s availability and protection requirements.”</em></blockquote><p>That gives you the <strong>core architecture, algorithm, distributed-state strategy, consistency mechanism, and failure handling</strong> in one answer.</p><p>Diagram:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ipPZs3JVIWiHy_NcbYNozA.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d27b00a30313" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[System Design: Designing Bitly — A URL Shortener at Scale]]></title>
            <link>https://theena18.medium.com/system-design-designing-bitly-a-url-shortener-at-scale-543c0b838cd2?source=rss-e6bb5de386b9------2</link>
            <guid isPermaLink="false">https://medium.com/p/543c0b838cd2</guid>
            <category><![CDATA[bitly]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <dc:creator><![CDATA[Dinakaran]]></dc:creator>
            <pubDate>Sun, 20 Sep 2026 05:08:37 GMT</pubDate>
            <atom:updated>2026-09-20T05:08:37.431Z</atom:updated>
            <content:encoded><![CDATA[<p>URL shorteners look simple.</p><p>You give the system a long URL:</p><pre>https://example.com/products/technology/very-long-product-url/12345</pre><p>and it gives you:</p><pre>https://short.ly/aB92xK</pre><p>But what happens when millions of users start clicking that short URL?</p><p>How do we generate unique short codes?</p><p>How do we handle billions of URLs?</p><p>How do we make redirects fast?</p><p>How do we prevent the database from becoming a bottleneck?</p><p>This is where a simple URL shortener becomes an interesting <strong>System Design problem</strong>.</p><p>In this post, I’ll walk through how I approached the design of a Bitly-like URL-shortening system, from the basic requirements to scalability and high availability.</p><h3>1. What Are We Building?</h3><p>At its core, the system performs two operations.</p><h3>1. Create a short URL</h3><p>The user provides a long URL:</p><pre>https://example.com/products/123</pre><p>The system generates:</p><pre>https://short.ly/aB92xK</pre><h3>2. Redirect the short URL</h3><p>When someone visits:</p><pre>https://short.ly/aB92xK</pre><p>the system finds the original URL and redirects the user:</p><pre>https://example.com/products/123</pre><p>So the core mapping is:</p><pre>short_code → long_url</pre><p>That simple mapping is the foundation of the entire system.</p><h3>2. Requirements</h3><p>Before designing the architecture, I would clarify the requirements.</p><h3>Functional Requirements</h3><p>The core system should:</p><ul><li>Create a short URL from a long URL</li><li>Redirect a short URL to the original URL</li><li>Generate unique short codes</li></ul><p>Optional features could include:</p><ul><li>Custom aliases</li><li>URL expiration</li><li>Authentication</li><li>Click analytics</li><li>Rate limiting</li></ul><p>For the initial design, I’ll focus on URL creation and redirection.</p><h3>3. Non-Functional Requirements</h3><p>The system should be:</p><h3>Highly available</h3><p>Users should be able to access short URLs even when individual servers fail.</p><h3>Low latency</h3><p>Redirects should be extremely fast because every click passes through the system.</p><h3>Scalable</h3><p>The system should support billions of URLs and a very large number of redirect requests.</p><h3>Highly read-oriented</h3><p>This is one of the most important characteristics of this system.</p><p>URL creation happens relatively infrequently compared with URL redirection.</p><p>A single short URL can potentially receive millions of clicks.</p><p>So:</p><pre>Reads &gt;&gt;&gt; Writes</pre><p>This observation will influence almost every architectural decision we make.</p><h3>4. API Design</h3><p>We can start with two APIs.</p><h3>Create Short URL</h3><pre>POST /api/v1/urls</pre><p>Request:</p><pre>{<br>  &quot;longUrl&quot;: &quot;https://example.com/products/123&quot;<br>}</pre><p>Response:</p><pre>{<br>  &quot;shortUrl&quot;: &quot;https://short.ly/aB92xK&quot;<br>}</pre><h3>Redirect</h3><pre>GET /aB92xK</pre><p>The server looks up the short code and returns:</p><pre>302 Found<br>Location: https://example.com/products/123</pre><p>The browser then follows the redirect.</p><h3>5. Why 302 Instead of 301?</h3><p>This is an interesting detail.</p><p>A 301 means:</p><pre>Permanent Redirect</pre><p>Browsers and intermediate caches can cache the redirect aggressively.</p><p>A 302 means:</p><pre>Temporary Redirect</pre><p>This gives the URL-shortening service more control over subsequent requests.</p><p>That can be useful when we want to support things such as:</p><ul><li>Analytics</li><li>URL expiration</li><li>Destination changes</li><li>Additional request processing</li></ul><p>For this design, I’ll use <strong>302 redirects</strong>.</p><h3>6. Database Design</h3><p>The core table can be simple:</p><pre>CREATE TABLE urls (<br>    short_code VARCHAR(10) PRIMARY KEY,<br>    long_url TEXT NOT NULL,<br>    created_at TIMESTAMP NOT NULL,<br>    expires_at TIMESTAMP NULL<br>);</pre><p>The important relationship is:</p><pre>short_code → long_url</pre><p>For example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/670/1*gZo0dhnO6-hPCzuqHQTmiA.png" /></figure><p>The short_code is the primary key.</p><p>This gives us two important properties:</p><ol><li>It must be unique.</li><li>It is efficiently indexed for lookups.</li></ol><p>Our redirect query becomes:</p><pre>SELECT long_url<br>FROM urls<br>WHERE short_code = &#39;aB92xK&#39;;</pre><h3>7. The Most Interesting Part: Generating Short Codes</h3><p>How do we generate:</p><pre>aB92xK</pre><p>from a long URL?</p><p>There are several possible approaches.</p><p>One approach is hashing.</p><pre>Long URL<br>   ↓<br>SHA-256<br>   ↓<br>Hash<br>   ↓<br>Base62<br>   ↓<br>Short Code</pre><p>However, if we truncate the hash to keep the URL short, collisions become possible.</p><p>For this design, I’ll use a different approach:</p><blockquote><strong><em>Generate a unique numeric ID and convert it to Base62.</em></strong></blockquote><h3>8. What Is Base62?</h3><p>Base62 uses:</p><pre>26 lowercase letters<br>+<br>26 uppercase letters<br>+<br>10 digits</pre><p>Therefore:</p><pre>26 + 26 + 10 = 62</pre><p>possible characters.</p><p>Instead of representing an ID using decimal numbers, we encode it using 62 characters.</p><p>For example:</p><pre>123456<br>   ↓<br>Base62<br>   ↓<br>aB92xK</pre><p>This allows us to represent large numbers using relatively short strings.</p><h3>9. How Do We Generate Unique IDs?</h3><p>Imagine we have multiple application servers:</p><pre>Server 1<br>Server 2<br>Server 3<br>Server 4</pre><p>We cannot simply maintain a local counter on each server.</p><p>Otherwise:</p><pre>Server 1 → 100<br>Server 2 → 100</pre><p>would produce duplicate IDs.</p><p>We need a centralized or distributed ID-generation mechanism.</p><p>One simple approach is to use Redis.</p><p>Redis provides an atomic INCR operation.</p><p>For example:</p><pre>INCR url_counter</pre><p>could return:</p><pre>1001</pre><p>The next request gets:</p><pre>1002</pre><p>and another server gets:</p><pre>1003</pre><p>Then:</p><pre>1001 → Base62 → short code<br>1002 → Base62 → short code<br>1003 → Base62 → short code</pre><p>Because the counter is atomic, concurrent requests receive unique IDs.</p><h3>10. Counter Batching</h3><p>There is an additional optimization.</p><p>Instead of asking Redis for every single ID:</p><pre>Request → Redis → ID<br>Request → Redis → ID<br>Request → Redis → ID</pre><p>we can allocate ranges.</p><p>For example:</p><pre>Server 1 → 1000–1999<br>Server 2 → 2000–2999<br>Server 3 → 3000–3999</pre><p>Each server can then generate IDs locally from its allocated range.</p><p>This reduces the number of requests sent to the centralized counter.</p><h3>11. The Basic Architecture</h3><p>We can now create our first architecture:</p><pre>Client<br>   |<br>   v<br>Application Server<br>   |<br>   v<br>PostgreSQL</pre><p>For URL creation:</p><pre>Client<br>   |<br>   | POST /urls<br>   v<br>Application Server<br>   |<br>   | Generate ID<br>   v<br>Redis Counter<br>   |<br>   | ID<br>   v<br>Base62<br>   |<br>   v<br>PostgreSQL</pre><p>This works, but it doesn’t scale well for a read-heavy workload.</p><p>So let’s improve it.</p><h3>12. The Biggest Problem: Read Traffic</h3><p>Imagine:</p><pre>1 URL created</pre><p>but:</p><pre>1,000 users click it</pre><p>or perhaps:</p><pre>1,000,000 users click it</pre><p>If every request hits PostgreSQL:</p><pre>User<br>  ↓<br>Application<br>  ↓<br>PostgreSQL</pre><p>the database can quickly become the bottleneck.</p><p>We need a caching layer.</p><h3>13. Introducing Redis Cache</h3><p>We can place Redis in front of PostgreSQL.</p><pre>Client<br>   |<br>   v<br>Application<br>   |<br>   v<br>Redis<br>   |<br>   | Cache miss<br>   v<br>PostgreSQL</pre><p>The redirect path becomes:</p><pre>GET /aB92xK<br>      |<br>      v<br>    Redis<br>      |<br>   ┌──┴──┐<br>   |     |<br> HIT   MISS<br>   |     |<br>   |     v<br>   |  PostgreSQL<br>   |     |<br>   |     v<br>   |   Redis<br>   |     |<br>   └──┬──┘<br>      |<br>      v<br>     302</pre><h3>14. Cache Hit</h3><p>Suppose Redis contains:</p><pre>aB92xK → https://example.com/products/123</pre><p>A request arrives:</p><pre>GET /aB92xK</pre><p>The application checks Redis.</p><p>Redis responds:</p><pre>FOUND</pre><p>The application immediately returns:</p><pre>302 Found<br>Location: https://example.com/products/123</pre><p>The database isn’t touched.</p><p>This is a <strong>cache hit</strong>.</p><h3>15. Cache Miss</h3><p>Suppose Redis doesn’t contain the short code.</p><p>The application queries PostgreSQL:</p><pre>Redis<br>  ↓<br>MISS<br>  ↓<br>PostgreSQL<br>  ↓<br>long_url</pre><p>Then it stores the result in Redis:</p><pre>Redis:<br>aB92xK → https://example.com/products/123</pre><p>The next request can be served directly from the cache.</p><p>This is the <strong>cache-aside pattern</strong>.</p><h3>16. Why Redis Is So Important Here</h3><p>The most important observation in this system is:</p><pre>Reads &gt;&gt;&gt; Writes</pre><p>Therefore:</p><pre>Without cache:</pre><pre>Millions of reads<br>       ↓<br>PostgreSQL<br>       ↓<br>Potential bottleneck</pre><p>With Redis:</p><pre>Millions of reads<br>       ↓<br>Redis<br>       ↓<br>Most requests handled in memory<br>       ↓<br>Only cache misses reach PostgreSQL</pre><p>This dramatically reduces database load and improves latency.</p><h3>17. Horizontal Scaling</h3><p>A single application server isn’t enough.</p><p>We can place multiple stateless servers behind a load balancer:</p><pre>Load Balancer<br>                       |<br>          ┌────────────┼────────────┐<br>          v            v            v<br>       Server 1     Server 2     Server 3<br>          |            |            |<br>          └────────────┼────────────┘<br>                       |<br>                     Redis<br>                       |<br>                  PostgreSQL</pre><p>If traffic increases:</p><pre>3 servers<br>   ↓<br>10 servers<br>   ↓<br>50 servers</pre><p>We simply add more application instances.</p><p>This is <strong>horizontal scaling</strong>.</p><h3>18. Why Stateless Application Servers?</h3><p>The application servers shouldn’t store important state locally.</p><p>Suppose Server 1 receives a request and stores information in its local memory.</p><p>The next request may go to Server 2.</p><p>That would create problems.</p><p>Instead:</p><pre>Application Servers<br>        ↓<br>Shared Redis<br>        ↓<br>Shared Database</pre><p>This means any server can handle any request.</p><p>That makes load balancing and horizontal scaling much easier.</p><h3>19. Read and Write Separation</h3><p>Because the system is heavily read-oriented, we can eventually separate the services.</p><pre>Load Balancer<br>                       |<br>              ┌────────┴────────┐<br>              v                 v<br>        Read Service       Write Service<br>              |                 |<br>              v                 v<br>           Redis             Database</pre><p>We can have many more read instances than write instances.</p><p>For example:</p><pre>100 Read instances<br>5 Write instances</pre><p>depending on traffic patterns.</p><p>This is an example of designing around the actual workload instead of scaling every component equally.</p><h3>20. Database Replication</h3><p>PostgreSQL can also become a bottleneck or single point of failure.</p><p>We can introduce replicas:</p><pre>              PostgreSQL Primary<br>                     |<br>             ┌───────┴───────┐<br>             v               v<br>         Replica 1        Replica 2</pre><p>The primary handles writes.</p><p>Replicas can handle read traffic where appropriate.</p><p>Replication also improves availability because we have additional copies of the data.</p><h3>21. Redis High Availability</h3><p>Redis itself shouldn’t become a single point of failure.</p><p>We can use:</p><pre>Redis Primary<br>     |<br> ┌───┴───┐<br> v       v<br>Replica Replica</pre><p>or Redis Cluster depending on the scale and requirements.</p><p>The exact topology depends on availability, throughput, and operational requirements.</p><h3>22. What Happens If Redis Goes Down?</h3><p>Redis is a cache, not our source of truth.</p><p>If Redis becomes unavailable:</p><pre>Redis ❌<br>   ↓<br>PostgreSQL</pre><p>The application can fall back to PostgreSQL.</p><p>Performance will degrade, but the system doesn’t necessarily have to become unavailable.</p><p>In production, we would also make Redis highly available.</p><h3>23. What Happens If PostgreSQL Goes Down?</h3><p>This is more serious.</p><p>If PostgreSQL is unavailable:</p><pre>Cache HIT<br>   ↓<br>Can still work</pre><p>But:</p><pre>Cache MISS<br>   ↓<br>Database unavailable<br>   ↓<br>Cannot retrieve mapping</pre><p>New URL creation would also be affected.</p><p>Therefore, we need:</p><ul><li>Replication</li><li>Automated failover</li><li>Backups</li><li>Disaster recovery</li></ul><p>for a highly available production system.</p><h3>24. URL Expiration</h3><p>Suppose we want URLs to expire.</p><p>We can add:</p><pre>expires_at</pre><p>to the database.</p><p>Example:</p><pre>short_code = abc123<br>long_url = https://example.com<br>expires_at = 2026-12-31</pre><p>During a redirect:</p><pre>Current time &gt; expires_at?</pre><p>If yes:</p><pre>410 Gone</pre><p>The cache TTL should also respect the URL’s expiration time.</p><p>Otherwise Redis could serve an expired mapping.</p><h3>25. Custom Aliases</h3><p>Users may want:</p><pre>short.ly/my-product</pre><p>instead of:</p><pre>short.ly/aB92xK</pre><p>We can support:</p><pre>{<br>  &quot;longUrl&quot;: &quot;https://example.com/product&quot;,<br>  &quot;customAlias&quot;: &quot;my-product&quot;<br>}</pre><p>The database still enforces:</p><pre>UNIQUE(short_code)</pre><p>If another user already owns:</p><pre>my-product</pre><p>we return:</p><pre>409 Conflict</pre><h3>26. Handling Hot URLs</h3><p>Imagine a celebrity posts:</p><pre>short.ly/aB92xK</pre><p>and suddenly millions of users click it.</p><p>This creates a <strong>hot key</strong>.</p><p>Redis helps because the mapping is already cached.</p><p>For extremely popular URLs, we can also introduce CDN or edge caching:</p><pre>Users<br>  |<br>  v<br>CDN / Edge<br>  |<br>  | cache hit<br>  v<br>302 Redirect</pre><p>This allows requests to be served closer to users and reduces traffic reaching our origin infrastructure.</p><h3>27. CDN and Global Scale</h3><p>If users are distributed globally:</p><pre>India<br>USA<br>Europe<br>Japan<br>Australia</pre><p>we don’t want every request travelling to a single region.</p><p>An edge/CDN layer can help:</p><pre>                   Internet<br>                      |<br>          ┌───────────┼───────────┐<br>          v           v           v<br>       India         USA        Europe<br>        Edge          Edge        Edge<br>          \            |           /<br>           \           |          /<br>                   Origin</pre><p>Popular redirects can potentially be served from nearby edge locations.</p><p>This is especially useful for a read-heavy workload.</p><h3>28. What About Analytics?</h3><p>A real URL-shortening service may want:</p><ul><li>Number of clicks</li><li>Country</li><li>Device</li><li>Referrer</li><li>Timestamp</li></ul><p>But we shouldn’t slow down every redirect by synchronously writing analytics.</p><p>Instead:</p><pre>              Redirect Request<br>                    |<br>             ┌──────┴──────┐<br>             v             v<br>          302 Response   Event<br>                           |<br>                           v<br>                         Queue<br>                           |<br>                           v<br>                       Analytics</pre><p>The user gets the redirect immediately.</p><p>Analytics processing happens asynchronously.</p><h3>29. Why Asynchronous Analytics?</h3><p>Suppose every click requires:</p><pre>Redirect<br>   ↓<br>Analytics DB<br>   ↓<br>302</pre><p>If the analytics system becomes slow, redirects become slow too.</p><p>Instead:</p><pre>Redirect<br>   ↓<br>302 immediately</pre><pre>Analytics Event<br>   ↓<br>Queue<br>   ↓<br>Process asynchronously</pre><p>This keeps the critical redirect path fast.</p><h3>30. Rate Limiting</h3><p>URL shorteners can be abused.</p><p>We can introduce rate limiting at the API gateway or load-balancer layer.</p><p>For example:</p><pre>User → 100 URL creations/minute</pre><p>If the user exceeds the limit:</p><pre>429 Too Many Requests</pre><p>Redis can be used to maintain distributed rate-limit counters.</p><h3>31. Monitoring</h3><p>For production, I would monitor several layers.</p><h3>Application</h3><pre>Request rate<br>Error rate<br>P50/P95/P99 latency</pre><h3>Redis</h3><pre>Cache hit ratio<br>Memory usage<br>Evictions<br>Latency</pre><h3>PostgreSQL</h3><pre>CPU<br>Connections<br>Query latency<br>Storage<br>Replication lag</pre><h3>Infrastructure</h3><pre>CPU<br>Memory<br>Network<br>Disk</pre><p>This helps us identify bottlenecks before they become outages.</p><h3>32. Complete Architecture</h3><p>Putting everything together:</p><pre>                            Clients<br>                               |<br>                               v<br>                         ┌───────────┐<br>                         │    CDN    │<br>                         └─────┬─────┘<br>                               |<br>                               v<br>                       ┌───────────────┐<br>                       │Load Balancer  │<br>                       └───────┬───────┘<br>                               |<br>                ┌──────────────┼──────────────┐<br>                |              |              |<br>                v              v              v<br>             App 1          App 2          App 3<br>                |              |              |<br>                └──────────────┼──────────────┘<br>                               |<br>                        ┌──────┴──────┐<br>                        │    Redis    │<br>                        │    Cache    │<br>                        └──────┬──────┘<br>                               |<br>                         Cache Miss<br>                               |<br>                               v<br>                      ┌────────────────┐<br>                      │   PostgreSQL   │<br>                      │    Primary     │<br>                      └───────┬────────┘<br>                              |<br>                       ┌──────┴──────┐<br>                       v             v<br>                   Replica 1      Replica 2<br></pre><pre>              URL Creation<br>                   |<br>                   v<br>             ID Generator<br>                   |<br>                   v<br>              Redis Counter<br>                   |<br>                   v<br>                Base62</pre><p>The architecture evolved because each component solves a specific problem.</p><h3>33. The Most Important Design Decisions</h3><p>The system can be summarized by these decisions:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/617/1*60LRznilDu0FrFFO_c1KhA.png" /></figure><h3>34. The Biggest Lesson</h3><p>The most important thing I learned from this design is that <strong>system design is not about drawing a complicated architecture</strong>.</p><p>It’s about understanding the workload and solving problems one by one.</p><p>For Bitly:</p><pre>Need unique short URLs<br>        ↓<br>Counter + Base62</pre><pre>Redirects are read-heavy<br>        ↓<br>Redis cache</pre><pre>Traffic increases<br>        ↓<br>Horizontal scaling</pre><pre>Database becomes a bottleneck<br>        ↓<br>Indexes + replicas</pre><pre>Global traffic increases<br>        ↓<br>CDN / edge</pre><pre>Analytics shouldn&#39;t slow redirects<br>        ↓<br>Async processing</pre><p>Every component exists for a reason.</p><h3>35. Final Takeaway</h3><p>A URL shortener looks like a small application:</p><pre>short URL → long URL</pre><p>But when we scale it to billions of URLs and millions of requests, we encounter many classic distributed-system problems:</p><ul><li>Unique ID generation</li><li>Caching</li><li>Database indexing</li><li>Horizontal scaling</li><li>Replication</li><li>High availability</li><li>Hot keys</li><li>CDN</li><li>Asynchronous processing</li><li>Rate limiting</li></ul><p>That’s why the Bitly problem is such a useful <strong>first system-design exercise</strong>.</p><p>The goal isn’t to memorize one architecture.</p><p>The goal is to learn the reasoning:</p><blockquote><strong><em>Start simple → identify the bottleneck → introduce the right component → understand its trade-offs → scale again.</em></strong></blockquote><p>And that same thought process can be applied to almost every system-design problem.</p><h3>What I would revise before an interview</h3><p>If I had only 10 minutes to revise Bitly, I’d remember:</p><pre>1. Requirements<br>2. POST /urls<br>3. GET /{shortCode}<br>4. short_code → long_url<br>5. Counter + Base62<br>6. Redis cache<br>7. PostgreSQL + index<br>8. Load balancer + stateless servers<br>9. Replication<br>10. CDN for global/hot traffic<br>11. Async analytics<br>12. Rate limiting</pre><p><strong>The key mental model:</strong></p><pre>BITLY</pre><pre>Create                    Redirect<br>  │                           │<br>  ▼                           ▼<br>Unique ID                   short code<br>  │                           │<br>  ▼                           ▼<br>Base62                      Redis<br>  │                        /     \<br>  ▼                      HIT     MISS<br>PostgreSQL                 │        │<br>                           │        ▼<br>                           │    PostgreSQL<br>                           │        │<br>                           └────┬───┘<br>                                ▼<br>                               302</pre><p>That is the core of the Bitly system design.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Nne7aKzVKwRyCV9zP__hQg.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=543c0b838cd2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Project Evolution: From VM-Based Deployment to GitOps on GKE]]></title>
            <link>https://theena18.medium.com/project-evolution-from-vm-based-deployment-to-gitops-on-gke-8a316558c348?source=rss-e6bb5de386b9------2</link>
            <guid isPermaLink="false">https://medium.com/p/8a316558c348</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[gitops]]></category>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <dc:creator><![CDATA[Dinakaran]]></dc:creator>
            <pubDate>Sun, 07 Jun 2026 17:08:11 GMT</pubDate>
            <atom:updated>2026-06-07T17:11:11.749Z</atom:updated>
            <content:encoded><![CDATA[<h3>My DevOps Migration Journey 🧑‍💻</h3><h3>Introduction</h3><p>A few months ago, I built a Notes Application deployment project using Terraform and Ansible on Google Cloud Platform. The architecture was simple: Terraform provisioned infrastructure, Ansible configured servers, Docker containers were deployed on virtual machines, and the application was exposed through a public IP.</p><p>While that project helped me understand Infrastructure as Code, Configuration Management, Linux administration, and container deployment, I wanted to take the next step and learn how modern cloud-native applications are deployed in production.</p><p>That led me to a new challenge:</p><p><strong>Migrating the entire application from a VM-based deployment model to a Kubernetes-based GitOps platform running on Google Kubernetes Engine (GKE).</strong></p><p>This article shares the complete migration journey, architecture decisions, challenges faced, and lessons learned.</p><h3>Previous Architecture (Version 1)</h3><p>My original deployment was built using:</p><ul><li>Terraform</li><li>Ansible</li><li>Google Compute Engine (GCE)</li><li>Docker</li><li>MongoDB</li></ul><p>The deployment flow looked like this:</p><p>Developer<br>↓<br>GitHub<br>↓<br>Terraform<br>↓<br>Google Compute Engine VM<br>↓<br>Ansible<br>↓<br>Install Docker<br>↓<br>Run Containers<br>↓<br>Application</p><p>The process worked well, but it had limitations:</p><ul><li>Manual server management</li><li>No container orchestration</li><li>No self-healing</li><li>No rolling updates</li><li>No GitOps workflow</li><li>Limited monitoring capabilities</li><li>Scaling required manual intervention</li></ul><p>As the project evolved, I wanted to build something closer to real-world production environments.</p><h3>Migration Goal</h3><p>The objective was not just to move the application to Kubernetes.</p><p>The goal was to build a complete cloud-native platform that included:</p><ul><li>Infrastructure as Code</li><li>Kubernetes</li><li>GitOps</li><li>CI/CD Automation</li><li>Monitoring</li><li>Security Scanning</li><li>Persistent Storage</li><li>Production-style deployment workflows</li></ul><h3>Target Architecture (Version 2)</h3><p>The architecture:</p><p>Internet<br>↓<br>Google Cloud Load Balancer<br>↓<br>NGINX Ingress Controller<br>↓<br>Frontend Service<br>↓<br>Frontend Pods</p><p>Backend Service<br>↓<br>Backend Pods</p><p>MongoDB Service<br>↓<br>MongoDB Pod<br>↓<br>Persistent Volume Claim<br>↓<br>Google Persistent Disk</p><p>Monitoring Stack<br>↓<br>Prometheus<br>↓<br>Grafana</p><p>GitOps Stack<br>↓<br>GitHub<br>↓<br>GitHub Actions<br>↓<br>DockerHub<br>↓<br>ArgoCD<br>↓<br>Google Kubernetes Engine</p><p>This architecture provides automation, scalability, observability, and improved reliability compared to the VM-based approach.</p><h3>Infrastructure Provisioning with Terraform</h3><p>Infrastructure is provisioned using Terraform.</p><p>Resources created:</p><ul><li>Custom VPC</li><li>Custom Subnet</li><li>Firewall Rules</li><li>GKE Cluster</li><li>Application Node Pool</li><li>Infrastructure Node Pool</li></ul><p>I intentionally created separate node pools to isolate workloads.</p><p>Application Node Pool:</p><ul><li>Frontend</li><li>Backend</li><li>MongoDB</li></ul><p>Infrastructure Node Pool:</p><ul><li>ArgoCD</li><li>Prometheus</li><li>Grafana</li><li>AlertManager</li></ul><p>This design helps separate business workloads from platform services.</p><h4>Terraform Remote State Management</h4><blockquote><em>To improve infrastructure management, I configured a Google Cloud Storage bucket as the Terraform remote backend. This moved the Terraform state file from local storage to centralized cloud storage, making the infrastructure setup more reliable and closer to production practices. Remote state management also provides better collaboration, state consistency, and protection against accidental state file loss.</em></blockquote><h3>Workload Isolation Using Taints, Tolerations, and Node Selectors</h3><p>As the platform grew, I wanted to separate business workloads from platform and monitoring workloads.</p><p>Instead of running everything on the same nodes, I implemented dedicated node pools and workload isolation mechanisms.</p><h3>Node Pool Design</h3><h3>Application Node Pool</h3><p>This node pool hosts the core business application:</p><ul><li>Frontend Pods</li><li>Backend Pods</li><li>MongoDB Pods</li></ul><h3>Infrastructure Node Pool</h3><p>This node pool hosts platform services:</p><ul><li>ArgoCD</li><li>Prometheus</li><li>Grafana</li><li>AlertManager</li><li>NGINX Ingress Controller</li></ul><h3>Why Workload Isolation?</h3><p>Without workload isolation, Kubernetes can schedule any pod on any available node.</p><p>This can lead to several issues:</p><ul><li>Monitoring tools consuming application resources</li><li>Application workloads competing with infrastructure services</li><li>Difficult troubleshooting and resource management</li><li>Reduced reliability during traffic spikes</li></ul><p>To avoid this, I implemented:</p><h3>Node Labels</h3><p>Each node pool was assigned a dedicated role:</p><p>Application Nodes:</p><p>role=application</p><p>Infrastructure Nodes:</p><p>role=infrastructure</p><h3>Node Selectors</h3><p>Application workloads were configured with:</p><p>nodeSelector:<br>role: application</p><p>Infrastructure workloads were configured with:</p><p>nodeSelector:<br>role: infrastructure</p><p>This ensured workloads were scheduled only on their intended node pools.</p><h3>Taints and Tolerations</h3><p>To further strengthen workload isolation, I applied taints on infrastructure nodes.</p><p>Infrastructure Node:</p><p>dedicated=infrastructure:NoSchedule</p><p>This prevents normal application workloads from being scheduled on infrastructure nodes.</p><p>Monitoring and platform services were then configured with matching tolerations:</p><p>tolerations:</p><ul><li>key: “dedicated”<br>operator: “Equal”<br>value: “infrastructure”<br>effect: “NoSchedule”</li></ul><p>As a result:</p><ul><li>Frontend, Backend, and MongoDB run only on Application Nodes</li><li>ArgoCD, Prometheus, Grafana, AlertManager, and Ingress run only on Infrastructure Nodes</li></ul><h3>Benefits</h3><p>This design more closely resembles production Kubernetes environments and provides:</p><ul><li>Better resource utilization</li><li>Improved workload separation</li><li>Easier operations and troubleshooting</li><li>Reduced risk of resource contention</li><li>Greater platform reliability</li></ul><p>Implementing node isolation was one of the most valuable Kubernetes concepts I learned during this migration project because it demonstrated how production clusters separate application workloads from platform services.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PCFktsjhKPWjduRjQhvVUg.png" /></figure><h3>Application Deployment</h3><p>The Notes Application consists of:</p><p>Frontend:</p><ul><li>React</li></ul><p>Backend:</p><ul><li>Node.js / Express</li></ul><p>Database:</p><ul><li>MongoDB</li></ul><p>All components were containerized using Docker and deployed to Kubernetes using Deployments and Services.</p><h3>Persistent Storage for MongoDB</h3><p>One of the first improvements was implementing persistent storage.</p><p>Initially, restarting the MongoDB pod resulted in data loss.</p><p>To solve this, I implemented:</p><ul><li>Persistent Volume Claim (PVC)</li><li>Google Persistent Disk</li></ul><p>Now data survives pod recreation and cluster operations.</p><p>This was a major step toward production readiness.</p><h3>Monitoring and Observability</h3><p>Monitoring was implemented using:</p><ul><li>Prometheus</li><li>Grafana</li></ul><p>The backend application exposes metrics using:</p><p>/metrics</p><p>Prometheus scrapes:</p><ul><li>Application metrics</li><li>Node metrics</li><li>Pod metrics</li><li>Cluster metrics</li></ul><p>Grafana dashboards provide real-time visibility into system health and application performance.</p><h3>Security with Trivy</h3><p>To improve security, I integrated Trivy into the CI/CD pipeline.</p><p>Trivy scans:</p><ul><li>Backend Docker images</li><li>Frontend Docker images</li><li>Kubernetes manifests</li></ul><p>The pipeline is configured to fail when critical vulnerabilities are detected.</p><p>This prevents vulnerable images from reaching production environments.</p><h3>CI/CD Pipeline</h3><p>GitHub Actions is used for automation.</p><p>Pipeline stages:</p><ol><li>Checkout source code</li><li>Build backend Docker image</li><li>Scan backend image with Trivy</li><li>Push backend image</li><li>Build frontend image</li><li>Scan frontend image with Trivy</li><li>Push frontend image</li><li>Update Kubernetes manifests</li><li>Commit manifest changes</li></ol><p>This process eliminates manual image management.</p><h3>GitOps with ArgoCD</h3><p>One of the most valuable parts of the migration was adopting GitOps.</p><p>Traditional deployment:</p><p>Developer<br>↓<br>kubectl apply</p><p>GitOps deployment:</p><p>Developer<br>↓<br>GitHub<br>↓<br>ArgoCD<br>↓<br>Kubernetes</p><p>ArgoCD continuously monitors the Git repository.</p><p>Whenever a deployment manifest changes:</p><ul><li>ArgoCD detects the change</li><li>Compares desired state with actual state</li><li>Automatically synchronizes the cluster</li></ul><p>This creates a fully automated deployment workflow.</p><h3>Challenges Faced During Migration</h3><p>The migration was not straightforward.</p><p>Several challenges were encountered.</p><h3>Ingress Routing Problems</h3><p>Initially, the application was inaccessible through the public endpoint.</p><p>Root Cause:<br>Incorrect ingress configuration and routing rules.</p><p>Solution:<br>Updated ingress rules and verified service mappings.</p><h3>MongoDB Connectivity Issues</h3><p>Backend services failed to connect to MongoDB.</p><p>Root Cause:<br>Incorrect service discovery configuration.</p><p>Solution:<br>Used Kubernetes service DNS names and corrected connection strings.</p><h3>Node Pool Resource Constraints</h3><p>Pods occasionally failed to schedule.</p><p>Root Cause:<br>Insufficient node capacity.</p><p>Solution:<br>Optimized resource allocation and workload placement.</p><h3>ArgoCD Synchronization Errors</h3><p>Applications failed to synchronize correctly.</p><p>Root Cause:<br>Repository structure and manifest path issues.</p><p>Solution:<br>Reorganized GitOps manifests and corrected application configuration.</p><h3>GitHub Actions Deployment Challenges</h3><p>Several iterations were required to move from traditional CI/CD to GitOps.</p><p>The original pipeline deployed directly to Kubernetes.</p><p>The final implementation updates GitOps manifests and allows ArgoCD to handle deployment responsibilities.</p><p>This separation significantly improved the architecture.</p><h3>Key Learnings</h3><p>This project helped me gain practical experience in:</p><ul><li>Terraform</li><li>Google Cloud Platform</li><li>Kubernetes</li><li>Google Kubernetes Engine</li><li>Docker</li><li>GitHub Actions</li><li>ArgoCD</li><li>GitOps</li><li>Prometheus</li><li>Grafana</li><li>Trivy</li><li>Persistent Storage</li><li>Kubernetes Networking</li><li>Ingress Controllers</li><li>Node Pool Design</li><li>Monitoring and Observability</li></ul><p>More importantly, it helped me understand how modern cloud-native platforms are built and operated.</p><h3>Before vs After</h3><p>Version 1</p><p>Terraform → VM → Ansible → Docker Containers</p><p>Version 2</p><p>Terraform → GKE → GitHub Actions → Trivy → DockerHub → ArgoCD → Kubernetes</p><p>The migration replaced server-centric management with a cloud-native, GitOps-driven platform.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/807/1*Ur_zc-xOyuanEU8-HD31-A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/817/1*ISUG9USn2Gvaan360IetpQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/668/1*pp-ofglaqkeYSYej8nUp8Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/777/1*PuiMu8VPLE9wFGVWy8CEUQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/755/1*dyivXBYweQw8uzNjkIbJbg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/501/1*_KdnpwLQYIMZ0PAT-xljQA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IocnOeshkB-KoarjwiUnLg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sDUuYW6j5cXKEAAMtP2cpg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lmWPxHdzfnrr1A9iLerUpA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8OqCO0hHnl8Hmd1OeBZ3iQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Maf7PmRCKfji35nvLW_5QQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s1iWfRx0WkqHPNuvhvPaVg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f6NE5EllL6G099OrTW0lsw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-CqeubNyF4tJnMHHb8u0qQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*evTL3FLkS_wl2MgHDtu7Bw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0_rjz1oPu_cjDPG2cg81hg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yaXDRFhcyvpRqnW7l97JGQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dJuO76xPl_g7Gp_OCUukYQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Pzs-TdjjpQF8KaiuPl8J3A.png" /></figure><h3>Conclusion</h3><p>This project started as a simple Notes Application deployment on virtual machines and evolved into a complete Kubernetes-based GitOps platform running on Google Kubernetes Engine.</p><p>The migration provided hands-on experience with infrastructure automation, Kubernetes operations, monitoring, security scanning, GitOps workflows, and cloud-native deployment practices.</p><p><strong>The migration reduced manual deployment effort by nearly 90%, transforming the deployment process from a VM-based manual workflow into a fully automated GitOps-driven platform.</strong></p><p>While there are still areas for future improvement such as SonarQube, AlertManager, centralized logging, and autoscaling, this project represents a major milestone in my DevOps learning journey and significantly improved my understanding of modern platform engineering practices.</p><p>As the project evolved, I wanted to build something closer to real-world production environments.</p><blockquote>THANK YOU FOR READING🤝</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8a316558c348" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>