<?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 Vaibhav Kansagara on Medium]]></title>
        <description><![CDATA[Stories by Vaibhav Kansagara on Medium]]></description>
        <link>https://medium.com/@vaibhavkansagara?source=rss-910c9c12cd74------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*NKT-RWP9Lqlq6l8R</url>
            <title>Stories by Vaibhav Kansagara on Medium</title>
            <link>https://medium.com/@vaibhavkansagara?source=rss-910c9c12cd74------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 06:50:59 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@vaibhavkansagara/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[Database design of Udemy]]></title>
            <link>https://medium.com/@vaibhavkansagara/database-design-of-udemy-66af2d42a03f?source=rss-910c9c12cd74------2</link>
            <guid isPermaLink="false">https://medium.com/p/66af2d42a03f</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <dc:creator><![CDATA[Vaibhav Kansagara]]></dc:creator>
            <pubDate>Fri, 23 Feb 2024 11:01:32 GMT</pubDate>
            <atom:updated>2024-02-23T11:01:32.890Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, we are going to talk about low-level implementation details about how Udemy’s database works. We will look at the structure of the data, what types of databases we should use, and the different types of queries that are made on the database, what indexes should be created to improve the performance of queries?</p><p>Udemy’s taxonomy is very simple. Based on the below diagram, it has three layers. The first layer is Categories which include Software Engineering, Arts, and Business. The second layer is sub-categories which include Programming Languages, Databases, Web Development, etc. The third category is specific niche topics inside each sub-category which we call topics which include Machine Learning, Python, etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l6H7H0uIuYOgiHcjOW0JBQ.png" /><figcaption>Udemy’s taxonomy</figcaption></figure><p>Before we go into database design, let’s first see what kind of database to use. It’s a classic SQL vs NoSQL tradeoff that needs to be discussed.</p><p><strong>Structure of the data</strong> — The data is fairly structured and the schema is well-defined, thus we can go with SQL here. For schema refer to later sections of this article.</p><p><strong>Do we have ever-increasing data</strong> — <strong>No</strong> since there are a limited number of categories. NoSql is more scalable compared to Sql but since there is no need for scale here, we can choose Sql here.</p><p><strong>Do we need distributed data</strong> — <strong>No</strong> since the number of categories is limited, the total size of the table would be less than a few TBs which can be accommodated in a single machine. For heavily distributed data we can go with NoSql but since there is no such need, we will choose Sql.</p><p><strong>Is our system write heavy </strong>—<strong> No</strong> since there are a limited number of updates happening aka new categories getting added/updated.</p><p><strong>Do we need strong data consistency</strong> — <strong>Yes </strong>refer below schema to understand why.<strong> </strong>Strong consistency is the hallmark of SQL databases.</p><p>All these questions indicate that we should go with the MySQL database.</p><p><strong>Database Design</strong></p><p>The first design that might come to your mind is to keep each layer(category, sub-category, topic) in a separate table and have foreign keys that weave them together. This is not a good design for three reasons.</p><ol><li>All three tables have the same schema. In software engineering, we must follow the DRY principle which is “do not repeat”.</li><li>What if we want to add another layer between subcategories and topics? In that case, we will need to create a new table therefore the design is not extensible.</li><li>What if we want to put certain topics directly under categories? Since foreign keys only allow one column to map to a single column in another table, we are unable to place certain topics under multiple categories directly. This limitation arises because we’re using foreign keys to establish relationships between records in separate tables.</li></ol><p>So instead of keeping separate tables for each layer, we can keep all the layers in a single table and keep an additional column “type” which indicates which layer it is. Below is the schema of the table.</p><pre>TableName: topics<br><br>Columns: <br>  id int primary_key auto_increment, <br>  name varchar non null, <br>  parent_id int null, <br>  type int non null, <br>  score floar default // score represents how popular a cateogry is<br><br>Primary Key: id<br>Foreign Key: parent_id -&gt; topics(id)</pre><p>Let’s see what the table will look like for the below topics<br>Software Engineering &gt; Programming Languages &gt; Python<br>Software Engineering &gt; Programming Languages &gt; Javascript</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MJuXk2jikk6fcPrSbBXt2A.png" /><figcaption>Topics table MySql Schema</figcaption></figure><p>Let’s now analyse the query patterns and then we will talk about what indices to use to fasten those queries. Let’s start with the simplest one.</p><p><strong>Query 1 — Get topic by topic id</strong></p><pre>SELECT * FROM topics WHERE id = 11792</pre><p><strong>Query 2 — Get all the children of the category or sub-category</strong><br><em>Usage</em> — When the user clicks on “Browse and Explore”, we need to list down all the categories where parent_id equals topic_id browsed by the user. To make the below query efficient, we will create a composite index <strong><em>(parent_id, score)</em></strong>.</p><pre>SELECT * FROM topics WHERE parent_id = 123 ORDER BY score DESC</pre><p><strong>Query 3 — Get all categories of a particular type</strong></p><pre>SELECT * FROM topics WHERE type = 1 ORDER BY score DESC</pre><p>To make the above query efficient, we will create an index on the type column.</p><p><strong>Summary of indexes we need on topics</strong></p><ul><li>Primary Key on id</li><li>Foreign Key on parents_id</li><li>Index on type</li><li>Composite Index on (parent_id, score)</li></ul><p>That’s it from today’s tutorial. Happy learning!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=66af2d42a03f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How does end-end encryption work]]></title>
            <link>https://medium.com/@vaibhavkansagara/how-does-end-end-encryption-work-7a37e0c7a5b0?source=rss-910c9c12cd74------2</link>
            <guid isPermaLink="false">https://medium.com/p/7a37e0c7a5b0</guid>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[encryption]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Vaibhav Kansagara]]></dc:creator>
            <pubDate>Mon, 19 Feb 2024 20:28:34 GMT</pubDate>
            <atom:updated>2024-02-19T20:28:34.687Z</atom:updated>
            <content:encoded><![CDATA[<p>Today we are going to talk about how end-end encryption works. You must have heard that WhatsApp and other text messaging platforms like Facebook Messenger use end-to-end encryption for securing text messages. Let’s dive deep into how it works, and what various algorithms are used in end-end encryption.</p><p>What does end-end encryption mean? Let’s say person A sends messages to person B, then only person B can see your messages and no one else. A question might come to your mind. What about the WhatsApp server? Can WhatsApp servers read the messages? The answer is No, even the server will not be able to read the messages.</p><p>Most of today’s applications are secured using public key cryptography. In public key cryptography, there are two keys public key and private key. Messages are encrypted using a public key but can be decrypted only with the private key. This is the basic essence of public key cryptography.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Uio-3mmmYy4cU_i8bj0n5A.png" /><figcaption>End-End Encryption</figcaption></figure><p>In the above diagram, you can see that both A and B have two sets of keys. Each has a public and private key. At the start of the chat, both parties exchange their public keys. Now when A wants to send a message to B, A encrypts the message with B’s public key and sends the message to B. Now B has the encrypted message. Now since the message was encrypted using B’s public key, B can decrypt the message using B’s private key and voila B can read the message A sent.</p><p>Here a question might come to your mind let’s suppose a hacker is sitting in the middle of the conversation and hijacks the public key of B. The Hacker then encrypts the message using B’s public key and sends a message to B. How does B figure out that the message was sent by A or the hacker? The answer is adding a digital signature to the message which will be verified by B that the message is actually sent by A or not. How does this signature verification take place?</p><p>The following steps are carried out:</p><ol><li>A adds a digital signature to the encrypted message. What is a digital signature and how is it calculated? A digital signature is nothing but the hash of the message and the hash of the message is then signed using A’s private key.</li><li>A sends the encrypted message + digital signature to B.</li><li>B extracts the digital signature and verifies the signature using A’s public key. Since the digital signature was signed using A’s private key which the hacker does not have access to, B is able to verify that the message was indeed sent by A.</li><li>After extracting the digital signature from the message, B decrypts the message using B’s private key.</li></ol><p>This whole process is called <strong>end-to-end</strong> encryption. Before the advent of end-to-end encryption, <strong>encryption-in-transit</strong> was widely used for securing messages. The below image sums up the encryption-in-transit concept.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*80HsId9GbfsWsf4LAGWxOg.png" /></figure><p>Here message is sent to the API server via HTTPS protocol which provides SSL/TSL encryption which means that the data is encrypted and then sent to the API server but SSL/TLS protection breaks at the API server end and the API server can read the unencrypted version of the message and store it in it’s datastores. The message is then sent to B again via HTTP protocol with SSL/TLS protection enabled. As you can see from the diagram the API server can read the message and thus the communication is not entirely secure.</p><p>Whenever you add a new contact to the list, the public key of that contact person is stored on your device. Note that <strong>your private key</strong> is stored on your device and not on the server. public key can be stored anywhere but usually stored on the server.</p><p>This is a really simple version of how WhatsApp encryption works. In reality, it is much more complicated, and under the hood, it uses something called a double ratchet algorithm. It cannot be covered here as it is very complicated but in essence, it uses a different encryption key for each message. If you want to understand the double ratchet algorithm in more detail, please check out this <a href="https://www.youtube.com/watch?v=7uEeE3TUqmU">video</a> which is a beautiful and intuitive explanation of how the algorithm works.</p><p>Now there might be an interesting question popping up in your head. There was some news recently where private WhatsApp messages of celebrities were leaked. you must be wondering whether WhatsApp is secretly storing users&#39; private keys. Although there have been allegations on WhatsApp that they are storing users&#39; private keys, in reality, the messages were leaked due to the vulnerability of the device OS and not due to a break in encryption.</p><p>Another question that might come to your mind is that if WhatsApp does not store private keys on the server then how does it perform backup? What happens when your device data is wiped out for some reason and you need to recover the data from WhatsApp backup? When a user performs a backup of data, an encryption key is generated which is derived from the user’s account information. Data is encrypted using this key and stored on the cloud. When the recovery happens, encrypted data is sent from the cloud to the new device, and an encryption key is generated using the same algorithm using which the data was encrypted. Data is then decrypted using this key and then restored. Note that the backup server doesn&#39;t decrypt the messages, all messages are decrypted only on the client end using the key that is also generated on the client end using the user&#39;s account information.</p><p>That’s it from today&#39;s tutorial. Happy learning!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7a37e0c7a5b0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Design In-Memory Database]]></title>
            <link>https://medium.com/@vaibhavkansagara/design-in-memory-database-16b010a521e0?source=rss-910c9c12cd74------2</link>
            <guid isPermaLink="false">https://medium.com/p/16b010a521e0</guid>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[hld]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[lld]]></category>
            <dc:creator><![CDATA[Vaibhav Kansagara]]></dc:creator>
            <pubDate>Wed, 14 Feb 2024 19:03:52 GMT</pubDate>
            <atom:updated>2024-02-14T19:03:52.396Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, we will discuss how to design an in-memory database. This question was asked to me in one of the design interviews and is a very famous question that is asked generally in LLD interviews. This article will start with a typical implementation of the in-memory database but the more exciting part is in the second half so stay tuned. So without further ado, let’s get on with it.</p><p>Now here a question might pop into your head(if it doesn’t then there is something seriously wrong with you). What the heck is an in-memory database and how does it differ from regular databases? in-memory database is a special kind of database that is entirely stored in RAM. Operations in RAM are faster and hence in-memory databases are used where we need ultra-low latency. Now again you might ask what if the server goes down? yeah, then in that case data is lost and never coming back. We will see how to get around this problem in the second part of this article.</p><p>Let’s first go over the requirements.</p><p>Requirements:</p><ol><li>The user should be able to create and remove the database.</li><li>The user should be able to create and drop tables in the database.</li><li>The user should be able to get a list of records based on the column value specified by the user.</li><li>The user should be able to insert/update/delete a record in the table.</li></ol><p>Now that we are done with the requirements, the first thing that should come to your mind is what classes would be required to implement the database.</p><p>Classes — DatabaseManager, Database, Table, Row</p><p>Let’s look into the above classes and what properties and methods each one has.</p><p><strong>Row</strong> —</p><pre>@Getter<br>@Setter<br>@RequiredArgsConstructor // will create the constructor with all arguments<br>public class Row {<br>    private String rowId;<br>    private Map&lt;String, Object&gt; columnToValueMap;<br>    private Date createdAt;<br>    private Date updatedAt;<br>}</pre><p><strong>Table</strong> —</p><pre>@Getter<br>@Setter<br>@RequiredArgsConstructor // will create the constructor with all arguments<br>public class Table {<br>    private String tableName;<br>    private Map&lt;String, Row&gt; rowEntries;<br>    private Date createdAt;<br><br>    Row insertRecord(String rowId, Row row);<br>    Row updateRecord(String rowId, Map&lt;String, Object&gt; rowValues);<br>    void deleteRecord(String rowId);<br>    Row getRecord(String rowId);<br>}</pre><p><strong>Database</strong> —</p><pre>@Getter<br>@Setter<br>@RequiredArgsConstructor // will create the constructor with all arguments<br>public class Database {<br>    private String databaseName;<br>    private Map&lt;String, Table&gt; tables;<br>    private Date createdAt;<br><br>    void createTable(String tableName);<br>    void dropTable(String tableName);<br>}</pre><p><strong>DatabaseManager</strong> —</p><pre>@Getter<br>@Setter<br>@RequiredArgsConstructor // will create the constructor with all arguments<br>public class DatabaseManager {<br>    private Map&lt;String, Database&gt; databases;<br><br>    public Database createDatabase(String databaseName);<br>    public void dropDatabase(String databaseName);<br>}</pre><p>We will not be going into the exact implementation as the implementation of these methods is very trivial.</p><p>Let’s talk about the interesting stuff now. In the first section, we saw how to implement the in-memory database. Since it is in memory, the entire database resides in the RAM. If the server goes down, we lose all the data. Most real-world implementations of in-memory databases for ex: Redis persist the data on disk to recover from situations like this. Operations are performed on RAM but the log of each operation is stored on disk so that if the server crashes, the transaction log in the disk can be used to reconstruct the cache.</p><p>In the below diagram, you can see that queries are performed on the main memory so the performance of queries is not impacted but updates happen to both main memory and also we need to store the operation in the transaction log. At this point, alarms should start going off in your head. Can you identify what is the problem here? At first glance, you will think that update latency will be very high as we are performing writes to disk since disk operations are much slower compared to RAM operations. So why the fuck are we using cache(RAM) in the first place if writes need to go to the disk. It’s like having a Ferrari for show but driving at a snail’s pace.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ito9OgutP4auGJkUGw7ciw.png" /></figure><p>The answer to the questions popping up in your head is that writing to the disk is not the bottleneck operation here. Why? Notice how we are trying to write to the log file. We are writing to the file in an <strong><em>append-only</em></strong> manner. Why is this important? Because writing to the disk in an append-only manner is almost as fast as writing to RAM. Let’s understand why that is the case.</p><p>Magnetic disks are unusually fast when accessed sequentially. On the other hand, they are extremely slow when accessed randomly. This is because the disk head has to rotate and physically move to the partition where the data is kept. To give you some numbers, the disk can perform around 100 operations/second whereas during sequential access, the disk can perform 10⁶ operations/second. This speed is in line with the speed of writing to cache and thus writing to disk is not the bottleneck operation.</p><p>That’s it from today’s tutorial. Happy learning.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=16b010a521e0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Design PasteBin]]></title>
            <link>https://medium.com/@vaibhavkansagara/design-pastebin-5863320ee429?source=rss-910c9c12cd74------2</link>
            <guid isPermaLink="false">https://medium.com/p/5863320ee429</guid>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[high-level-design]]></category>
            <category><![CDATA[lld]]></category>
            <dc:creator><![CDATA[Vaibhav Kansagara]]></dc:creator>
            <pubDate>Sun, 28 Jan 2024 20:09:52 GMT</pubDate>
            <atom:updated>2024-01-28T20:09:52.607Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, we will discuss how to design a live-streaming feature in Disney+ Hotstar. This question was asked to me in the Microsoft system design interview round. So without further ado, let’s get on with it.</p><p>Let’s first talk about functional and non-functional requirements and then we will dive deep into each of the requirements.</p><p><strong>Functional Requirements:</strong></p><ol><li>The user should be able to create a paste with a blob of text. Here only text should be allowed and not images.</li><li>The user should be able to specify the expiration time for the paste. This could range from 5 minutes to 5 years. Expired pasts should not be visible to the user.</li><li>The user should be able to fetch the text by going to the URL.</li></ol><p><strong>Non-Functional Requirements:</strong></p><ol><li>High Availability</li><li>Eventual Consistency — Since the user is not going to access the link immediately after creating the link, there is no need for strong consistency here.</li><li>Low Latency — The URL for accessing the paste must have low latency &lt; 100ms</li></ol><p><strong>Capacity Estimation</strong></p><p>The read/Write ratio of Pastebin would be around 100:1 as Pastebin is a read-heavy system. Therefore,</p><p><strong><em>no of write requests/day</em></strong> ~ 1 million ~ 12 writes/sec<br><strong><em>no of read requests/day</em></strong> ~ 100 million ~ 1200 reads/sec</p><p>Assuming the maximum size of paste is ~ 10MB and since we receive 1 million paste/day</p><p><strong><em>Average size of paste</em></strong> ~ 10KB<br><strong><em>Total memory needed for 1 day</em></strong> = 1 million * 10 KB ~ 10GB</p><p>Assuming we are storing the paste for 5 years<br><strong><em>Total memory needed</em></strong> ~ 365 * 5 * 10 ~ 17TB<br><strong>Number of unique URLs needed</strong> ~ 1 million * 365 * 5 ~ 2 billion URLs</p><p><strong>APIs Design</strong></p><ol><li>Create Paste</li></ol><p>EndPoint: <strong>POST</strong> <em>/pastes</em><br><strong>Request</strong>:</p><pre>{<br>  &quot;content&quot;: &quot;Paste content goes here&quot;,<br>  &quot;title&quot;: &quot;Optional paste title&quot;,<br>  &quot;expiry&quot;: &quot;Optional expiry date/time&quot;<br>}</pre><p><strong>Response</strong>:</p><pre>{<br>  &quot;id&quot;: &quot;paste_id&quot;,<br>  &quot;url&quot;: &quot;https://api.example.com/pastes/paste_id&quot;<br>}</pre><p>2. Get Paste</p><p>EndPoint: <strong>GET</strong> <em>/pastes/{paste_id}</em><br>Response:</p><pre>{<br>  &quot;id&quot;: &quot;paste_id&quot;,<br>  &quot;create_at&quot;: &quot;Timestamp&quot;,<br>  &quot;content&quot; : &quot;Paste content goes here&quot;,<br>  &quot;expiry_date&quot;: &quot;Optional expiry date/time&quot;,<br>  &quot;url&quot; : &quot;https://api.example.com/pastes/paste_id&quot;,<br>  &quot;title&quot;: &quot;This is an example paste titel&quot;,<br>  &quot;views&quot;: 123<br>}</pre><p>3. List all pastes by user</p><p>EndPoint: <strong>GET</strong> <em>/users/{user_id}/pastes</em><br>Response:</p><pre>[{<br>  &quot;id&quot;: &quot;paste_id&quot;,<br>  &quot;create_at&quot;: &quot;Timestamp&quot;,<br>  &quot;content&quot; : &quot;Paste content goes here&quot;,<br>  &quot;expiry_date&quot;: &quot;Optional expiry date/time&quot;,<br>  &quot;url&quot; : &quot;https://api.example.com/pastes/paste_id&quot;,<br>  &quot;title&quot;: &quot;This is an example paste titel&quot;,<br>  &quot;views&quot;: 123<br>},<br>// other paste<br>]</pre><p>4. Delete paste</p><p>EndPoint: <strong>DELETE</strong> <em>/pastes/{pasteId}</em></p><p><strong>Database Design</strong></p><p>We will have two tables, one for storing user data and another for storing paste metadata.</p><p><strong>User table</strong>: <em>user_id</em>{hash_key}, name, phoneno, password_hash <br><strong>PasteMetadata table</strong>: <em>paste_id</em>{hash_key}, create_at, pasteUrl, title, expiry_date, views</p><p><strong>High-Level Design</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZornRzIJAqWgQwFB40lZWA.png" /><figcaption>PasteBin HLD</figcaption></figure><p>Before we move to individual components, we need to talk about pasteId. In the capacity estimation discussion, we estimated the unique number of URLs needed to be around 2 billion. we can create pasteId containing {a-zA-Z0–9}. we will use a length of 6 for pasteId which would make around 65⁶ ~ 56 billion combinations giving us enough room for spare IDs.</p><p><strong>Components:</strong></p><p><strong>KeyGenerationService</strong> — <br>1. When a new paste creation request comes, one thing we can do here is we can generate unique keys every time in a random manner and check in the database if the key is present. If the key is present, we again generate a new random key, again check in the database if the key is present and if the key is not present, we return the key to the user and store the past corresponding to that key. This approach is not efficient as it will increase write latency as we need to perform a check in the db whether the key exists or not.</p><p>2. To get around this problem, we will pre-generate the keys and store them in keyDB. This db stores a mapping between keyId and a boolean value indicating whether a key is already in use. When a paste creation request comes, we query the keyDB to get keys that are not currently in use. That way there is no extra write latency and in a single call, we can get the pasteId and return the url to the user. But here also there is a problem. There will be multiple instances of KeyGenerationservice running in parallel so how do we ensure consistency?</p><p>3. To get around this problem, we use a caching layer. Each keyGeneration server will query the keyDb to get a list of unused pasteIds(for ex: 1000) and each server will have a unique list and this list will be stored in the in-memory cache of the server. When a new pasteId generation request comes, individual servers will return an id from the unused pasteId pool. After that, the server will mark the id as used in the keyDB. If for some reason the server goes down, we lose the list of unused keyIds but since we have a large number of potential Ids(~56 billion), a loss of a few thousand ids is acceptable.</p><p><strong>KeyDB — <br></strong>Database storing mapping of keys and a boolean value indicating whether they are currently in use or not.</p><p><strong>PasteBinService</strong> — <br>This service exposes all client-facing APIs mentioned at the beginning of this article and is responsible for creating the paste and storing paste metadata in the PasteBinDB and s3 bucket. This service is also responsible for fetching the paste content from the s3 bucket when a GET request comes.</p><p><strong>S3 bucket</strong> — <br>object data store storing the paste contents. paste content will be stored against pastId which will be the key for retrieving paste content.</p><p><strong>PasteBinDB</strong> — <br>NoSQL database(Amazon DynamoDb) storing the above-mentioned tables(UserMetadataTable and PasteMetadataTable)</p><p><strong>Redis Cache</strong> — <br>Since our system is read-heavy, redis cache will be used to query the cache first and if the paste is not found in the cache, then data will be fetched from the database. The typical cache eviction policy of LRU will be used for evicting elements.</p><p><strong>AWS Lambda</strong> — <br>Aws lambda is responsible for expiring the records. aws lambda will periodically scan the PastebinMetadata table and delete the records that are expired. It will also mark the corresponding keys of the deleted records in keyDb to true meaning that they can be re-used.</p><p>That’s it for today’s tutorial.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5863320ee429" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Design Live Streaming feature in Disney+Hotstar]]></title>
            <link>https://medium.com/@vaibhavkansagara/design-live-streaming-feature-in-disney-hotstar-dfc9ac27b4ea?source=rss-910c9c12cd74------2</link>
            <guid isPermaLink="false">https://medium.com/p/dfc9ac27b4ea</guid>
            <category><![CDATA[hld]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[lld]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <dc:creator><![CDATA[Vaibhav Kansagara]]></dc:creator>
            <pubDate>Thu, 25 Jan 2024 19:58:43 GMT</pubDate>
            <atom:updated>2024-01-25T19:58:43.627Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, we will discuss how to design a live-streaming feature in Disney+ Hotstar. This question was asked to me in the Microsoft system design interview round. So without further ado, let&#39;s get on with it.</p><p>Live streaming is a little different and challenging compared to streaming static video. Videos on Netflix are examples of static videos that can be uploaded to the server and then shown to the users but here we cannot do the same. We need to upload the video on the fly and show it to the users.</p><p>Start thinking from the source of the data. It could be a mobile camera or browser webcam. The device encoder will capture the live stream data and now this data needs to be transferred to the server. To transfer this data we use a protocol called <strong>RTMP(Real-time Message Protocol)</strong> protocol. Now I know what you are thinking. Why do we need some fancy ass protocol for transferring the encoded data to the server? Let’s dive deep into it.</p><p>RTMP protocol uses TCP as its underlying protocol. TCP ensures that there is no data loss and also supports the ordering of the packages.</p><p>RTMP protocol is used and specifically designed for live streaming audio, and video content over the internet. The main benefits of this protocol include <em>low latency, adaptive bit rate streaming, and bi-directional communication</em>. Let’s see how it achieves all these things.</p><p>How does it achieve low latency? RTMP is a bi-directional protocol meaning it will keep the connection open instead of creating a new HTTP connection for each data packet. This minimizes connection creation and teardown overhead and reduces latency. Apart from this it also does data compression to reduce the size of the data to be transmitted over the network.</p><p>What is adaptive bit rate streaming? Adaptive bit rate streaming is a technique in which the client will automatically adjust the bit rate based on the network quality. For ex: if the network is very good, the client will request the server to provide higher-resolution video packets. For some reason if the network quality drops, the client will request lower-quality video resolution packets. This way users will get a seamless experience. This functionality is supported by the RTMP protocol.</p><p>Once the data is received on the server end, we store the data in an S3 bucket. After that, we need to do some transformations on the video to convert it into different resolutions and video formats to meet our heterogeneous client. This transformation will be done by Transformation Service. The transformation service will create tasks and publish them to a message queue. An example of this task could be “convert this video packet from 1080p to 360p”. Message queue will then be polled by a pool of workers and they will consume the messages from the message queue, do the processing, and publish the result to another message queue.</p><p>Processed messages will be stored in DFS(distributed file system) and then consumers will start consuming the messages from the queue. The below diagram will make the above process clear. These workers will publish the messages to different queues. Different queues will support different video resolution and video formats. Workers will publish the message into queues based on video resolution and video format supported by the client and consumers of that resolution and format will consume the messages from the corresponding queue.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FXN9IgP09jXtjsQfr9lE5g.png" /><figcaption>Live Streaming HLD</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dfc9ac27b4ea" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Distributed Locking Service]]></title>
            <link>https://medium.com/@vaibhavkansagara/distributed-locking-service-d49824fb6e1f?source=rss-910c9c12cd74------2</link>
            <guid isPermaLink="false">https://medium.com/p/d49824fb6e1f</guid>
            <category><![CDATA[hld]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[lld]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <dc:creator><![CDATA[Vaibhav Kansagara]]></dc:creator>
            <pubDate>Fri, 19 Jan 2024 09:58:27 GMT</pubDate>
            <atom:updated>2024-01-19T09:59:37.556Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, we will talk about distributed locking services. We will go through some important concepts in locking mechanisms and then talk about how locking works in a distributed environment with multiple machines.</p><p>Let’s first understand the concept of locks, mutex, and semaphores</p><p><strong>Locks</strong> — It’s a synchronization mechanism for controlling access to a shared resource like files in a multi-threaded environment. locks are generally used to control access to a resource among multiple threads in the same process.</p><p><strong>Mutex</strong> — It’s also a synchronization mechanism for controlling access to a shared resource but the key difference from locks is that mutex is used to synchronize access among multiple different processes.</p><p><strong>Semaphores</strong> — Semaphores are a synchronization mechanism that allows multiple threads to access the same resource up to a specific limit. It keeps a counter of how many threads are accessing a particular resource and restricts access to n number of threads. If n+1&#39;th thread tries to access the resource, it will block that thread.</p><p>Locking looks simple in a single-machine environment but quickly becomes an issue when there are multiple machines involved. How do we ensure locking in a distributed environment?</p><p>The main problem with locking is that when multiple servers are trying to access the same file, how do we ensure that this file is not accessed by multiple machines? If all the machines access the file, there is a chance that it will get corrupted. One obvious solution that comes to mind is that we keep the information of which file is accessed by which server in a database and all the servers will query this database first to see if the file is locked or not. The problem with this approach is that the database represents a single point of failure and to get away with that we need multiple copies of the database but this will make the task of syncing difficult. Also using a database for such frequent reads/writes is not efficient and we should consider using a cache here but the same problem arises as to what happens if the cache goes down.</p><p>To get around this problem, we introduce a lock manager. The lock manager will interact with Redis and provide a boolean value indicating whether a particular resource is locked or not. Here again, we face the issue of a single point of failure so we need to have multiple instances of lock manager running. How do we sync the data between multiple instances? Well, we do that using a master-slave architecture where one of the nodes is elected as a leader and will perform read+write operations, and the rest of the nodes will perform only read operations. Write is considered successful only if the data is synced by all the nodes. Here we are compromising on latency to ensure high availability. To perform leader election we use zookeeper instances which keep track of which node is the leader. If the leader node goes down, the rest of the nodes participates in the leader election and one of the nodes becomes the leader.</p><p>Let’s say instance 1 is acquiring a lock then all the other instances will have to wait for lock manager to release the lock and then only they can access the data. But this has an obvious flaw that if instance 1 goes down without releasing the lock then all other instances will be indefinitely get blocked. In order to solve this problem we introduce TTL in Redis cache that the lock will expire after 5 seconds and other instances can get the lock after expiry so that they don’t get deadlocked.</p><p>But again this has problems as let&#39;s say at 7 seconds instance one finishes the task and tries to write the data into Redis but the lock is now acquired by someone else who will write something else in Redis. So here there is a high chance that the data in Redis will be corrupted and also there will be redundant work done by instances. To get around this problem, the lock manager keeps a unique lockId for the instance that acquired the lock and when instance1 comes to modify the data in Redis with lockId1, it will get rejected as it does not match with the current lockId2 which is acquired by another instance.</p><p>Even then there is a possibility of a collision while generating lockIds. Here we need to ensure that each lock manager instance generates unique lockIds based on nanosecond or microsecond timestamps.</p><p>That’s it for today&#39;s tutorial.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d49824fb6e1f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Distributed Cache System Design]]></title>
            <link>https://medium.com/@vaibhavkansagara/distributed-cache-system-design-2ee5e25a5000?source=rss-910c9c12cd74------2</link>
            <guid isPermaLink="false">https://medium.com/p/2ee5e25a5000</guid>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[cache]]></category>
            <category><![CDATA[hld]]></category>
            <category><![CDATA[lld]]></category>
            <category><![CDATA[computer-science]]></category>
            <dc:creator><![CDATA[Vaibhav Kansagara]]></dc:creator>
            <pubDate>Sat, 13 Jan 2024 15:47:42 GMT</pubDate>
            <atom:updated>2024-01-13T15:47:42.193Z</atom:updated>
            <content:encoded><![CDATA[<p>Today we will be talking about how to design a distributed cache. But before we dive deep into how to design a distributed cache, we need to understand the topic of cache in significant detail. Hop on for an exciting journey.</p><p>Caching is used at multiple places to reduce latency and fast retrieval of data. Let’s explore common places where caching is used.</p><ol><li>CPU Cache — The CPU uses cache to store frequently accessed data in L1, L2, or L3 cache. retrieval of data is faster from these caches than from RAM.</li><li>RAM cache — operating systems use RAM for in-memory cache to retrieve data faster compared to retrieving from hard disks.</li><li>CDN cache — CDN stands for content delivery network and frequently accessed media(images, video, files) are cached into servers closer to the user’s location thereby reducing the latency for retrieving the data.</li><li>DNS cache — DNS servers cache mapping of domain names to IP addresses so that frequently accessed domains don’t need to go through the DNS resolution process and can resolve the DNS query faster.</li><li>Database caching — database caching is a mechanism for storing expensive and frequent queries to improve database performance.</li></ol><p>We need to understand the validity of the data that is cached. Effective caching strategies ensure a high cache hit rate(meaning a lot of requests are satisfied by cache). If the cache cannot respond to the query, then it is cache-miss. Now there would be a question in your mind as to what data will reside in the cache and for how long. TTL stands for time to live. It is measured in seconds/milliseconds. Each entry in the cache has an associated TTL. when TTL expires for the record, it gets deleted from the cache and subsequent requests for the record will result in a cache miss.</p><p>Below are the requirements that we are considering for our design</p><ul><li>The storage capacity of the cache should be in <strong>Terabytes</strong>.</li><li>Number of requests/ sec ~ <strong>1 million</strong></li><li>Latency for retrieval ~ <strong>1 millisecond</strong></li><li>High Availability</li><li>High Scalability</li></ul><p>Let’s explore cache access strategies. There are three main strategies to access the cache. Write-Through, Write-Around, and Write back.</p><p><strong>Write-Through</strong><br>In this strategy, all operations happen through the cache. When a write operation is performed, data is first written to the cache and then to the database. This strategy ensures that there is strong consistency between cache and Db. Write is considered successful only when the data is written to both cache and DB. This strategy is employed when we have a read-heavy system.</p><p><strong>Pros</strong>: Strong consistency is maintained. Preferred in read-heavy systems.</p><p><strong>Cons</strong>: <br>1. Write latency is higher as writes happen to both cache and DB.<br>2. Load on Db is higher as every write is performed on db.</p><p><strong>Real-world System Use Case</strong>:</p><p>Consider an online banking application where users frequently check their balance and perform transactions and data is written to both cache and db. Here write-through policy is used to ensure that there is no discrepancy between cache and persisted data. Why is write-through used here? Because we need a strongly consistent system here. If the user deposits the money in the bank and then checks his balance, and if it does not get reflected immediately, the user will lose his shit.</p><p><strong>Write Around</strong></p><p>In the write-around strategy, write operations completely bypass the cache and are directly performed on the database. Data in the cache from the db is only populated when there is a cache miss. This strategy is often employed when no of operations are write heavy but not frequently read.</p><p><strong>Pros</strong>: <br>1. Write latency is reduced as writes only happen to ddb.</p><p><strong>Cons</strong>:<br>1. Read latency is increased for cache miss data.</p><p><strong>Real-world use cases</strong>:</p><ol><li><em>Archival Systems</em>: In archival systems, data is write-intensive and rarely read. Emphasis is on preserving data for the future rather than optimizing read performance.</li><li><em>Log Analysis</em>: Applications are generating logs continuously and thus the data is write-intensive and seldom queried so in this case we can use this strategy.</li><li><em>Large Datasets</em>: In large datasets, where the data is write-intensive, this strategy is used to prevent the cache from overwhelming less frequently read data.</li></ol><p><strong>Write Back</strong></p><p>In the write-back cache strategy, data is written to the cache only. As soon as the data is successfully written to the cache, a successful response is sent. Data from the cache is then periodically synced with database asynchronously. This strategy is used when both read-heavy and write-heavy requests are present and tolerance for data loss is present.</p><p><strong>Pros</strong>:<br>1. Low latency for both read and write operations as we are only doing operations in cache.</p><p><strong>Cons</strong>:<br>1. Data is inconsistent as there is a delay in synchronizing cache and ddb.<br>2. There is a possibility for data loss if the cache goes down before the data is synced with the ddb.</p><p><strong>Real-world use cases</strong>:</p><p>Write write-back strategy is used in HFT(High-frequency trading) systems. This system demands extremely low latency and therefore whenever a write operation is performed, it is immediately acknowledged thereby improving the responsiveness of the trading system. Here eventual consistency model is followed where data is asynchronously written to the database. In HFT systems, speed and responsiveness are prioritized over consistency with the underlying data store.</p><p>The data structure used to implement cache is a hash table. We need a key, value, and hash function that will map the value to the appropriate bucket.</p><p>Working of a hash table is simple and intuitive. We calculate the hash value aka bucketId in which we need to store the element using the hashcode() method. Once the bucket is located, we store the element in that bucket. Here there is a possibility of collision. There are several strategies like separate chaining, open addressing for collision handling. Let’s discuss both of them in detail.</p><p><strong>Separate Chaining</strong> — In this strategy, we calculate the hashIndex and then append the element to the linked list of hashIndex. The drawback of this approach is that the linked list becomes large if there are sufficient collisions. Therefore periodic re-hashing should be performed to distribute the elements uniformly. In Java hash map implementation, initially, the elements will be appended in the linked list but if the size of the linked list grows then the linked list is converted to a balanced binary search tree which is more efficient for insertion and retrieval providing logarithmic time complexity. Separate chaining is used in database indexing to handle collisions.</p><p><strong>Open Addressing</strong> — In this strategy, we calculate the hash index. Then if the element is already present in that location, we start iterating forward and place the element in the first bucket that is empty. During retrieval we follow the same technique, we iterate over all the elements in a linear fashion until we find the desired element. This process is called linear probing because we are linearly iterating. The drawback of this approach is that clustering will happen. What do I mean by that? Clustering means that elements will be cluttered together and you will need to iterate over a large list to fetch the item which means read latency will increase. Therefore the choice of probing strategy is crucial to mitigate these concerns.</p><p>Distributed caching is done using a consistent hashing algorithm which is very efficient at distributing the load as well as minimizing the data movement. Let’s dive deep into how a consistent hashing algorithm works.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vwKcy4BvTJraRcBCUthEzg.png" /><figcaption>Consistent Hashing</figcaption></figure><p>Imagine a circular ring where the entire hash space is distributed on the ring. As you can see from the above diagram we have five servers on the ring. Each position on the ring represents a hash space. The position of the server on the ring is determined by calculating the hash value of the server identifier. Once the servers are mapped to the ring space, we calculate the position of the key-value pair on the ring using the same hash function. we move clockwise from that position and put the key-value pair in the first server that we encounter. Retrieval of data also works similarly. Now consider a scenario if one of the servers (Server 4) goes down. In this case, key 4 will now be mapped to Server 5. Notice that data movement is minimal and we only needed to change the position of a small subset of keys. This is the property that is very useful while designing scalable systems as new nodes can be easily added or removed with minimal data movement.</p><p><strong>Cache eviction policy</strong><br>We cannot keep all the data in the cache since cache is very expensive so we need to prioritize which data should be present in the cache and which data to remove. Generally LRU(Least recently used) policy is used to evict elements from the cache.</p><p>Lets explore the internal working of cache. Even though read and write operations are fast from RAM, calls are blocking. So what to do when there are n number of requests coming simultaneously. We can do two things in this case:<br>1. create new thread for each request which processes the request and returns a response. This method is generally not preferred due to several reasons. A large number of threads are created especially if the requests are short lived and each thread creation has associated overhead. Also as the capacity of new thread creation is limited, this is not scalable.<br>2. Put the requests in a queue and process them asynchronously. there will be a single threaded event loop which continuously polls the queue and assigns request to one of the worker threads. After assigning the request to the worker thread, it will poll another and the process continues. When the worker thread finish execution, it returns the response to the event loop which then returns back to the user.</p><p>How do we make our system fault tolerant. There are two approaches to make the system fault tolerant.</p><ol><li>Periodically sync the cache data to disk. When the cache goes down, the data in disk is used to reconstruct the cache.</li><li>Log reconstruction. Each operation is saved in the log file in append only manner and when the cache goes down, these operations are performed in sequence to reconstruct the cache.</li></ol><p><strong>How do we ensure High availability?</strong></p><p>We can have multiple copy of cache so that each replica can serve read/write requests. But here the challenge would be to maintain consistency between those replicas. So in order to avoid that problem, we can have one master node which does read/write operations and other nodes will perform read operations. We will have one zookeeper server which handles the responsibility of electing a new master node in case master node goes down.</p><p>That’s it from today&#39;s tutorial. Happy learning.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2ee5e25a5000" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[High-Level System Design for Amazon]]></title>
            <link>https://medium.com/@vaibhavkansagara/high-level-system-design-for-amazon-1aa18f3efd15?source=rss-910c9c12cd74------2</link>
            <guid isPermaLink="false">https://medium.com/p/1aa18f3efd15</guid>
            <category><![CDATA[lld]]></category>
            <category><![CDATA[hld]]></category>
            <category><![CDATA[amazon]]></category>
            <category><![CDATA[design-systems]]></category>
            <dc:creator><![CDATA[Vaibhav Kansagara]]></dc:creator>
            <pubDate>Wed, 10 Jan 2024 15:54:03 GMT</pubDate>
            <atom:updated>2024-01-10T15:54:03.137Z</atom:updated>
            <content:encoded><![CDATA[<p>Today we are going to deep dive into how Amazon works. Amazon is a huge company comprising several big businesses such as retail, prime, Alexa, amazon business, etc. Today we will focus on how Amazon&#39;s online retail business works under the hood and what makes the retail platform great. I am sure you will find tens of articles like this on the internet but in this article, I will be a narrator instead of a passive tone and will be actively providing examples from my real-world experience of working with highly distributed systems, so hop on for an interesting journey. The only drawback of reading this article is that it is going to take some time so be patient as we will be going through a lot more detail instead of just skimming through the surface. This Article is written based on the “CODEKARLE” System Design Series so I will be borrowing some of the design diagrams.</p><p><strong>Functional Requirements:</strong></p><ol><li>Provide Search functionality with a delivery ETA<br>Here we will explore how search functionality is implemented, how it integrates with the rest of the ecosystem, and what real-world search algorithms are used. How fast is the ETA updated etc?</li><li>Provide a Catalog of all products.<br>Here we will explore how product catalog view is dynamically updated and personalized based on user profile and user behaviour.</li><li>Provide Cart and WishList features.<br>Here we will explore how cart and wishlist features are implemented, and how it is integrated with a notification system to notify customers that a particular item is now available.</li><li>Handle Payment flow smoothly.<br>Here we will talk about how payment services work, how different currencies are supported, and how payment fraud detection works.</li><li>Provide order history view.<br>Here we will talk about what services are involved in rendering the order history page which displays the order date, items purchased, order status, etc.</li></ol><p><strong>Non Functional Requirements:</strong></p><ol><li>Low Latency<br>Why do we need this? Ughhh. Isn’t it obvious? The thing to keep in mind is that not all services require low latency. We will discuss in detail what services have a strict requirement of low latency.</li><li>High Availability<br>Why do we need this? Amazon serves millions of customers every second. Imagine if the service was down for a few minutes, it could easily cost millions of dollars. On a personal note, I have worked on systems that serve a few thousand customers per hour and was responsible for causing one outage that lasted a few hours and impacted 3000 customers so this one hits close to home. Details of the outage will be a story for a different article.</li><li>High Consistency<br>Why do we need this? Amazon has a vast inventory comprising millions of products. If the system is not consistent, the same product could be sold to multiple customers. Another area where high consistency is needed is to handle financial data to avoid problems like double billing or payment failures.</li></ol><p>Now we will divide the HLD into two parts. First, we will discuss Home/Search Flow and secondly, we will discuss Purchase/Checkout Flow.</p><p><strong>Home/Search Flow:</strong></p><p>Before we start drawing random diagrams about services used for implementing Search functionality, think about where the data is coming from. The data that you see on the home page or when you search for something comes from the seller. So for Amazon, the seller is the producer of the data. We need a set of systems that interact with sellers and onboard their products onto our platform. Let’s call this collection of services “Inbound” services which will take input from sellers and through these services, data will flow into <strong>Kafka</strong> and then onto the homepage and search page. Hold on, WTF is KafKa. Officially Kafka is a distributed event streaming platform. Kafka serves as a central hub aka “post office” where different parts of the software can send and receive messages. For our use case, inbound service will publish an event into KafKa saying “Hey one of the sellers needs to onboard one product to the platform. Is anybody interested? If you are then subscribe to me, and then you can get the details of the product”. These events will be listened to by Search services to further show them to the potentially interested end customers.</p><p>Let&#39;s dive deep into what services are part of inbound services. Inbound services consist of three services.</p><p>1. Seller Onboarding Service — Handles registration of new sellers, collecting and validating seller information. There are several APIs that will be exposed. Let&#39;s talk about a few of them.</p><ul><li><strong>Register Seller</strong><br>EndPoint: <strong>POST</strong><em> /api/seller/register</em><br>Description: Allows a new seller to register on Amazon with business details, contact info, and authentication credentials.</li><li><strong>Login for Seller</strong><br>EndPoint: <strong>POST</strong> <em>/api/seller/login</em><br>Description: Allows sellers to log in with the credentials created in the registration step.</li><li><strong>Update Seller Information</strong><br>EndPoint: <strong>PUT</strong> <em>/api/seller/{sellerId}</em><br>Description: Allows sellers to update their information like business details, contact info, or authentication credentials.</li></ul><p>2. Product Onboarding Service — Allows sellers to add/update/delete products on the platform seamlessly.</p><ul><li><strong>Onboard Product</strong><br>EndPoint: <strong>POST</strong> <em>/api/product/onboard</em><br>Description: Allows onboarding of product with product name, images, price, inventory information, etc.</li><li><strong>Retrieve Product information</strong><br>EndPoint: <strong>GET</strong> <em>/api/product/{productId}</em><br>Description: Retrieves detailed information about specific products based on productId.</li><li><strong>Update Product information</strong><br>EndPoint: <strong>PUT</strong> <em>/api/product/{productId}</em><br>Description: Updates product information like product name, images, and price based on product ID.</li></ul><p>3. Image Processing Service —Handles and optimizes images associated with the products.</p><ul><li><strong>Upload image</strong><br>EndPoint: <strong>POST</strong> <em>/api/images/upload</em></li><li><strong>Upload multiple images</strong><br>EndPoint: <strong>POST</strong> <em>/api/images/upload-multiple</em></li><li><strong>Resize image</strong><br>EndPoint: <strong>POST</strong> <em>/api/images/resize</em></li><li><strong>Compress image</strong><br>EndPoint: <strong>POST</strong> <em>/api/images/compress</em></li><li><strong>Crop image</strong><br>EndPoint: <strong>POST</strong> <em>/api/images/crop</em></li></ul><p>One of the consumers of these events is “Items Service”. This service will consume the events, onboard new items, and update the inventory. It will also expose APIs to add, update, and delete items. It will then store the data in MongoDB, DynamoDB, or any NoSQL DB. Why? Because the item data is fundamentally unstructured. Different items have different attributes for ex: a shirt has size, fabric, and color attributes whereas a TV has width, length, resolution, weight, color technology, etc.</p><p>Let’s dive deep into what the MongoDB schema might look like.</p><pre>{<br>  &quot;_id&quot;: ObjectId(&quot;unique_item_id&quot;),<br>  &quot;name&quot;: &quot;Item Name&quot;,<br>  &quot;type&quot;: &quot;ItemType&quot;,<br>  &quot;attributes&quot;: {<br>    &quot;attribute1&quot;: &quot;value1&quot;,<br>    &quot;attribute2&quot;: &quot;value2&quot;,<br>    // Additional attributes based on item type<br>  },<br>  &quot;created_at&quot;: ISODate(&quot;timestamp&quot;),<br>  &quot;updated_at&quot;: ISODate(&quot;timestamp&quot;)<br>}</pre><p>As you can see from the schema, there are itemId, itemName, itemType, created_at, and updated_at fields but the most important field is “attributes” which allows flexibility in having different sets of attributes for different item types.</p><p>Once the event for onboarding an item is published, it is consumed by “Search Consumer”. Search consumer reads and process new items and formats the data which can be stored in a database and can be easily understood by the search system. After formatting the data, the search consumer will put the data into ElasticSearch. ElasticSearch is used here as it is very efficient for text-based search and it also supports fuzzy search. There is a lot of information packed here. Let’s dive deep into how exactly it works.</p><p>Let’s first understand how the formatting of the data takes place. Formatting of the data involves six major steps which are as follows.</p><ol><li><strong>Attribute Extraction</strong><br>Extract attributes from the item data like itemName, description, category, etc.</li><li><strong>Data Normalization</strong><br>data normalization means to ensure consistency. text is converted to lowercase and necessary whitespace is removed.</li><li><strong>Tokenization<br></strong>tokenization means splitting the text into separate words aka tokens. ElasticSearch uses these tokens to index the data.</li><li><strong>Removal of Stop words<br></strong>Stop words are those words that have no significance on their own. Words like “is”, “the”, and “an” add noise so it is necessary to remove such words.</li><li><strong>Stemming<br></strong>Stemming is the process of converting words to their root form. Ex: running -&gt; run.</li><li><strong>Geocoding<br></strong>Geocoding is a process of converting addresses into coordinates. Amazon uses geocoding to ensure that you cannot order products to undeliverable locations. Your address is converted to coordinates and when you visit the homepage or search page, you are only shown those products that are deliverable to your location.</li></ol><p>Once the data is formatted and described, it is fed into ElasticSearch. Why are we using ElasticSearch? We will not dive too deep into how ElasticSearch works but let’s discuss some of the functionality that ElasticSearch provides.</p><p>ElasticSearch provides two major functionalities that we need in this design.</p><ol><li><strong>Full-Text Search</strong><br>This is the core feature of elastic search. This allows users to query elastic search based on words, phrases, or complex queries in the text.</li><li><strong>Fuzzy Search</strong><br>Fuzzy search allows for minor spelling mistakes to be overlooked and search words that are close to the word that is searched.</li><li><strong>Geo-based Search</strong><br>Elastic search supports geo search which allows us to make spatial queries such as finding items that are within a certain distance.</li></ol><p>Search Service sits on top of ElasticSearch and it exposes APIs for filtering, sorting, and searching the products.</p><p>API exposed by search service:<br>EndPoint: <strong>POST</strong> <em>/api/products/search</em><br>Sample request:</p><pre>{<br>  &quot;query&quot;: &quot;laptop&quot;,<br>  &quot;filters&quot;: {<br>    &quot;category&quot;: &quot;Electronics&quot;,<br>    &quot;price_range&quot;: {&quot;min&quot;: 500, &quot;max&quot;: 2000}<br>  },<br>  &quot;sort_by&quot;: &quot;price_asc&quot;,<br>  &quot;user_location&quot;: {<br>    &quot;pin_code&quot;: &quot;123456&quot;,<br>    &quot;coordinates&quot;: {&quot;latitude&quot;: 40.7128, &quot;longitude&quot;: -74.0060}<br>  }<br>}</pre><p>The above query is done with the laptop keyword with filters specifying category, price_range. After that, the results are sorted in ascending order and shown to the user. Here location information is used for determining whether the product is deliverable or not.</p><p>Sample response:</p><pre>{<br>  &quot;results&quot;: [<br>    {<br>      &quot;product_id&quot;: &quot;123&quot;,<br>      &quot;name&quot;: &quot;Laptop X&quot;,<br>      &quot;description&quot;: &quot;Powerful laptop for work and gaming&quot;,<br>      &quot;price&quot;: 1200,<br>      &quot;serviceable&quot;: true,<br>      &quot;delivery_date&quot;: &quot;2024-02-15&quot;<br>    },<br>    // Other products...<br>  ]<br>}</pre><p>A question should come to your mind, how does search service determine whether the product is serviceable to your location or not? Search service delegates this task to “Serviceability and TAT service” which is responsible for providing a boolean value indicating whether the product is deliverable or not to your location and if yes then provide the delivery ETA. In the above response, Serviceability and TAT service populates the “serviceable” and “delivery_date” fields.</p><p>With this, our first functional requirement is over and you can take a deep sigh. I know you are tired, I feel you brother but don’t give up just yet. Next, we will talk about Cart and WishList features.</p><p>For the Cart and WishList feature, we have two services Cart Service and WishList Service. Cart Service is a repo of all products in the cart and WishList Service is a repo of all products in the wishlist. Both are built similarly and provide similar APIs to fetch, update, and delete items from the respective list. Both use MySQL as a database to store the lists. Why do we use MySQL here? We need ACID properties mainly atomicity and consistency. Let’s look at the schema of Cart MySQL DB.</p><pre>CREATE TABLE Users (<br>    UserID INT PRIMARY KEY,<br>    UserName VARCHAR(255) NOT NULL<br>);<br><br>CREATE TABLE CartItems (<br>    CartItemID INT PRIMARY KEY,<br>    UserID INT,<br>    ProductID INT,<br>    Quantity INT,<br>    ItemName VARCHAR(255) NOT NULL,<br>    CONSTRAINT fk_user FOREIGN KEY (UserID) REFERENCES Users(UserID)<br>);</pre><p>Here CartItems table has a foreign key connecting to the users table. Let’s look at how atomicity plays into the picture here. Consider the below transaction</p><pre>START TRANSACTION;<br>INSERT INTO CartItems (UserID, ProductID, Quantity, ItemName) VALUES (1, 101, 1, &#39;Product A&#39;);<br>COMMIT;</pre><p>Without atomicity, if the insert operation fails or is interrupted, then the database will be in an inconsistent state. To safeguard against that we perform insert operation as a transaction meaning it will be executed wholly or not at all.</p><p>Another question might pop into your head. Why have we kept separate tables for cart and wishlist? Can’t we combine both of them into a single table and keep a flag for distinguishing items that are in the cart or wishlist? The answer is really simple. we have kept the db separate as the wishlist tends to be much longer than the cart table and in times of sales like Black Friday, and Diwali, the wishlist tends to grow much higher than the cart so if we keep it separate, we can also scale the db separately. With this one of our functional requirements is taken care of.</p><p>All these services will be sending events to Kafka continuously and based on what users are searching for, a recommendation system is built which will provide personalized recommendations to the users as well as generalized recommendations if the user is not logged in.</p><p>There is a spark streaming consumer that consumes the event from the various Kafka topics and generates real-time reports like which product is the most bought in the last 1 hour or day, the most wish-listed items, the location where most of the orders are coming from, etc. Let&#39;s dive deep into how spark streaming consumer works. The best way to understand is through an example.</p><p>Input that spark streaming consumer consumes from various Kafka topics</p><pre>// Input to Spark Streaming consumer from various Kafka topics.<br>{<br>  &quot;eventType&quot;: &quot;purchase&quot;,<br>  &quot;timestamp&quot;: &quot;2024-01-10T12:30:45&quot;,<br>  &quot;userID&quot;: &quot;user123&quot;,<br>  &quot;productID&quot;: &quot;product789&quot;,<br>  &quot;quantity&quot;: 2<br>}</pre><p>The input contains data about what type of event was performed, the timestamp of the event, the user who initiated the event, a product that was purchased, quantity, etc. Let’s now see the processing logic of the spark consumer.</p><pre>// specifies metadata of kafka brokers<br>val kafkaParams = Map(&quot;metadata.broker.list&quot; -&gt; &quot;kafka-broker1:9092,kafka-broker2:9092&quot;)<br><br>// specifies set of kafka topics to subscribe<br>val topics = Set(&quot;user-interactions-topic&quot;)<br><br>// creates direct kafka stream.<br>// First two parameters are key type and value type.<br>// Third and fourth paramters are decoder for key and value respectively.<br>val kafkaStream = KafkaUtils.createDirectStream[String, String, StringDecoder, StringDecoder](<br>  streamingContext, kafkaParams, topics<br>)<br><br>val parsedData = kafkaStream.map(record =&gt; parse(record.value()))<br><br>// Filter and aggregate purchase events to find popular products<br>val popularProducts = parsedData<br>  .filter(data =&gt; data.eventType == &quot;purchase&quot;)<br>  .map(data =&gt; (data.productID, 1))<br>  .reduceByKey(_ + _)<br>  .transform(_.sortBy(_._2, ascending = false))<br><br>// Output the popular products to the console<br>popularProducts.print()</pre><p>Below is the output from the spark streaming consumer</p><pre>-------------------------------------------<br>Time: 2024-01-10 12:31:00<br>-------------------------------------------<br>(product789, 5)<br>(product123, 3)<br>(product456, 2)<br>...</pre><p>I hope by now you get a clear idea about every system I have talked about. In System Design it is important to dive deep into each topic instead of skimming through the surface and that is why detail matters. Once you have studied every system in detail and if you know how each system works under the hood, you won’t even have to memorize it, it will come automatically and naturally.</p><p>Data that we got from the spark streaming consumer is dumped into the Hadoop cluster. Algorithms like ALS(Alternating least squares) are run on the data to generate recommendations. ALS will generate recommendations based on past purchases, wishlists, user interactions, and items bought by similar users and create a mapping between users and products.</p><p>After this, a spark cluster will collect the recommendations and those recommendations into Kafka. These events will be listened to by a recommendation service which will store this data into Cassandra. What kind of recommendations will be saved? Two types of recommendations will be saved. Personalized recommendations based on userId and personalized recommendations based on userId as well as categoryId. Let’s explore the schema of the Cassandra database which stores the recommendations.</p><pre>CREATE TABLE IF NOT EXISTS user_recommendations (<br>  user_id UUID,<br>  category_id UUID,<br>  recommended_product_ids LIST&lt;UUID&gt;,<br>  confidence_scores LIST&lt;DOUBLE&gt;,<br>  PRIMARY KEY (user_id, category_id)<br>);</pre><p>The primary key is a combination of user_id and category_id. This way we can query the user_id for general recommendations and on category_id for category-specific recommendations.</p><p>The next Component is User Service. User service sits on top of Mysql db and contains user profile information. User service exposes APIs to add, modify, and delete users. Since a lot of services have a dependency on user service, user service receives a lot of traffic. Most of the requests will be read-heavy and here we can do one optimization and include Redis cache to reduce the load on MySQL DB. One such example is when a search service wants the user&#39;s PIN code to determine whether it should show the product as serviceable or not. It will query the Redis cache first. If the user data is not present, then it will fetch the data from MySQL DB and update the cache. Let’s look into the schema of User Mysql db.</p><pre>CREATE TABLE IF NOT EXISTS users (<br>  user_id INT AUTO_INCREMENT PRIMARY KEY,<br>  name VARCHAR(255) NOT NULL,<br>  email VARCHAR(255) UNIQUE NOT NULL,<br>  password_hash VARCHAR(255) NOT NULL,<br>  pin_code VARCHAR(10),  -- Assuming a 6-digit pin code<br>  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,<br>  updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP<br>);</pre><p>Let’s discuss next how the ETA for the product delivery is calculated. ETA calculation step can be divided into two steps.<br>1. Find the optimal warehouse which has the product. Warehouse Service comes into the picture here. It is a repo of all warehouses with a list of all products that are present in the warehouse.<br>2. Find the path to the user from the warehouse from the first step. Serviceability and TAT service will connect with Logistics Service to find out all delivery courier partners and finally calculate the ETA for the product delivery.</p><p>Let&#39;s dive deep into DB schema for Warehouse and Logistics Services.</p><p>Logistics Service DB Schema</p><pre>CREATE TABLE IF NOT EXISTS courier_partners (<br>  partner_id INT AUTO_INCREMENT PRIMARY KEY,<br>  partner_name VARCHAR(255) NOT NULL,<br>  serviceable_pin_codes TEXT,  -- Comma-separated list of serviceable pin codes<br>  delivery_routes TEXT,  -- JSON or serialized data representing delivery routes<br>  capabilities TEXT,  -- JSON or serialized data representing partner capabilities<br>  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,<br>  updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP<br>);</pre><p>logistics db contains information like partner_id, partner_name, list of serviceable pin codes, delivery routes, etc. “delivery_routes” JSON contains the ETA that we need.</p><p>Warehouse Service DB Schema</p><pre>CREATE TABLE IF NOT EXISTS Warehouses (<br>  warehouse_id INT AUTO_INCREMENT PRIMARY KEY,<br>  location VARCHAR(255) NOT NULL,<br>  capacity INT,<br>  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,<br>  updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP<br>);</pre><pre>CREATE TABLE IF NOT EXISTS ProductsInWarehouse (<br>  product_id INT AUTO_INCREMENT PRIMARY KEY,<br>  warehouse_id INT,  -- Foreign key referencing Warehouses<br>  product_name VARCHAR(255) NOT NULL,<br>  quantity INT,<br>  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,<br>  updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,<br>  FOREIGN KEY (warehouse_id) REFERENCES Warehouses(warehouse_id)<br>);</pre><p>As you can see from the above, the warehouse service has two tables. One contains the information about the warehouse, its location, and its capacity. Another table contains the product information and warehouse ID in which it is present. “warehouse_id” in the table ProductsInWarehouse references the warehouse table.</p><p>One thing to note here is that none of these calculations will happen at runtime. ETA information is precalculated for each product item and cached to retrieve with minimal latency. With this, we complete the Home and search flow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AMLQwXMGqlTSNUxKYiLWAQ.png" /><figcaption>Search/HomePage Flow</figcaption></figure><p>Now Let’s talk about Purchase and checkout flow.</p><p>Following are the steps that happen when the user places an order.</p><ol><li>The user initiates an Order.</li><li>Order-taking service validates users&#39; requests and authenticates the customer.</li><li>Before the database is modified, the order-taking service initiates a transaction. This is done to ensure that the entire process is treated as an atomic operation so that the database does not remain in an inconsistent state.</li><li>Order-taking service creates a record in REDIS cache with order details like orderId, itemCount, total amount, expriy_time, and status — initially “created”.</li><li>Check Item Availability<br>Order-taking service checks if the item is available in the items table to see if the quantity count is greater than zero. If the item is available then the item count is decreased. Also, the status in Redis is changed to “inventory_updated”.</li><li>Redirection to payment flow<br>The user is redirected to the payment flow. If the payment flow is successful, then the status in Redis is changed to “payment_successfull”.</li><li>A record in the order table is created with details like orderId, List&lt;productName&gt;, quantity, timestamp, etc.</li><li>If all the steps in the transaction are successful, then the transaction is committed. Once the transaction is committed, the record in the Redis cache is deleted.</li></ol><p>As you can see, we need strong consistency here and ACID properties.<br><strong>Atomicity</strong> — the whole transaction is executed or none of it is executed.<br><strong>Consistency</strong> — DB remains in a consistent state always.<br><strong>Isolation</strong> — multiple orderId entries do not interfere with each other therefore ensuring isolation.<br><strong>Durability</strong> — Once the transaction is complete, changes are permanent and will survive system failure.</p><p>The need for ACID properties means we use Mysql db for the items table and orders table.</p><p>Now a question will come to your mind. Why are we updating the inventory count before the payment flow? If the payment is complete and the user gets to know that the item is not available, the user will be frustrated and overall it will be a bad user experience. So if there is only one item available and three users are trying to buy the item at the same time. Only one will be able to get past the payment flow. The rest of the two users&#39; flow will end before going to the payment page therefore preventing frustration.</p><p>Let’s explore the payment flow in more detail. There are three scenarios in payment flow. payment success, payment failure, and no response.</p><p><strong>Payment Success Flow:</strong></p><ol><li>payment is initiated at 10:01 and expiry in Redis is kept at 10:05.</li><li>The payment success response is received at 10:03.</li><li>payment status in Redis and the order table is updated to “complete”. Transaction is committed.</li><li>Notification is sent to the user that the payment is successful and the order is placed.</li></ol><p><strong>Payment Flow Failure:</strong></p><ol><li>payment is initiated at 10:01 and expiry in Redis is kept at 10:05.</li><li>payment failure is received at 10:03.</li><li>the transaction is rolled back and the inventory count is increased.</li><li>user is notified of payment failure.</li></ol><p><strong>No Response:</strong></p><ol><li>Payment is initiated at 10:01 and expiry in Redis is kept at 10:05.</li><li>User closes the browser before the payment is complete.</li><li>record in Redis expires at 10:05.</li><li>Order-taking service initiates failure flow. Flow after this is the same as failure flow in which transaction is rolled back and inventory count is increased.</li></ol><p><strong>Race Condition Mitigation:</strong></p><p>We need to address a scenario when both payment success and Redis expiry happen at the same time. If the expiry happens before and payment success happens afterward, we have two options.</p><ol><li>Refund the user and notify of the order canceled status. This is not the ideal option as we are taking the joy out of the customer.</li><li>The system places the order on the user&#39;s behalf and notifies the user of payment success and order completion status.</li></ol><p>Since Amazon has millions of customers and they keep ordering items so order and items MySQL db will grow very quickly. Mysql db is not very efficient at scaling compared to NoSql Dbs. So we need to do some optimization here. Take a pause here and think about how you can reduce the amount of data that needs to be stored in MySQL DB.</p><p><strong>Hint</strong>: Think about different types of order status and how you can segregate the records based on order status.</p><p><strong>Answer</strong>: Orders that are in a completed or canceled state will not have any updates and therefore will become stale data. Where to move the stale data. You can move the stale data to NoSQL dbs like Cassandra.</p><p>We will have a Historical Order service which will sit on top of Cassandra and expose APIs to add, fetch, update, and delete order records from Cassandra. We will have an archival service that will transfer the data from MySQL to Cassandra once the order moves into the terminal state(completed or canceled). Let’s explore how does Archival service transfers terminal state orders from MySQL to Cassandra. Below is the query that the archival service will use to fetch terminal orders from orders MySQL DB.</p><pre>SELECT *<br>FROM orders<br>WHERE status IN (&#39;delivered&#39;, &#39;canceled&#39;)<br>  AND archival_status = &#39;pending&#39;;</pre><p>After extracting terminal orders, the archival service talks with the historical orders service to bulk-write the data to Cassandra. Batch operations are used for efficient writes to Cassandra DB.</p><p>Once the orders are successfully archived into Cassandra, the archival service again talks to order taking service to delete orders that are successfully archived. It marks the “archival_status” field as “archived” and then executes the below query to remove all terminal orders.</p><pre>DELETE FROM orders<br>WHERE archived_status = &#39;archived&#39;;</pre><p>Now the last requirement is to show the order detail view to the users. To do that we need to fetch all past orders as well as ongoing orders. Order detail service will query both order order-taking service to fetch ongoing orders and the query historical orders service to fetch past orders. There will be separate queries and both results will be combined in application-level logic.</p><p><strong>Query for retrieving orders from the order-taking service:</strong></p><pre>-- Query to fetch ongoing orders from Order Taking Service (SQL)<br>SELECT order_id, user_id, order_status, order_date<br>FROM order_taking_service.ongoing_orders<br>WHERE order_status = &#39;ongoing&#39;; </pre><p><strong>Query for fetching orders from historical orders service:</strong></p><pre>-- Query to fetch ongoing orders from Order Taking Service<br>-- Here Cassandra query language is used which is similar to SQL.<br>SELECT order_id, user_id, order_status, order_date<br>FROM order_taking_service.ongoing_orders<br>WHERE order_status = &#39;ongoing&#39;;</pre><p><strong>Application level logic for combining both types of orders:</strong></p><pre># Pseudocode to combine ongoing and terminal orders in your application code<br>ongoing_orders_sql = execute_sql_query(&quot;SELECT order_id, user_id, order_status, order_date FROM order_taking_service.ongoing_orders WHERE order_status = &#39;ongoing&#39;&quot;)<br>terminal_orders_cassandra = execute_cassandra_query(&quot;SELECT order_id, user_id, order_status, order_date FROM historical_orders_service.terminal_orders WHERE order_status IN (&#39;completed&#39;, &#39;canceled&#39;)&quot;)<br><br>combined_orders = merge_orders(ongoing_orders_sql, terminal_orders_cassandra)py</pre><p>Last but not least, there is a Notification Service that takes the responsibility of notifying the customer whenever the order status changes, payment status changes, delivery status changes, etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nCOeakK0ZTDc3CA9608ZYQ.png" /><figcaption>Purchase/Checkout Flow</figcaption></figure><p>With this, you can take a sigh of relief. The article is finally over.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1aa18f3efd15" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>