<?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 Shivam Sinha on Medium]]></title>
        <description><![CDATA[Stories by Shivam Sinha on Medium]]></description>
        <link>https://medium.com/@shivam-sinha?source=rss-a74f7b448497------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*0ld317GkDkNhwKH9E-DLIA.jpeg</url>
            <title>Stories by Shivam Sinha on Medium</title>
            <link>https://medium.com/@shivam-sinha?source=rss-a74f7b448497------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 23:58:07 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@shivam-sinha/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Design Elastic Search]]></title>
            <link>https://shivam-sinha.medium.com/design-elastic-search-8392d3c50e00?source=rss-a74f7b448497------2</link>
            <guid isPermaLink="false">https://medium.com/p/8392d3c50e00</guid>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[high-level-design]]></category>
            <category><![CDATA[design-systems]]></category>
            <category><![CDATA[search-engines]]></category>
            <category><![CDATA[elasticsearch]]></category>
            <dc:creator><![CDATA[Shivam Sinha]]></dc:creator>
            <pubDate>Tue, 30 Apr 2024 13:54:57 GMT</pubDate>
            <atom:updated>2024-11-15T06:40:05.158Z</atom:updated>
            <content:encoded><![CDATA[<p>Elasticsearch is a search engine based on the Lucene library. It provides a distributed, multitenant-capable full-text search engine with an HTTP web interface and schema-free JSON documents.</p><h4>Functional Requirements:</h4><ol><li>Search documents with given queries. (Full Text Search)</li><li>Find top documents (Ranking).</li></ol><h4>Non-Functional Requirements:</h4><ol><li>We have billions of documents.</li><li>Eventual Consistency. (It’s okay if new documents are included in search queries later.).</li><li>Highly Available.</li></ol><h4>Examples:</h4><ol><li>E-commerce Website: Review Search, Product Search</li><li>Social Media: Search bar (Post, comment, tweets)</li><li>Search Engine</li></ol><h4>Jamboard Link</h4><p><a href="https://jamboard.google.com/d/11qDh6ds-giA0AOJQ9IVYivPFaII1W1eQjOujJxq2K90/edit?usp=sharing">Elastic search - Google Jamboard</a></p><h3>Design Deep Dive/Decision</h3><h4>How to store Documents:</h4><p>We will store documents in the form of an inverted index.</p><p>Let’s see examples of how this is being stored:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eUfXRkf2hc5NuLZqdNY2xA.png" /><figcaption>Inverted Index Example</figcaption></figure><p>Inverted Index (HashMap):</p><ol><li>Product -&gt; [(1,4), (2,0), (3,0)]</li><li>Using -&gt; [(1,2)]</li><li>Working -&gt; [(1,8)]</li><li>Nice -&gt; [(1,9)]</li><li>Great -&gt; [(2,2)]</li><li>Feature -&gt; [(2,4)]</li><li>OverPriced -&gt; [(3,2)]</li></ol><h4>Documents often contain numerous unnecessary words. Let’s explore ways to remove them.</h4><ol><li>Remove Stop Words: Useless words that appear often. of, the, are, a, of etc.</li><li>Stemming/Lemmatization</li><li>Other Cleaning Methods: Removing negative/abusive/sensitive words.</li></ol><p>Stemming: It’s fast and simple.</p><ol><li>Escaped -&gt; Escap</li><li>Escaping -&gt; Escap</li><li>Escape -&gt; Escap</li><li>Caring -&gt; Car</li></ol><p>Lemmatization: It takes context into account.</p><ol><li>Caring -&gt; Care</li><li>Escaping -&gt; Escape</li></ol><h4>Example of Search Query:</h4><ol><li><strong>Search Query:</strong> The Product Quality is great.</li><li><strong>Cleaning: </strong>product quality great.</li><li><strong>Intersection:</strong> Find all the docs with all the words.</li><li><strong>Union:</strong> Find all docs that contains any of the word.</li><li><strong>Maintain Order of words:</strong> [product — i, quality — i+1, great — i+2]</li></ol><h3>Processing</h3><h4>Single Node:</h4><ol><li>It can cause Single Point of Failure.</li><li>Run Out of space.</li><li>High Load</li><li>Solution: Sharding.</li></ol><h4>CAP Theorem:</h4><ol><li>Eventual Consistency: It’s okay if new documents are included in search queries later.</li><li>High Availability: System Should be available, whenever we search something.</li><li>Partition Tolerant: System should handle any network partitions, it should continue to work despite any number of communication breakdowns.</li></ol><h3>Sharding:</h3><h4>Shard by Document Id [Recommended]:</h4><p>DocumentId can be:</p><ol><li>ReviewId</li><li>LogId</li><li>ProductId</li><li>PostId/TweetId</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LqOsqEC3L-dNQ53b8ymonQ.png" /><figcaption>Shard by DocumentId</figcaption></figure><p><strong>Pros:</strong></p><ol><li>Latency is highly predictable: ResponseTime doesn’t depend on search query.</li><li>No need to perform intersection.</li><li>Can skip unresponsive/slow shards.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/241/1*t5lBtAouPKlygHh4dATiAg.png" /><figcaption>Skip Unresponsive/Slow Shards</figcaption></figure><p><strong>Cons:</strong></p><ol><li>Read Heavy: Complexity (Run on all shards)</li><li>Write Heavy: Simple (1 Shard)</li></ol><h4>Shard by Words:</h4><ol><li>Insert/update/Delete: Go to all shards corresponding to the words in the document. (Multiple Shards)</li><li>Query: Go to all shards</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y5Gsx-B8Y-7LL3I9hKexQg.png" /><figcaption>Word Sharding</figcaption></figure><h3>Let’s See How Processing will Work:</h3><h4>Map Reduce:</h4><ol><li><strong>Search: </strong>“product quality good”, Go to all shards -&gt; Run query at every shards.</li><li>Each shards will return a list of docs that matches the query.</li><li>Collect them all.</li><li>Items: Map(Single Shard), Reduce(Combine result from 2 shards) -&gt; Easy to fit in a memory.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AvtiS7p8bjB6oyImAN2foA.png" /><figcaption>Map Reduce</figcaption></figure><h4>Replication:</h4><ol><li>It will be good to have replication in case a node goes down.</li><li><strong>Parameter:</strong> Number of shards, Replication factor.</li><li>n -&gt; number of nodes, M -&gt; shards, R -&gt; replication factor</li><li>n ≤ M*R</li><li><strong>Master Slave Replication</strong></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OFfJiSd5H8fsoH2MwKfSPA.png" /><figcaption>Replication</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*ne3OUExSoBbTXV0slMh52A.png" /><figcaption>Master Slave Replication</figcaption></figure><h4>Ranking:</h4><ol><li>Rank all the document matches a certain query.</li><li><strong>Method: TF-IDF, is a popular method.</strong></li></ol><p><strong>TF-IDF (Below Diagram):</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EFQ4kjQlGA3DPWG66AdQqA.png" /><figcaption>TF-IDF</figcaption></figure><p>ThankYou. Please do give suggestions.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8392d3c50e00" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Design Notification System]]></title>
            <link>https://shivam-sinha.medium.com/design-notification-system-270506e944e0?source=rss-a74f7b448497------2</link>
            <guid isPermaLink="false">https://medium.com/p/270506e944e0</guid>
            <category><![CDATA[notifications]]></category>
            <category><![CDATA[design-systems]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[notification-service]]></category>
            <category><![CDATA[high-level-design]]></category>
            <dc:creator><![CDATA[Shivam Sinha]]></dc:creator>
            <pubDate>Sun, 10 Dec 2023 15:44:41 GMT</pubDate>
            <atom:updated>2023-12-10T15:44:41.904Z</atom:updated>
            <content:encoded><![CDATA[<p>The Notification System alerts users with important information, including breaking news, product updates, events, offerings, etc. Notifications can be delivered through mobile push notifications, SMS messages, or emails.</p><h3>Functional Requirements:</h3><ol><li>Different types of notifications (SMS, Email, Mobile Push)</li><li>Real-Time System (A slight delay is acceptable)</li><li>Subscription (User can opt-in/opt-out)</li></ol><h3>Non-Functional Requirements:</h3><ol><li>Highly Scalable (Sends out millions of notifications in a day.)</li><li>Supports multiple Devices (IOS, Android, Laptop/Desktop)</li><li>Reliable</li></ol><h3>Types of Notification:</h3><ol><li>SMS</li><li>Email</li><li>Mobile Push (IOS, Android)</li></ol><h3>Notification Component:</h3><ol><li>Provider: Build and Send notification to notification service.</li><li>Device Token: Unique Identifier used for sending push notifications.</li><li>Payload: JSON, contains notification <a href="https://developer.apple.com/library/archive/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/CreatingtheNotificationPayload.html">payload</a>.</li><li>Notification Service: Sends notifications to clients.</li><li>Client (Mobile Devices/Emails)</li></ol><h4>IOS Push Notification:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/585/1*JB4ROhZjLL8rjmJIEz4aXg.png" /><figcaption>IOS Notification Flow</figcaption></figure><p><a href="https://developer.apple.com/documentation/usernotifications/registering_your_app_with_apns"><strong>APNs</strong></a>: Apple Push Notification Service, a remote service Apple provides to propagate push notifications to IOS.</p><h4>Android Push Notification:</h4><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Fshivam04%2Fembed%2Fpreview%2FGRzeLpr%3Fdefault-tabs%3Dhtml%252Cresult%26height%3D600%26host%3Dhttps%253A%252F%252Fcodepen.io%26slug-hash%3DGRzeLpr&amp;display_name=CodePen&amp;url=https%3A%2F%2Fcodepen.io%2Fshivam04%2Fpen%2FGRzeLpr&amp;image=https%3A%2F%2Fshots.codepen.io%2Fusername%2Fpen%2FGRzeLpr-512.jpg%3Fversion%3D1702218080&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/9a7e8039425ab4cc269ced8f506340e2/href">https://medium.com/media/9a7e8039425ab4cc269ced8f506340e2/href</a></iframe><p><a href="https://firebase.google.com/docs/cloud-messaging"><strong>FCM</strong></a><strong>: </strong>Firebase Cloud Messaging sends push notifications to Android devices.</p><h4>SMS Message:</h4><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Fshivam04%2Fembed%2Fpreview%2FwvNOZMr%3Fdefault-tabs%3Dhtml%252Cresult%26height%3D600%26host%3Dhttps%253A%252F%252Fcodepen.io%26slug-hash%3DwvNOZMr&amp;display_name=CodePen&amp;url=https%3A%2F%2Fcodepen.io%2Fshivam04%2Fpen%2FwvNOZMr&amp;image=https%3A%2F%2Fshots.codepen.io%2Fusername%2Fpen%2FwvNOZMr-512.jpg%3Fversion%3D1702218285&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/2b24885d3aa7a8172eb0ff9031dba50b/href">https://medium.com/media/2b24885d3aa7a8172eb0ff9031dba50b/href</a></iframe><h4>Email:</h4><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Fshivam04%2Fembed%2Fpreview%2FmdvogPO%3Fdefault-tabs%3Dhtml%252Cresult%26height%3D600%26host%3Dhttps%253A%252F%252Fcodepen.io%26slug-hash%3DmdvogPO&amp;display_name=CodePen&amp;url=https%3A%2F%2Fcodepen.io%2Fshivam04%2Fpen%2FmdvogPO&amp;image=https%3A%2F%2Fshots.codepen.io%2Fusername%2Fpen%2FmdvogPO-512.jpg%3Fversion%3D1702218378&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/bcb0b69374f77f9cd329ffbbad9cf0b1/href">https://medium.com/media/bcb0b69374f77f9cd329ffbbad9cf0b1/href</a></iframe><h3>Notification Flow:</h3><h4>Contact Gathering Flow:</h4><p>Gather mobile device tokens, phone numbers, or email addresses. When users install apps or sign up for the first time, API servers collect user contact info and store it in the database.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Fshivam04%2Fembed%2Fpreview%2FxxMBeRK%3Fdefault-tabs%3Dhtml%252Cresult%26height%3D600%26host%3Dhttps%253A%252F%252Fcodepen.io%26slug-hash%3DxxMBeRK&amp;display_name=CodePen&amp;url=https%3A%2F%2Fcodepen.io%2Fshivam04%2Fpen%2FxxMBeRK&amp;image=https%3A%2F%2Fshots.codepen.io%2Fusername%2Fpen%2FxxMBeRK-512.jpg%3Fversion%3D1702218768&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/3aa25795b38cd3793b4175bbd7292ea2/href">https://medium.com/media/3aa25795b38cd3793b4175bbd7292ea2/href</a></iframe><h4>DB Design:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/804/1*q5Dmf9zudF6HOTWaZ0b5Tg.png" /></figure><h4>High-Level Flow:</h4><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Fshivam04%2Fembed%2Fpreview%2FxxMBeqx%3Fdefault-tabs%3Dhtml%252Cresult%26height%3D600%26host%3Dhttps%253A%252F%252Fcodepen.io%26slug-hash%3DxxMBeqx&amp;display_name=CodePen&amp;url=https%3A%2F%2Fcodepen.io%2Fshivam04%2Fpen%2FxxMBeqx&amp;image=https%3A%2F%2Fshots.codepen.io%2Fusername%2Fpen%2FxxMBeqx-512.jpg%3Fversion%3D1702219133&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/2b539b5d7920b26ba5cf7e991804de6b/href">https://medium.com/media/2b539b5d7920b26ba5cf7e991804de6b/href</a></iframe><h3>Design Deep Dive:</h3><h4><strong>Reliability:</strong></h4><ol><li><strong>Prevent Data Loss: </strong>Persists notification data in the database and implements a retry mechanism.</li><li><strong>Deliver notification exactly once: </strong>Due to the distributed nature could result in duplicate notifications. Use cache DB to check if the event(EventID) has been seen before or not.</li></ol><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Fshivam04%2Fembed%2Fpreview%2FJjxzVLG%3Fdefault-tabs%3Dhtml%252Cresult%26height%3D600%26host%3Dhttps%253A%252F%252Fcodepen.io%26slug-hash%3DJjxzVLG&amp;display_name=CodePen&amp;url=https%3A%2F%2Fcodepen.io%2Fshivam04%2Fpen%2FJjxzVLG&amp;image=https%3A%2F%2Fshots.codepen.io%2Fusername%2Fpen%2FJjxzVLG-512.jpg%3Fversion%3D1702220378&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/9945448a6b185624be3dc20929de9738/href">https://medium.com/media/9945448a6b185624be3dc20929de9738/href</a></iframe><h3>Raw Design:</h3><p><a href="https://jamboard.google.com/d/1vsaej7q2q5ND_FZXLYefuD16zw-fHwKyK76xjNszkBI/edit?usp=sharing">Notification System - Google Jamboard</a></p><h3>Services:</h3><ol><li>Service 1 to N (Providers): Microservice, a cron job or a distributed system that triggers notification-sending events.</li><li>Notification Systems/Servers: Provide APIs to send notifications. Do validations to verify emails, phone numbers etc. Put notification data into the message Queue.</li><li>Cache: User Info, device info, and notification templates are cached.</li><li>DB: It stores data about users, notifications, settings, etc.</li><li>Message Queues: Buffers when high volumes of notifications are to be sent out. They remove dependencies between components.</li><li>Workers: List of servers that pull notification events from message queues and send them to the corresponding third-party services.</li><li>Third-Party Services: APNs, FCM, SMS, Emails etc.</li><li>Notification Log: To prevent data loss, persist notification data in a database.</li><li>Notification Template: Preformatted notification to create unique notifications by customizing parameters, styling, tracking links, etc.</li><li>Notification Setting: User-based setting to Opt In/Opt Out notification settings.</li><li>Rate Limiting: Limit the number of notifications a user can receive.</li><li>Retry Mechanism: When a third-party service fails to send a notification, the notification will be added to the message queue for retrying.</li><li>Analytics Service: Used for events tracking, such as open rate, click rate and engagements to understand customer behaviours.</li></ol><h3>High-Level Architecture:</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Fshivam04%2Fembed%2Fpreview%2FbGzZJZm%3Fdefault-tabs%3Dhtml%252Cresult%26height%3D600%26host%3Dhttps%253A%252F%252Fcodepen.io%26slug-hash%3DbGzZJZm&amp;display_name=CodePen&amp;url=https%3A%2F%2Fcodepen.io%2Fshivam04%2Fpen%2FbGzZJZm&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/4a2dec38a16ef6ffc0cf75a48cbe62f0/href">https://medium.com/media/4a2dec38a16ef6ffc0cf75a48cbe62f0/href</a></iframe><p>ThankYou. Please do give suggestions.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=270506e944e0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Design OTT Platform]]></title>
            <link>https://shivam-sinha.medium.com/design-ott-platform-3727765c22a7?source=rss-a74f7b448497------2</link>
            <guid isPermaLink="false">https://medium.com/p/3727765c22a7</guid>
            <category><![CDATA[high-level-design]]></category>
            <category><![CDATA[ott]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[streaming]]></category>
            <category><![CDATA[design-systems]]></category>
            <dc:creator><![CDATA[Shivam Sinha]]></dc:creator>
            <pubDate>Fri, 19 May 2023 12:01:54 GMT</pubDate>
            <atom:updated>2023-05-19T12:01:54.453Z</atom:updated>
            <content:encoded><![CDATA[<p>OTT describes the platform that delivers streaming content via the internet across devices including mobile phones, smart TVs, computers, and tablets. The content that is streamed can include video, music, and messaging. Example: <a href="https://www.hotstar.com/">HotStar</a>, <a href="https://netflix.com/">Netflix</a>, <a href="https://primevideo.com/">AmazonPrime</a></p><h3>Functional Requirements:</h3><ol><li>Upload Video</li><li>Watch Video</li><li>Analytics and Logs</li></ol><h3>Non Functional Requirements:</h3><ol><li>Highly Available</li><li>Low Latencies</li><li>Global Service</li><li>Read Heavy System</li><li>Eventual Consistency (Why?)</li></ol><h3>Scale Estimations:</h3><p>We are scaling for 200 Million users across globe.</p><h4>Data</h4><ol><li>Video</li><li>User<br>a. Video Watched<br>b. Video liked<br>c. Video rate<br>d. Video paused at.</li></ol><h4>Video Data Estimations:</h4><p>OTT platforms, unlike content creation platform(like Youtube, <a href="https://shivam-sinha.medium.com/tiktok-system-design-26a184bb7ad9">TikTok</a>) has limited amount of videos.</p><p>Say, we have onboarded 1M videos/shows on our OTT platform, and on average the length of each video is 2 hours.</p><p>Based on different devices, internet speed we may need to store different resolutions and stream relevant resolution video to the users. Check <a href="https://www.cloudflare.com/learning/video/what-is-adaptive-bitrate-streaming/#:~:text=Adaptive%20bitrate%20streaming%20adjusts%20video,%2C%20location%2C%20or%20Internet%20speed.">ABS</a>.</p><p>For simplicity we have 2 resolution -&gt; SD, HD</p><p>Size: for SD -&gt; 10GB/hour and for HD -&gt; 20GB/hour</p><p>Total size of single video of 2 hour: (10+20)*2 = 60GB/video</p><p>Total Video Size: 60*1M = 60*10⁶ = 60 PetaByte or 60 PB.</p><h4>User Data Estimations:</h4><p>Say, on an average a single user watches, 2 shows/week i.e, ~100 shows/year.</p><p>Average lifetime of a user on an OTT platform: 10 years.</p><p>Logs: 100 bytes/show.</p><p>Total Size: 200*10⁶(users)*100(logs size/show)*10(years)*100(shows/year) = 20 Tera Byte or 20 TB.</p><p>We can use any Key-Value Store(KVS) like DynamoDB to store such data.</p><p>We can shard based on user_id , all data of a single user will present in a single device.</p><h4>How are we going to Onboard a Video:</h4><p>This section deals with video storage and optimal way to stream those videos.</p><p>We can use S3, GCS to store our videos.</p><ol><li>Store full video in SD and HD format.<br>Issue: When someone is watching any show, they have to wait until full video is available to them. Consumes lot of bandwidth.</li><li>(Recommended) Store videos in chunks.<br>a. Say, we store a show in the chunks of 2min.<br>b. For a 2 hour show there will be 60 chunks.<br>c. We have 2 resolutions (SD and HD). So, total chunk count will be 120 chunks.</li></ol><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Fshivam04%2Fembed%2Fpreview%2FxxyQOOv%3Fdefault-tabs%3Dhtml%252Cresult%26height%3D600%26host%3Dhttps%253A%252F%252Fcodepen.io%26slug-hash%3DxxyQOOv&amp;display_name=CodePen&amp;url=https%3A%2F%2Fcodepen.io%2Fshivam04%2Fpen%2FxxyQOOv&amp;image=https%3A%2F%2Fshots.codepen.io%2Fusername%2Fpen%2FxxyQOOv-512.jpg%3Fversion%3D1684493760&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/f02e897cc26c43b512664487ec297d7f/href">https://medium.com/media/f02e897cc26c43b512664487ec297d7f/href</a></iframe><h4>Video MetaData Size Estimation:</h4><pre><br>+----------+----------+------------+-----------+-----------+-----------+------------+----------+<br>| video_id | chunk_id | resolution | thumbnail | chunk_url | video_url | start_time | end_time |<br>+----------+----------+------------+-----------+-----------+-----------+------------+----------+<br>|        1 | 1_1      |          0 | cdn_url   | cdn_url   | cdn_url   | 00:00:00   | 00:01:59 |<br>|        1 | 1_1      |          0 | cdn_url   | cdn_url   | cdn_url   | 00:00:00   | 00:01:59 |<br>|        1 | 1_2      |          1 | cdn_url   | cdn_url   | cdn_url   | 00:02:00   | 00:03:59 |<br>|        1 | 1_2      |          1 | cdn_url   | cdn_url   | cdn_url   | 00:02:00   | 00:03:59 |<br>+----------+----------+------------+-----------+-----------+-----------+------------+----------+<br><br></pre><p>Size of 1 row: ~350 bytes.</p><p>1 video: 60 chunks * 2 resolution * 350 bytes = ~40KB.</p><p>Total Size: 40 * 10⁶ KB = 40 GB. (Can be easily store in single device, RDBMS is a good choice).</p><h3>How To Stream Videos:</h3><p>Now, as we already discussed user logs, video onboarding let’s see how user can stream videos.</p><p>Example: Watch Avengers Infinity Wars</p><ol><li>User request for video or say fetch latest/next chunk.</li><li>Request to server: /fetch_next_chunk(current_chunk_id) . In case of first chunk set current_chunk_id = -1 .</li><li>After completing half (1 min) of the chunk request for next chunk.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uByyTp_LIGacpNx_c6087g.png" /><figcaption>Chunk Fetcher</figcaption></figure><ul><li>If chunk request fail buffer on UI.</li></ul><p>Now, let’s say OTT platform announces a new movie and everyone is waiting for this movie (like: Avengers EndGame, Avatar2) or at peak traffic 10M are online and are watching this video. This will put a lot of load on S3 storage as API Server will be requesting for video from S3.</p><p>Solution: <a href="https://www.cloudflare.com/en-gb/learning/cdn/what-is-a-cdn/">CDN</a></p><ol><li>Present at different regions.</li><li>It acts like a cache that stores hot/popular shows for out OTT platform at regional level.</li></ol><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Fshivam04%2Fembed%2Fpreview%2FXWxyKPr%3Fdefault-tabs%3Dhtml%252Cresult%26height%3D600%26host%3Dhttps%253A%252F%252Fcodepen.io%26slug-hash%3DXWxyKPr&amp;display_name=CodePen&amp;url=https%3A%2F%2Fcodepen.io%2Fshivam04%2Fpen%2FXWxyKPr&amp;image=https%3A%2F%2Fshots.codepen.io%2Fusername%2Fpen%2FXWxyKPr-512.jpg%3Fversion%3D1684495680&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/f42286f792ce1c5fe9fd4692c47b3d82/href">https://medium.com/media/f42286f792ce1c5fe9fd4692c47b3d82/href</a></iframe><p>How to populate CDN?</p><ol><li>For hot/popular video we can use a service like CachePopulatorService . Acts as a CRON and populate videos to CDN.</li><li>Also for any other videos, will populate CDN only if we received say 5–10 requests for a particular videos.</li></ol><h3>Jamboard Link:</h3><p><a href="https://jamboard.google.com/d/1gf67RuhSthqquGagIWJIIShpToxj6GzaQeQoJ8D53i0/edit?usp=sharing">OTTPlatform - Google Jamboard</a></p><h3><strong>Services:</strong></h3><ol><li>User App/ Web App: Used to upload and watch/stream videos.</li><li>User Activity Service: To store logs.</li><li>FetchChunkService: To fetch latest/new chunk requested by user while watching videos.</li><li>Upload Service: To onboard a new Show/Video.</li><li>Chunk Service: To divide a video into chunks of 2 minutes.</li><li>Encoder Service: Encode videos into different resolutions and formats.</li><li>Recommender Service: Not covered, but we can use user_metadata and video_meatadata to build Recommender service.</li></ol><h3>High-Level Architecture:</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Fshivam04%2Fembed%2Fpreview%2FxxyQEGE%3Fdefault-tabs%3Dhtml%252Cresult%26height%3D600%26host%3Dhttps%253A%252F%252Fcodepen.io%26slug-hash%3DxxyQEGE&amp;display_name=CodePen&amp;url=https%3A%2F%2Fcodepen.io%2Fshivam04%2Fpen%2FxxyQEGE&amp;image=https%3A%2F%2Fshots.codepen.io%2Fusername%2Fpen%2FxxyQEGE-512.jpg%3Fversion%3D1684497087&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/1f2e3c5e45c98614736727bf49bea0ef/href">https://medium.com/media/1f2e3c5e45c98614736727bf49bea0ef/href</a></iframe><p>ThankYou. Please do give suggestions.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3727765c22a7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Twitter System Design Part-2]]></title>
            <link>https://shivam-sinha.medium.com/twitter-system-design-part-2-17b26002a4dc?source=rss-a74f7b448497------2</link>
            <guid isPermaLink="false">https://medium.com/p/17b26002a4dc</guid>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[twitter]]></category>
            <category><![CDATA[design-systems]]></category>
            <category><![CDATA[high-level-design]]></category>
            <category><![CDATA[systemdesigntwitter]]></category>
            <dc:creator><![CDATA[Shivam Sinha]]></dc:creator>
            <pubDate>Sat, 15 Oct 2022 17:06:58 GMT</pubDate>
            <atom:updated>2022-10-15T17:10:13.534Z</atom:updated>
            <content:encoded><![CDATA[<p>Twitter is an American microblogging and social networking service on which users post and interact with messages known as “tweets”. Registered users can post, like, and retweet tweets, but unregistered users can only read those that are publicly available. In <a href="https://shivam-sinha.medium.com/twitter-system-design-part-1-a6507231cafc">part 1</a> we discussed the design of tweets, home timelines, and user timelines.</p><h3>Functional Requirements:</h3><ol><li>Search Tweets.</li><li>Check Trending Tweets.</li><li>Check your tweets analytics based on keywords.</li></ol><h3>Non-Functional Requirements:</h3><ol><li>Highly Available</li><li>Eventual Consistency (It’s ok if a tweet is shown to followers after some time).</li><li>Low Latency (Real Time)</li></ol><h3>Estimations:</h3><p>Characters Supported per tweet: 280 Characters</p><p>Write Requests: 1000 tweets/sec</p><p>Read Requests: 1000,000 tweets/sec</p><p>So, it’s a read-heavy system.</p><p>Storage Estimations:</p><p>Tweets/Sec: 1000*280 = 280000 Bytes/sec = 280 KB/sec ~ 0.3 MB/sec</p><p>Tweets/Day: 0.3*3600*24 = 26 GB/Day</p><h3>Trending Tweets &amp; Analytics:</h3><p>In this section, we will discuss the 2nd and 3rd functional requirements.</p><p>So, first of all, what are trending tweets or Trends? [We will keep trends and keyword analytics based on hashtags].</p><p>Let’s take 2 examples:</p><ol><li>We get 1000 tweets with the same hashtag in a minute.</li><li>We get 10000 tweets with the same hashtag in a month.</li></ol><p>Obviously, the first hashtag is trending.</p><p>Trends depend on hashtags along with the location of the tweets. Say, tweets related to the Cricket match between India and Pakistan are going to be popular in India and Pakistan.</p><p>So, Geotagging of tweets is also important here.</p><p>Now, talking about analytics like how many tweets we get with say hashtag #election or #coding or #systemdesign in a minute, day, month or so.</p><p>So, we need to store these keywords and the time these occur in some distributed database. So, it can be easily accessible and admins can generate analytics on the data.</p><p>Now the question arises, how can we store this data?</p><p>We Can use a time-series [<a href="https://en.wikipedia.org/wiki/Time_series_database">Read Here</a>] database to store hashtags with the time at which the tweets were published.</p><h3>Search Timeline:</h3><p>For this we need to filter out keywords and store the data in a database.</p><p>How can we store data?</p><p>We can store data as <a href="https://www.geeksforgeeks.org/inverted-index/">inverted index</a> in a <a href="https://www.techtarget.com/searchoracle/definition/distributed-database#:~:text=A%20distributed%20database%20is%20a,distributed%20among%20multiple%20database%20nodes.">distributed database</a> (Why?)</p><p>Now how can we query? We can use scatter and gather approach to query data scattered in distributed database and then gather the output to be displayed in search timeline.</p><h3><strong>Raw Design:</strong></h3><p><a href="https://jamboard.google.com/d/1vaskPevY1ASOQzuifb_CGIKnyYjYxAa0owIE2Kknuos/edit?usp=sharing">Twitter System Design Part 2 - Google Jamboard</a></p><h3>Services:</h3><ol><li>Filter Service: Filter hashtags from tweets.</li><li>Parse Service: Figure Out Appropriate hashtags, and remove negative hashtags.</li><li>Count Service: Count Hashtags and pass this data to the rank service.</li><li>Rank Service: Ranks hashtags and stores the data in a cache like Redis.</li><li>Geo-Tagging Service: Geo-tag hashtags/tweets.</li><li>Search Service: Gets tweets, filter keyword store in DB (reverted index) with tweet Id.</li><li>Tweet Service: API to receive tweets and publish in Kafka topic.</li></ol><h3>High-Level Architecture:</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Fshivam04%2Fembed%2Fpreview%2FeYrXjpo%3Fdefault-tabs%3Dhtml%252Cresult%26height%3D600%26host%3Dhttps%253A%252F%252Fcodepen.io%26slug-hash%3DeYrXjpo&amp;display_name=CodePen&amp;url=https%3A%2F%2Fcodepen.io%2Fshivam04%2Fpen%2FeYrXjpo&amp;image=https%3A%2F%2Fshots.codepen.io%2Fshivam04%2Fpen%2FeYrXjpo-512.jpg%3Fversion%3D1665853391&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/7f233bd10692296ab7b5c5541afe6d92/href">https://medium.com/media/7f233bd10692296ab7b5c5541afe6d92/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=17b26002a4dc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Twitter System Design Part-1]]></title>
            <link>https://shivam-sinha.medium.com/twitter-system-design-part-1-a6507231cafc?source=rss-a74f7b448497------2</link>
            <guid isPermaLink="false">https://medium.com/p/a6507231cafc</guid>
            <category><![CDATA[systemdesigntwitter]]></category>
            <category><![CDATA[high-level-design]]></category>
            <category><![CDATA[design-systems]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[db-design]]></category>
            <dc:creator><![CDATA[Shivam Sinha]]></dc:creator>
            <pubDate>Sun, 19 Jun 2022 12:15:11 GMT</pubDate>
            <atom:updated>2022-06-19T12:22:42.059Z</atom:updated>
            <content:encoded><![CDATA[<p>Twitter is an American microblogging and social networking service on which users post and interact with messages known as “tweets”. Registered users can post, like, and retweet tweets, but unregistered users can only read those that are publicly available.</p><h3>Functional Requirements:</h3><ol><li>Tweets Obviously</li><li>User Timeline</li><li>Home Timeline</li><li>Trending Tweets (HashTags(#), Topics)</li><li>Search Tweet</li></ol><h3>Non Functional Requirements:</h3><ol><li>Highly Available</li><li>Eventual Consistency (It’s ok if a tweet is shown to followers after some time).</li><li>Low Latency (Real Time)</li></ol><h3>Estimations:</h3><p>Characters Supported per tweet: 280 Characters</p><p>Write Requests: 1000 tweets/sec</p><p>Read Requests: 1000,000 tweets/sec</p><p>So It’s a read-heavy system.</p><p>Storage Estimations:</p><p>Tweets/Sec: 1000*280 = 280000 Bytes/sec = 280 KB/sec ~ 0.3 MB/sec</p><p>Tweets/Day: 0.3*3600*24 = 26 GB/Day</p><p>Jamboard Link:</p><p><a href="https://jamboard.google.com/d/1jQMwpgBzmWmjTWh8qbvGeoif8S5Cct5dN81Gau4W_lA/edit?usp=sharing">Twitter System Design - Google Jamboard</a></p><h3>Database:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2r-7Xf70v3n4eOeD-ilWdA.png" /><figcaption>Database Design</figcaption></figure><p>Let’s see how we use cache to store tweets in order to reduce latency.</p><p>For this example, I am taking <a href="https://redis.io/">Redis</a> as my cache.</p><p>We can use a <a href="https://redis.io/commands/sadd/">stored set</a> to store tweets and followers.</p><p>Example:</p><ol><li>&lt;user_id1&gt;_tweets: {1,2,3..}</li><li>&lt;user_id2&gt;_tweets: {4,5,6..}</li><li>&lt;user_id1&gt;_follows: {1,2,3…}</li><li>&lt;user_id2&gt;_follows: {4,5,6…}</li></ol><p>For fast loading, we can store 5 years of data in Redis:</p><p>Total Space: (26 GB/Day) * (365*5 Day) = 65700 GB ~ 66 TB</p><h3><strong>User Timeline:</strong></h3><p>For the user timeline, we need to store all the tweets the user tweeted.</p><p>Let’s discuss how we store and read tweets from Redis/DB.</p><p>We can use a <a href="https://redis.io/commands/zadd/">sorted set</a> as discussed above to store tweets based on some scores say timestamp. Say we can fetch the top 20 tweets and once we read the top 10 tweets we can call from the backend to load 10 more we can use the timestamp of the last tweet (i.e the 20th tweet in a window) as the offset here.</p><p>Here’s the example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wZBYdBPOoKx7tWP0SwS1LQ.png" /></figure><p>Let’s see how we can store tweets in Redis. For this, we can use <a href="https://redis.io/commands/set/">set</a> commands.</p><p>Example:</p><p>tweet_id_1: “Hello There!”</p><p>tweet_id_2: “Check out my new article”</p><p>We can reduce key characters from tweet_id to T_ID to save some space.</p><h3>HomeTime:</h3><p>For the home timeline let’s discuss the steps:</p><ol><li>Get followers</li><li>Get latest tweets</li><li>Merge and Display Tweets</li></ol><p>For each user, we can maintain a home timeline basically <a href="https://redis.io/commands/zadd/">key-value</a> just like we use to store tweets in the user timeline.</p><p>Example:</p><p>H_U_ID1: {1,2,3…}</p><p>H_U_ID2: {3,4,5…}</p><p>So we can use a cache populator service to populate home timeline data in Redis. For online users, we can populate the tweet from a user to its followers directly. But we can’t do the same thing with celebrity tweets right as they have millions of followers.</p><p>Now for Celebrity tweets what we can do is wait and let the cache populator service(CRON) update tweets in individual user hometime caches.</p><p>So In short:</p><ol><li>For Normal Users: Tweets push to followers&#39; home timelines.</li><li>For Celebrity Users: Tweets pull to followers’ home timelines.</li></ol><p>Example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bRU2Lxi2wp9DA2kiLk0Zdg.png" /><figcaption>Normal Users Followers Home Timeline</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EMCES76xYzMu15qU3Ornlg.png" /><figcaption>Celebrity Users Followers Home Timeline</figcaption></figure><h3>Services:</h3><ol><li>User App/ Web App: Used to write and read tweets.</li><li>Tweet Write Service: Handle all the write request</li><li>Tweet Write Consumer Service: To save data in the database and Redis cache based on the user and home timeline.</li><li>Tweet Read Service: Handle all the read requests.</li><li>API Gateway: That forwards traffic to different Load balancers (Path-Based API Gateway).</li><li>Cache Populator Service: Explained Above</li><li>Notification Service. (Real-Time)</li><li>Search Service: (Will be discussed In Part 2)</li><li>Trend Service: (Missing Here Will be discussed In Part 2)</li></ol><h3>High-Level Architecture:</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Fshivam04%2Fembed%2Fpreview%2FOJQGwXw%3Fdefault-tabs%3Dhtml%252Cresult%26height%3D600%26host%3Dhttps%253A%252F%252Fcodepen.io%26slug-hash%3DOJQGwXw&amp;display_name=CodePen&amp;url=https%3A%2F%2Fcodepen.io%2Fshivam04%2Fpen%2FOJQGwXw&amp;image=https%3A%2F%2Fshots.codepen.io%2Fshivam04%2Fpen%2FOJQGwXw-512.jpg%3Fversion%3D1655639754&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/175c9351332e9e228a10077f3f9890e2/href">https://medium.com/media/175c9351332e9e228a10077f3f9890e2/href</a></iframe><p>ThankYou. Please do give suggestions.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a6507231cafc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Design Instagram | Machine Coding]]></title>
            <link>https://shivam-sinha.medium.com/design-instagram-machine-coding-7a2b4dc32bac?source=rss-a74f7b448497------2</link>
            <guid isPermaLink="false">https://medium.com/p/7a2b4dc32bac</guid>
            <category><![CDATA[object-oriented]]></category>
            <category><![CDATA[lld]]></category>
            <category><![CDATA[hld]]></category>
            <category><![CDATA[instagram]]></category>
            <category><![CDATA[machine-code]]></category>
            <dc:creator><![CDATA[Shivam Sinha]]></dc:creator>
            <pubDate>Wed, 04 May 2022 14:36:09 GMT</pubDate>
            <atom:updated>2022-05-04T14:42:36.551Z</atom:updated>
            <content:encoded><![CDATA[<p>Instagram is a photo and video-sharing social networking service.</p><h3>Requirements:</h3><ul><li>Users should be able to upload/download/view photos.</li><li>Users can perform searches based on photo/video id.</li><li>Users can follow other users.</li></ul><h3>High-Level Diagram:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l77jyIdibdl4OX4txCYV7A.png" /><figcaption>Basic HLD</figcaption></figure><h3>Entities:</h3><ol><li>User</li><li>Entity</li><li>UserFollow</li></ol><h3>Basic Schema Design:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OnQ8fPOqZGSQ_Y1NcG2P4Q.png" /><figcaption>Basic Schema Design</figcaption></figure><h3><strong>Relationship Between Tables:</strong></h3><ol><li>User and Entity (One to Many).</li><li>User and User (For Followers -&gt; Many to Many)</li></ol><h3>Low-Level Design:</h3><p><strong>File Structure:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/872/1*bG_oAvP6zuebgrZhuJNZEQ.png" /><figcaption>File Structure</figcaption></figure><p><strong>UML Diagram:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_-35zdQ8Ba0Mg_GKy5oo-g.png" /><figcaption>UML Diagarm</figcaption></figure><p><strong>Code:</strong></p><p><a href="https://github.com/shivam04/InstaGramLLD/tree/master/src/main/java/com/example/instagramlld">InstaGramLLD/src/main/java/com/example/instagramlld at master · shivam04/InstaGramLLD</a></p><p>ThankYou. Please do give suggestions.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7a2b4dc32bac" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Design An Elevator System]]></title>
            <link>https://shivam-sinha.medium.com/design-an-elevator-system-6fe739e2c802?source=rss-a74f7b448497------2</link>
            <guid isPermaLink="false">https://medium.com/p/6fe739e2c802</guid>
            <category><![CDATA[object-oriented-design]]></category>
            <category><![CDATA[design-systems]]></category>
            <category><![CDATA[elevator-system-design]]></category>
            <category><![CDATA[low-level-design]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <dc:creator><![CDATA[Shivam Sinha]]></dc:creator>
            <pubDate>Thu, 17 Mar 2022 16:59:43 GMT</pubDate>
            <atom:updated>2022-03-17T16:59:43.188Z</atom:updated>
            <content:encoded><![CDATA[<p>An elevator is essentially a platform that is either pulled or pushed up by mechanical means.</p><h3>Requirements:</h3><ol><li>Goes Up/Down.</li><li>When going up we stop at all floors.</li><li>When we get a request to go down, while we are going up, we first stop at the highest floor.</li><li>Users can send requests from both inside and outside of the elevator.</li></ol><h3>Use Cases:</h3><ol><li>User requests from inside/outside of the elevator.</li><li>Add DOWN/UP Requests.</li><li>While going up or down we should maintain a queue that tells the elevator where to stop.</li></ol><h3>Class Diagram:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vsUEijTZef-mgBr3eW0hLg.png" /><figcaption>UML Diagram</figcaption></figure><h3>Implementation:</h3><p>Constants:</p><pre><em>public enum Direction </em>{<br>    UP,<br>    DOWN,<br>    IDLE<br>}</pre><pre><em>public enum Location </em>{<br>    INSIDE,<br>    OUTSIDE<br>}</pre><p>Request:</p><pre><em>public class Request </em>{<br>    <em>int </em>currentFloor;<br>    <em>int </em>desiredFloor;<br>    <em>Location </em>location;<br>    <em>Direction </em>direction;<br><br>    <em>public </em>Request(<em>int currentFloor</em>, <em>int desiredFloor</em>, <em>Location location</em>, <em>Direction direction</em>) {<br>        <em>this</em>.currentFloor = <em>currentFloor</em>;<br>        <em>this</em>.desiredFloor = <em>desiredFloor</em>;<br>        <em>this</em>.location = <em>location</em>;<br>        <em>this</em>.direction = <em>direction</em>;<br>    }<br>}</pre><p>Elevator:</p><pre><em>import java.util.PriorityQueue</em>;<em><br><br>public class Elevator </em>{<br>    <em>int </em>currentFloor;<br>    <em>Direction </em>direction;<br>    <em>PriorityQueue</em>&lt;<em>Request</em>&gt; upQ;<br>    <em>PriorityQueue</em>&lt;<em>Request</em>&gt; downQ;<br><br>    <em>public </em>Elevator(<em>int currentFloor</em>) {<br>        <em>this</em>.currentFloor = <em>currentFloor</em>;<br>        <em>this</em>.direction = <em>Direction</em>.IDLE;<br>        upQ = <em>new </em>PriorityQueue&lt;&gt;((<em>a</em>,<em>b</em>) -&gt; <em>a</em>.desiredFloor - <em>b</em>.desiredFloor);<br>        downQ = <em>new </em>PriorityQueue&lt;&gt;((<em>a</em>,<em>b</em>) -&gt; <em>b</em>.desiredFloor - <em>a</em>.desiredFloor);<br>    }<br><br>    <em>public PriorityQueue</em>&lt;<em>Request</em>&gt; getUpQ() {<br>        <em>return </em>upQ;<br>    }<br><br>    <em>public void </em>setUpQ(<em>PriorityQueue</em>&lt;<em>Request</em>&gt; <em>upQ</em>) {<br>        <em>this</em>.upQ = <em>upQ</em>;<br>    }<br><br>    <em>public PriorityQueue</em>&lt;<em>Request</em>&gt; getDownQ() {<br>        <em>return </em>downQ;<br>    }<br><br>    <em>public void </em>setDownQ(<em>PriorityQueue</em>&lt;<em>Request</em>&gt; <em>downQ</em>) {<br>        <em>this</em>.downQ = <em>downQ</em>;<br>    }<br><br>    <em>public void </em>addUpRequest(<em>Request upRequest</em>) {<br>        <em>if</em>(<em>Location</em>.OUTSIDE == <em>upRequest</em>.location) {<br>            upQ.offer(<em>new </em>Request(<em>upRequest</em>.currentFloor, <em>upRequest</em>.currentFloor, <em>Location</em>.OUTSIDE, <em>Direction</em>.UP));<br>            <em>System</em>.out.println(&quot;Added up request going to floor &quot; + <em>upRequest</em>.currentFloor + &quot;.&quot;);<br>        }<br>        upQ.offer(<em>upRequest</em>);<br>        <em>System</em>.out.println(&quot;Added up request going to floor &quot; + <em>upRequest</em>.desiredFloor + &quot;.&quot;);<br>    }<br><br>    <em>public void </em>addDownRequest(<em>Request downRequest</em>) {<br>        <em>if</em>(<em>Location</em>.OUTSIDE == <em>downRequest</em>.location) {<br>            downQ.offer(<em>new </em>Request(<em>downRequest</em>.currentFloor, <em>downRequest</em>.currentFloor, <em>Location</em>.OUTSIDE, <em>Direction</em>.DOWN));<br>            <em>System</em>.out.println(&quot;Added down request going to floor &quot; + <em>downRequest</em>.currentFloor + &quot;.&quot;);<br>        }<br>        downQ.offer(<em>downRequest</em>);<br>        <em>System</em>.out.println(&quot;Added down request going to floor &quot; + <em>downRequest</em>.desiredFloor + &quot;.&quot;);<br>    }<br><br>    <em>public void </em>run() {<br>        <em>while </em>(!upQ.isEmpty() || !downQ.isEmpty()) {<br>            processRequests();<br>        }<br><br>        <em>System</em>.out.println(&quot;Finished all requests.&quot;);<br>        <em>this</em>.direction = <em>Direction</em>.IDLE;<br>    }<br><br>    <em>private void </em>processRequests() {<br>        <em>if </em>(<em>this</em>.direction == <em>Direction</em>.UP || <em>this</em>.direction == <em>Direction</em>.IDLE) {<br>            processUpRequest();<br>            processDownRequest();<br>        } <em>else </em>{<br>            processDownRequest();<br>            processUpRequest();<br>        }<br>    }<br><br>    <em>private void </em>processUpRequest() {<br>        <em>while</em>(!upQ.isEmpty()) {<br>            <em>Request </em>upRequest = upQ.poll();<br>            <em>this</em>.currentFloor = upRequest.desiredFloor;<br>            <em>System</em>.out.println(&quot;Up -&gt; Elevator stopped at floor &quot; + <em>this</em>.currentFloor + &quot;.&quot;);<br>        }<br>        <em>if </em>(!downQ.isEmpty()) {<br>            <em>this</em>.direction = <em>Direction</em>.DOWN;<br>        } <em>else </em>{<br>            <em>this</em>.direction = <em>Direction</em>.IDLE;<br>        }<br>    }<br><br>    <em>private void </em>processDownRequest() {<br>        <em>while</em>(!downQ.isEmpty()) {<br>            <em>Request </em>downRequest = downQ.poll();<br>            <em>this</em>.currentFloor = downRequest.desiredFloor;<br>            <em>System</em>.out.println(&quot;Down -&gt; Elevator stopped at floor &quot; + <em>this</em>.currentFloor + &quot;.&quot;);<br>        }<br>        <em>if </em>(!upQ.isEmpty()) {<br>            <em>this</em>.direction = <em>Direction</em>.UP;<br>        } <em>else </em>{<br>            <em>this</em>.direction = <em>Direction</em>.IDLE;<br>        }<br>    }<br><br>}</pre><p>ElevatorRunner:</p><pre><em>import java.util.PriorityQueue</em>;<br><em>import java.util.concurrent.locks.Lock</em>;<br><em>import java.util.concurrent.locks.ReentrantLock</em>;<br><em><br><br>public class ElevatorRunner </em>{<br>    <em>Elevator </em>elevator;<br><br><br>    <em>private static class RequestProcessor implements Runnable </em>{<br>        <em>Elevator </em>elevator;<br>        <em>private boolean </em>stop;<br><br>        <em>public </em>RequestProcessor(<em>Elevator elevator</em>) {<br>            <em>this</em>.elevator = <em>elevator</em>;<br>            stop = <em>false</em>;<br>        }<br><br>        <em>public void </em>setStop(<em>boolean stop</em>) {<br>            <em>this</em>.stop = <em>stop</em>;<br>        }<br><br>        <em>@Override<br>        public void </em>run() {<br>            <em>while</em>(stop == <em>false</em>) {<br>                <em>Request </em>upRequest1 = <em>new </em>Request(elevator.currentFloor, 5, <em>Location</em>.INSIDE, <em>Direction</em>.UP);<br>                <em>Request </em>upRequest2 = <em>new </em>Request(elevator.currentFloor, 3, <em>Location</em>.INSIDE, <em>Direction</em>.UP);<br><br>                <em>Request </em>downRequest1 = <em>new </em>Request(elevator.currentFloor, 1, <em>Location</em>.INSIDE, <em>Direction</em>.DOWN);<br>                <em>Request </em>downRequest2 = <em>new </em>Request(elevator.currentFloor, 2, <em>Location</em>.INSIDE, <em>Direction</em>.DOWN);<br>                <em>Request </em>downRequest3 = <em>new </em>Request(4, 0, <em>Location</em>.OUTSIDE, <em>Direction</em>.DOWN);<br><br>                elevator.addUpRequest(upRequest1);<br>                elevator.addUpRequest(upRequest2);<br><br>                elevator.addDownRequest(downRequest3);<br><br>                elevator.addDownRequest(downRequest1);<br>                elevator.addDownRequest(downRequest2);<br>                <em>try </em>{<br>                    <em>Thread</em>.<em>sleep</em>(1000); <em>//just for test<br>                </em>} <em>catch </em>(<em>InterruptedException e</em>) {<br>                    <em>e</em>.printStackTrace();<br>                }<br>            }<br>        }<br>    }<br><br>    <em>public static void </em>main(<em>String</em>[] <em>args</em>) <em>throws InterruptedException </em>{<br>        <em>Elevator </em>elevator = <em>new </em>Elevator(0);<br>        <em>RequestProcessor </em>requestProcessor = <em>new </em>RequestProcessor(elevator);<br>        <em>Thread </em>thread = <em>new </em>Thread(requestProcessor);<br>        thread.start();<br>        <em>int </em>k = 0;<br>        <em>while</em>(<em>true</em>) {<br>            elevator.run();<br>            <em>//If idle then wait for some time say at night when no one uses elevator we can relax system i.e don&#39;t call elevator.run() continuously<br>            Thread</em>.<em>sleep</em>(3000);<br>            k++;<br><br>            <em>if</em>(k==3)<br>                <em>break</em>; <em>//just for test<br>        </em>}<br>        requestProcessor.setStop(<em>true</em>);<br>    }<br>}</pre><p>You can access the code from <a href="https://github.com/shivam04/System-Design-Object-Oriented-Design/tree/master/ElevatorSystemDesign">here</a>.</p><p>ThankYou. Please do give suggestions.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6fe739e2c802" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Design An ATM System]]></title>
            <link>https://shivam-sinha.medium.com/design-an-atm-system-389c67f2433e?source=rss-a74f7b448497------2</link>
            <guid isPermaLink="false">https://medium.com/p/389c67f2433e</guid>
            <category><![CDATA[design-systems]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[object-oriented-design]]></category>
            <category><![CDATA[design-atm]]></category>
            <category><![CDATA[javascript-oops]]></category>
            <dc:creator><![CDATA[Shivam Sinha]]></dc:creator>
            <pubDate>Fri, 04 Mar 2022 09:56:35 GMT</pubDate>
            <atom:updated>2022-03-04T09:56:35.142Z</atom:updated>
            <content:encoded><![CDATA[<p>An automated teller machine (ATM) is an electronic telecommunications device that enables customers of financial institutions to perform financial transactions, such as cash withdrawals, deposits, funds transfers, balance inquiries, or account information inquiries, at any time and without the need for direct interaction with bank staff.</p><h3><strong>Requirements:</strong></h3><ol><li>Card Reader, to read user’s debit/credit card.</li><li>Keypad to input card pin, amount to debit, etc.</li><li>Screen to display messages to users like the amount left in the bank.</li><li>Cash Dispenser for dispensing cash.</li><li>Users must have a bank account.</li><li>Users must have a card(debit/credit) linked to their bank account to use an ATM.</li><li>Users can change the pin of that card from the ATM.</li></ol><h3>Main Actors:</h3><ol><li><strong>ATM operator</strong>: Turn On/Off ATM, Refill Cash in an ATM.</li><li><strong>Customer</strong>: Balance Inquiry, Cash Withdrawal, Change Pin.</li><li><strong>Bank Manager: </strong>Block/Unblock any customers, Generate reports for any ATM.</li></ol><h3>Use Cases:</h3><ol><li>Read Card</li><li>Check Balance, Withdraw Cash.</li><li>Check how much amount is left in ATM (Bank Manager can access this information).</li><li>ATM system can show messages like required cash not available, or any other message.</li><li>Add New ATMs</li><li>Add New Bills</li></ol><h3><strong>Classes:</strong></h3><ol><li>ATM</li><li>Account</li><li>User (Abstract Class)</li><li>Customer</li><li>BankManager</li><li>Card</li><li>ATMOperator</li><li>Bank</li><li>Screen</li><li>CardReader</li><li>Keypad</li><li>CashDispensers</li><li>Address</li><li>Transaction (Abstract Class)</li><li>BalanceInquiry</li><li>Withdraw</li></ol><h3><strong>Implementation:</strong></h3><p>Constants</p><pre>const CustomerStatus = {<br>    ACTIVE: &#39;Active&#39;,<br>    BLOCKED: &#39;Blocked&#39;,<br>    CLOSED: &#39;Closed&#39;<br>}<br><br>module.exports = CustomerStatus;</pre><pre>const TransactionStatus = {<br>    SUCCESS: &quot;Success&quot;,<br>    FAILURE: &quot;Failure&quot;,<br>    BLOCKED: &quot;Blocked&quot;,<br>    PARTIAL: &quot;Partial&quot;<br>}<br><br>module.exports = TransactionStatus;</pre><pre>const TransactionType = {<br>    BALANCE_INQUIRY: &quot;Balance Inquiry&quot;,<br>    CASH_WITHDRAWAL: &quot;Cash Withdrawal&quot;<br>}<br><br>module.exports = TransactionType;</pre><pre>class Address {<br>    constructor(streetAddress, city, state, country, zipcode) {<br>        this._streetAddress = streetAddress;<br>        this._city = city;<br>        this._state = state;<br>        this._country = country;<br>        this._zipcode = zipcode;<br>    }<br><br><br>    get streetAddress() {<br>        return this._streetAddress;<br>    }<br><br>    set streetAddress(value) {<br>        this._streetAddress = value;<br>    }<br><br>    get city() {<br>        return this._city;<br>    }<br><br>    set city(value) {<br>        this._city = value;<br>    }<br><br>    get state() {<br>        return this._state;<br>    }<br><br>    set state(value) {<br>        this._state = value;<br>    }<br><br>    get country() {<br>        return this._country;<br>    }<br><br>    set country(value) {<br>        this._country = value;<br>    }<br><br>    get zipcode() {<br>        return this._zipcode;<br>    }<br><br>    set zipcode(value) {<br>        this._zipcode = value;<br>    }<br>}</pre><p>User, Customer, BankManager, ATMOperator, Card</p><pre>//Abstract Class<br>class User {<br>    constructor(id, name, email, phone, status) {<br>        this._id = id;<br>        this._name = name;<br>        this._email = email;<br>        this._phone = phone;<br>        this._status = status;<br>        if(this.constructor === User) {<br>            throw new Error(&quot; Object of Transaction Class cannot be created&quot;);<br>        }<br>    }<br><br><br>    get id() {<br>        return this._id;<br>    }<br><br>    set id(value) {<br>        this._id = value;<br>    }<br><br>    get name() {<br>        return this._name;<br>    }<br><br>    set name(value) {<br>        this._name = value;<br>    }<br><br>    get email() {<br>        return this._email;<br>    }<br><br>    set email(value) {<br>        this._email = value;<br>    }<br><br>    get phone() {<br>        return this._phone;<br>    }<br><br>    set phone(value) {<br>        this._phone = value;<br>    }<br><br>    get status() {<br>        return this._status;<br>    }<br><br>    set status(value) {<br>        this._status = value;<br>    }<br>}</pre><pre>class Customer extends User{<br><br>    constructor(id, name, email, phone, address, status, card, account) {<br>        super(id, name, email, phone, status);<br>        this._address = address;<br>        this._card = card;<br>        this._account = account;<br>    }<br><br>    get address() {<br>        return this._address;<br>    }<br><br>    set address(value) {<br>        this._address = value;<br>    }<br><br>    get card() {<br>        return this._card;<br>    }<br><br>    set card(value) {<br>        this._card = value;<br>    }<br><br>    get account() {<br>        return this._account;<br>    }<br><br>    set account(value) {<br>        this._account = value;<br>    }<br><br>    makeTransaction(transaction) {<br>        transaction.makeTransaction();<br>    }<br>}</pre><pre>class BankManager extends User{<br>    constructor(id, name, email, phone, status) {<br>        super(id, name, email, phone, status);<br>    }<br><br>    checkAvailableBalance(atm) {<br>        atm.getAvailableBalance();<br>    }<br>}</pre><pre>class ATMOperator extends User{<br>    constructor(id, name, email, phone, status, atm) {<br>        super(id, name, email, phone, status);<br>        this._atm = atm;<br>    }<br>    get atm() {<br>        return this._atm;<br>    }<br><br>    set atm(value) {<br>        this._atm = value;<br>    }<br><br>    addBill(bill, quantity) {<br>        this.atm.addCash(bill, quantity);<br>    }<br><br>    addMultipleBills(bills) {<br>        for(let bill in bills) {<br>            this.atm.addCash(bill, bills[bill]);<br>        }<br>    }<br>}</pre><pre>class Card {<br>    constructor(number, customerName, expiry, pin) {<br>        this._number = number;<br>        this._customerName = customerName;<br>        this._expiry = expiry;<br>        this._pin = pin;<br>    }<br><br>    get number() {<br>        return this._number;<br>    }<br><br>    set number(value) {<br>        this._number = value;<br>    }<br><br>    get customerName() {<br>        return this._customerName;<br>    }<br><br>    set customerName(value) {<br>        this._customerName = value;<br>    }<br><br>    get expiry() {<br>        return this._expiry;<br>    }<br><br>    set expiry(value) {<br>        this._expiry = value;<br>    }<br><br>    get pin() {<br>        return this._pin;<br>    }<br><br>    set pin(value) {<br>        this._pin = value;<br>    }<br>}</pre><p>ATM, Keypad, CardReader, CashDispenser, Screen</p><pre>class ATM {<br>    constructor(id, address, keypad, screen, cashDispenser, cardReader, availableCash) {<br>        this._id = id;<br>        this._address = address;<br>        this._keypad = keypad;<br>        this._screen = screen;<br>        this._cashDispenser = cashDispenser;<br>        this._cardReader = cardReader;<br>        this._availableCash = {}.concat(...availableCash)<br>        this._availableCash = availableCash; //just for cash<br>    }<br><br><br>    get id() {<br>        return this._id;<br>    }<br><br>    set id(value) {<br>        this._id = value;<br>    }<br><br>    get address() {<br>        return this._address;<br>    }<br><br>    set address(value) {<br>        this._address = value;<br>    }<br><br>    get keypad() {<br>        return this._keypad;<br>    }<br><br>    set keypad(value) {<br>        this._keypad = value;<br>    }<br><br>    get screen() {<br>        return this._screen;<br>    }<br><br>    set screen(value) {<br>        this._screen = value;<br>    }<br><br>    get cashDispenser() {<br>        return this._cashDispenser;<br>    }<br><br>    set cashDispenser(value) {<br>        this._cashDispenser = value;<br>    }<br><br>    get cardReader() {<br>        return this._cardReader;<br>    }<br><br>    set cardReader(value) {<br>        this._cardReader = value;<br>    }<br><br>    get availableCash() {<br>        return this._availableCash;<br>    }<br><br>    set availableCash(value) {<br>        this._availableCash = value;<br>    }<br><br>    authenticateUser(account) {<br><br>    }<br><br>    getAvailableBalance() {<br>        let sum = 0;<br>        for (let bill in this.availableCash) {<br>            sum += this.availableCash[bill];<br>        }<br>        return sum;<br>    }<br><br>    addCash(bill, quantity) {<br>        if(this.availableCash.hasOwnProperty(bill))<br>            this.availableCash[bill] += quantity;<br>        else<br>            this.availableCash[bill] = quantity;<br>    }<br>}<br><br>class Keypad {<br>    getInput() {<br><br>    }<br>}</pre><pre>class CardReader {<br>    readCard() {<br><br>    }<br>}</pre><pre>class CashDispenser {<br>    dispenseCash(amount) {<br><br>    }<br>}</pre><pre>class Screen {<br>    showMessage() {<br><br>    }<br><br>    getInput() {<br><br>    }<br>}</pre><p>Transaction</p><pre>//Abstract Class<br>class Transaction {<br>    constructor(transactionId, createdAt, status) {<br>        this._transactionId = transactionId;<br>        this._createdAt = createdAt;<br>        this._status = status;<br>        if(this.constructor === Transaction) {<br>            throw new Error(&quot; Object of Transaction Class cannot be created&quot;);<br>        }<br>    }<br><br>    get transactionId() {<br>        return this._transactionId;<br>    }<br><br>    set transactionId(value) {<br>        this._transactionId = value;<br>    }<br><br>    get createdAt() {<br>        return this._createdAt;<br>    }<br><br>    set createdAt(value) {<br>        this._createdAt = value;<br>    }<br><br>    get status() {<br>        return this._status;<br>    }<br><br>    set status(value) {<br>        this._status = value;<br>    }</pre><pre>    //Abstract Method<br>    makeTransaction() {<br>        throw new Error(&quot;Abstract Method makeTransaction has no implementation&quot;);<br>    }<br>}</pre><pre>class BalanceInquiry extends Transaction {<br>    constructor(transactionId, createdAt, status, accountId) {<br>        super(transactionId, createdAt, status);<br>        this._accountId = accountId;<br>    }<br><br>    get accountId() {<br>        return this._accountId;<br>    }<br><br>    set accountId(value) {<br>        this._accountId = value;<br>    }<br><br>    getAmount() {<br><br>    }<br><br>    makeTransaction() {<br>        //some db operation<br>    }<br><br>}</pre><pre>class Withdraw extends Transaction {<br><br>    constructor(transactionId, createdAt, status, amount) {<br>        super(transactionId, createdAt, status);<br>        this._transactionId = transactionId;<br>        this._createdAt = createdAt;<br>        this._status = status;<br>        this._amount = amount;<br>    }<br>    get amount() {<br>        return this._amount;<br>    }<br><br>    set amount(value) {<br>        this._amount = value;<br>    }<br><br>    makeTransaction() {<br>        //some db operation<br>    }<br>}</pre><p>You can access the code from <a href="https://github.com/shivam04/System-Design-Object-Oriented-Design/tree/master/atm-design/src">here</a>.</p><p>ThankYou. Please do give suggestions.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=389c67f2433e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Design Movie Ticket Booking System]]></title>
            <link>https://shivam-sinha.medium.com/design-movie-ticket-booking-system-2bc3ddef5803?source=rss-a74f7b448497------2</link>
            <guid isPermaLink="false">https://medium.com/p/2bc3ddef5803</guid>
            <category><![CDATA[object-oriented-design]]></category>
            <category><![CDATA[low-level-design]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[design-systems]]></category>
            <category><![CDATA[object-oriented-program]]></category>
            <dc:creator><![CDATA[Shivam Sinha]]></dc:creator>
            <pubDate>Sat, 26 Feb 2022 14:25:38 GMT</pubDate>
            <atom:updated>2022-02-26T14:25:38.707Z</atom:updated>
            <content:encoded><![CDATA[<p>A Movie Ticket Booking System is an online system that facilitates the purchasing of movies tickets to its customers. It also allows customers to browse through movies and book seats.</p><h3>Requirements</h3><ol><li>List cities where cinemas are located.</li><li>Each cinema can have multiple halls and each hall will run one show at a time.</li><li>Each movie will have multiple shows.</li><li>Each cinema hall runs only one movie at a time.</li><li>Customers can search movies based on title, genre, language, release date, and city name.</li><li>Customers can select show and book tickets.</li><li>The system will show seating arrangements in the hall and Customers can select their own seats based on their preferences.</li><li>Customers can pay for tickets and cancel their tickets.</li><li>The system can send notifications whenever there is a new movie, or when a booking is made or canceled.</li><li>Customers of our system should be able to pay with credit cards or cash.</li><li>The system should ensure that no two customers can reserve the same seat.</li><li>Admin can add a new movie, cancel the movie.</li></ol><h3>Main Actors:</h3><ol><li><strong>Admin: </strong>Can add/cancel the movie, block/unblock a user.</li><li><strong>Customer: </strong>Can search movies, book, and cancel tickets.</li><li><strong>Guest: </strong>Can search movies but to register themselves for booking movies.</li><li><strong>System: </strong>Sending notification whenever there is a new movie, or when a booking is made or canceled.</li></ol><p><strong>Use Cases for Movie Ticket Booking System:</strong></p><ol><li>Search Movies.</li><li>Create/Modify/Delete Booking.</li><li>Select Seats.</li><li>Pay for the ticket.</li><li>Refund for the ticket if someone cancels their ticket.</li></ol><p><strong>Raw Design:</strong></p><p><a href="https://jamboard.google.com/d/1tBfz-DhHjwnIaGU92JEVwhfHsCfcrm5Ga6qOw5OqZaE/edit?usp=sharing">MovieTicketLLD - Google Jamboard</a></p><h3>Classes:</h3><ol><li>Account</li><li>Customer</li><li>Admin</li><li>Guest</li><li>City</li><li>Cinema</li><li>CinemaHall</li><li>CinemaHallSeat</li><li>Movie</li><li>Show</li><li>Booking</li><li>Payment</li><li>Notification</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_Wl0cWnsnTdof4cD1N16eg.png" /><figcaption>UML Diagram</figcaption></figure><h3><strong>Implementation:</strong></h3><p>Constants and Enums</p><pre><em>public enum AccountStatus </em>{<br>    ACTIVE,<br>    BLOCKED,<br>    BANNED,<br>    ARCHIVED<br>}</pre><pre><em>public enum BookingStatus </em>{<br>    PENDING,<br>    CONFIRMED,<br>    CANCELED<br>}</pre><pre><em>public enum PaymentStatus </em>{<br>    UNPAID,<br>    PENDING,<br>    COMPLETED,<br>    CANCELLED,<br>    DECLINED,<br>    REFUNDED<br>}</pre><pre><em>public enum PaymentType </em>{<br>    CREDIT_CARD,<br>    CASH<br>}</pre><pre><em>public enum SeatType </em>{<br>    REGULAR,<br>    PREMIUM,<br>    OTHER<br>}</pre><p>Address</p><pre><em>public class Address </em>{<br>    <em>private String </em>streetAddress;<br>    <em>private String </em>city;<br>    <em>private String </em>state;<br>    <em>private String </em>zipCode;<br>    <em>private String </em>country;<br>}</pre><pre><em>public class City </em>{<br>    <em>private String </em>name;<br>    <em>private String </em>state;<br>    <em>private String </em>zipCode;<br><br>    <em>List</em>&lt;<em>Cinema</em>&gt; cinemaList;<br>}</pre><p>Account</p><pre><em>public class Account </em>{<br>    <em>private String </em>id;<br>    <em>private String </em>password;<br>    <em>private AccountStatus </em>status;<br>    <em>private String </em>name;<br>    <em>private String </em>email;<br>    <em>private String </em>phone;<br><br>    <em>public boolean </em>resetPassword(){<br>        <em>return true</em>;<br>    }<br>}</pre><pre><em>public class Admin extends Account</em>{<br>    <em>public boolean </em>addMovie(<em>Movie movie</em>) {<br>        <em>return true</em>;<br>    }<br>    <em>public boolean </em>addShow(<em>Show show</em>) {<br>        <em>return true</em>;<br>    }<br>    <em>public boolean </em>blockUser(<em>Customer customer</em>){<br>        <em>return true</em>;<br>    }<br><br>    <em>/*cancel show, block unblock movie*/<br></em>}</pre><pre><em>public class Customer extends Account</em>{<br>    <em>List</em>&lt;<em>Booking</em>&gt; bookingList;<br>    <em>public boolean </em>makeBooking(<em>Booking booking</em>) {<br>        bookingList.add(<em>booking</em>);<br>        <em>return true</em>;<br>    }<br><br>    <em>public List</em>&lt;<em>Booking</em>&gt; getBookings() {<br>        <em>return </em>bookingList;<br>    }<br>}</pre><pre><em>public class Guest </em>{<br>    <em>public boolean </em>registerAccount() {<br>        <em>return true</em>;<br>    }<br>}</pre><p>Movie, Shows</p><pre><em>public class Movie </em>{<br>    <em>private Integer </em>movieId;<br>    <em>private String </em>movieTitle;<br>    <em>private String </em>description;<br>    <em>private Integer </em>durationInMins;<br>    <em>private String </em>language;<br>    <em>private Date </em>releaseDate;<br>    <em>private String </em>country;<br>    <em>private String </em>genre;<br><br>    <em>List</em>&lt;<em>Show</em>&gt; showList;<br><br>    <em>public boolean </em>addShow(<em>Show show</em>) {<br>        showList.add(<em>show</em>);<br>        <em>return true</em>;<br>    }<br><br>    <em>public List</em>&lt;<em>Show</em>&gt; getShows() {<br>        <em>return </em>showList;<br>    }<br>}</pre><pre><em>public class Show </em>{<br>    <em>private Integer </em>showId;<br>    <em>private Date </em>createdOn;<br>    <em>private Date </em>startTime;<br>    <em>private Date </em>endTime;<br>    <em>private Movie </em>movie;<br>    <em>private CinemaHall </em>playedAt;<br><br>    <em>public void </em>addShow() {<br>        <em>this</em>.movie.addShow(<em>this</em>);<br>    }<br>}</pre><p>Cinema, CinemaHall and CinemaHallSeat</p><pre><em>public class Cinema </em>{<br>    <em>private String </em>name;<br>    <em>private Integer </em>totalCinemaHalls;<br>    <em>private Address </em>location;<br>    <em>private List</em>&lt;<em>CinemaHall</em>&gt; halls;<br><br>    <em>public List</em>&lt;<em>CinemaHall</em>&gt; getHalls() {<br>        <em>return </em>halls;<br>    }<br><br>    <em>public void </em>setHalls(<em>List</em>&lt;<em>CinemaHall</em>&gt; <em>halls</em>) {<br>        <em>this</em>.halls = <em>halls</em>;<br>    }<br>}</pre><pre><em>public class CinemaHall </em>{<br>    <em>private String </em>name;<br>    <em>private int </em>totalSeats;<br><br>    <em>private List</em>&lt;<em>CinemaHallSeat</em>&gt; seats;<br>    <em>private List</em>&lt;<em>Show</em>&gt; shows;<br><br><br>    <em>public List</em>&lt;<em>CinemaHallSeat</em>&gt; getSeats() {<br>        <em>return </em>seats;<br>    }<br><br>    <em>public void </em>setSeats(<em>List</em>&lt;<em>CinemaHallSeat</em>&gt; <em>seats</em>) {<br>        <em>this</em>.seats = <em>seats</em>;<br>    }<br><br>    <em>public List</em>&lt;<em>Show</em>&gt; getShows() {<br>        <em>return </em>shows;<br>    }<br><br>    <em>public void </em>setShows(<em>List</em>&lt;<em>Show</em>&gt; <em>shows</em>) {<br>        <em>this</em>.shows = <em>shows</em>;<br>    }<br>}</pre><pre><em>public class CinemaHallSeat </em>{<br>    <em>private int </em>showSeatId;<br>    <em>private boolean </em>isReserved;<br>    <em>private double </em>price;<br>    <em>private SeatType </em>seatType;<br>}</pre><p>Booking and Payment</p><pre><em>public class Booking </em>{<br>    <em>private Integer </em>bookingId;<br>    <em>private  Integer </em>numberOfSeats;<br>    <em>private Date </em>createdOn;<br>    <em>private BookingStatus </em>status;<br>    <em>private Show </em>show;<br>    <em>private List</em>&lt;<em>CinemaHallSeat</em>&gt; seats;<br>    <em>private Payment </em>payment;<br><br>    <em>public boolean </em>makeBooking(<em>Payment payment</em>) {<br>        <em>this</em>.payment = <em>payment</em>;<br>        <em>payment</em>.makePayment();<br>        <em>return true</em>;<br>    }<br><br>    <em>public boolean </em>cancel() {<br>        <em>return true</em>;<br>    }<br>    <em>public boolean </em>assignSeats(<em>List</em>&lt;<em>CinemaHallSeat</em>&gt; <em>seats</em>) {<br>        <em>this</em>.seats.addAll(<em>seats</em>);<br>        <em>return true</em>;<br>    }<br>}</pre><pre><em>public class Payment </em>{<br>    <em>public Integer </em>paymentId;<br>    <em>PaymentStatus </em>paymentStatus;<br>    <em>private Double </em>amount;<br>    <em>private Date </em>createdOn;<br>    <em>private int </em>transactionId;<br>    <em>private PaymentStatus </em>status;<br>    <em>private PaymentType </em>paymentType;<br><br>    <em>public void </em>makePayment() {<br><br>    }<br>}</pre><p>Notification</p><pre><em>public class Notification </em>{<br>    <em>private Integer </em>notificationId;<br>    <em>private Date </em>createdOn;<br>    <em>private String </em>content;<br><br>    <em>public boolean </em>sendNotification() {<br>        <em>return true</em>;<br>    }<br>}</pre><p>Search</p><pre><em>public interface Search </em>{<br>    <em>public List</em>&lt;<em>Movie</em>&gt; searchByTitle(<em>String title</em>);<br>    <em>public List</em>&lt;<em>Movie</em>&gt; searchByCity(<em>String cityName</em>);<br>    <em>public List</em>&lt;<em>Movie</em>&gt; searchByGenre(<em>String genre</em>);<br>    <em>public List</em>&lt;<em>Movie</em>&gt; searchByReleaseDate(<em>Date releaseDate</em>);<br>    <em>public List</em>&lt;<em>Movie</em>&gt; searchByLanguage(<em>String language</em>);<br>}</pre><pre><em>public class SearchCache implements Search</em>{<br><br>    <em>HashMap</em>&lt;<em>String</em>, <em>List</em>&lt;<em>Movie</em>&gt;&gt; searchTitles;<br>    <em>HashMap</em>&lt;<em>String</em>, <em>List</em>&lt;<em>Movie</em>&gt;&gt; searchCity;<br>    <em>HashMap</em>&lt;<em>String</em>, <em>List</em>&lt;<em>Movie</em>&gt;&gt; searchGenre;<br>    <em>HashMap</em>&lt;<em>String</em>, <em>List</em>&lt;<em>Movie</em>&gt;&gt; searchReleaseDate;<br>    <em>HashMap</em>&lt;<em>String</em>, <em>List</em>&lt;<em>Movie</em>&gt;&gt; searchLanguage;<br><br>    <em>@Override<br>    public List</em>&lt;<em>Movie</em>&gt; searchByTitle(<em>String title</em>) {<br>        <em>return </em>searchTitles.get(<em>title</em>);<br>    }<br><br>    <em>@Override<br>    public List</em>&lt;<em>Movie</em>&gt; searchByCity(<em>String cityName</em>) {<br>        <em>return </em>searchCity.get(<em>cityName</em>);<br>    }<br><br>    <em>@Override<br>    public List</em>&lt;<em>Movie</em>&gt; searchByGenre(<em>String genre</em>) {<br>        <em>return </em>searchGenre.get(<em>genre</em>);<br>    }<br><br>    <em>@Override<br>    public List</em>&lt;<em>Movie</em>&gt; searchByReleaseDate(<em>Date releaseDate</em>) {<br>        <em>return </em>searchReleaseDate.get(<em>releaseDate</em>);<br>    }<br><br>    <em>@Override<br>    public List</em>&lt;<em>Movie</em>&gt; searchByLanguage(<em>String language</em>) {<br>        <em>return </em>searchLanguage.get(<em>language</em>);<br>    }<br>}</pre><p>So it’s just an overview we can further add the logic like how can we lock seats while booking seats, etc.</p><p>You can access the code from <a href="https://github.com/shivam04/System-Design-Object-Oriented-Design/tree/master/MovieTicket/src/main">here</a>.</p><p>ThankYou. Please do give suggestions.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2bc3ddef5803" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[System Design Architecture StackOverflow]]></title>
            <link>https://shivam-sinha.medium.com/system-design-architecture-stackoverflow-40c16d59f4e1?source=rss-a74f7b448497------2</link>
            <guid isPermaLink="false">https://medium.com/p/40c16d59f4e1</guid>
            <category><![CDATA[high-level-design]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[design-systems]]></category>
            <category><![CDATA[high-level-architecture]]></category>
            <category><![CDATA[stackoverflow-design]]></category>
            <dc:creator><![CDATA[Shivam Sinha]]></dc:creator>
            <pubDate>Mon, 21 Feb 2022 13:39:45 GMT</pubDate>
            <atom:updated>2022-02-21T15:28:49.511Z</atom:updated>
            <content:encoded><![CDATA[<p>Stack Overflow is a question-and-answer website for professional and enthusiast programmers. In the previous <a href="https://shivam-sinha.medium.com/design-stackoverflow-416518562a2b">post</a>, we discussed LLD, in this post we are going to discuss the HLD of StackOverflow.</p><h3>Functional Requirements</h3><ol><li>Post questions, answers, upvotes, and downvotes.</li><li>Follow Users.</li><li>Home Timeline: To show relevant questions to users.</li><li>Search Questions.</li></ol><h3>Non Functional Requirements</h3><ol><li>High Availability</li><li>Low Latency (Real Time)</li></ol><h3><strong>Estimations:</strong></h3><ol><li>Total Users: 20M</li><li>Total Questions: 25M</li><li>Toal Answers: 40M</li><li>Total Votes: 200M</li></ol><p>Questions/day: 5K</p><p>Answers/day: 7K</p><p>Votes/day : 36K</p><p>Active Users/day: 5000</p><p>Storage Estimations:</p><p>Size of each question and answer: 30KB</p><p>Votes: 20 Bytes</p><p>UserMetaData(like views, time spent, etc.): 10KB</p><p>Storage/day: 30KB*(5000+7000) + 20Bytes*(36000) + 10KB*(5000) = 410MB</p><h3><strong>Database:</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9Fp6jqU-1UumaYROfExJIg.png" /><figcaption>Database Design</figcaption></figure><h3><strong>Services:</strong></h3><ol><li>User App/ Web App: Used to Add/Delete/Modify Questions and answers. Voting questions and answers.</li><li>Question Service: A list of API Servers handles queries related to questions like Add/Modify questions.</li><li>Answer Service.</li><li>Vote Service: For upvote and downvote.</li><li>User Activity Service: Use Pub-Sub model like Kafka and store them in HDFS data store.</li><li>LOG Service: Subscribe to user activities topics and publish messages for notification service also storing all logs in HDFS data store that can be used later for recommending questions to different users, analytics, etc.</li><li>Load Balancer: Behind different API servers that handle different services (Question Service, Answer Service).</li><li>API Gateway: That forwards traffic to different Load balancers (Path-Based API Gateway).</li><li>Home Timeline Service.</li><li>Cache Populator Service: Cron which populate the cache with say top 200 questions per user. Also, we can run this service on demand to fetch more questions say when a user viewed 100 out of 200 questions. It may use some machine learning algorithms to fetch questions. This also uses logs saved by the User Activity Service to populate questions in our cache using some machine learning algorithms or any other recommendation algorithms.</li><li>Search Service (Lets’s discuss this later). For now, I am considering that there is already a search service.</li><li>Notification Service. (Real-Time)</li></ol><h3>High-Level Architecture:</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Fshivam04%2Fembed%2Fpreview%2FmdqLyOE%3Fdefault-tabs%3Dhtml%252Cresult%26height%3D600%26host%3Dhttps%253A%252F%252Fcodepen.io%26slug-hash%3DmdqLyOE&amp;display_name=CodePen&amp;url=https%3A%2F%2Fcodepen.io%2Fshivam04%2Fpen%2FmdqLyOE&amp;image=https%3A%2F%2Fshots.codepen.io%2Fshivam04%2Fpen%2FmdqLyOE-512.jpg%3Fversion%3D1645450628&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/b6585e965a17bcb23dcc4d2245192cbd/href">https://medium.com/media/b6585e965a17bcb23dcc4d2245192cbd/href</a></iframe><p>ThankYou. Please do give suggestions.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=40c16d59f4e1" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>