<?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 Deepak Pant on Medium]]></title>
        <description><![CDATA[Stories by Deepak Pant on Medium]]></description>
        <link>https://medium.com/@mail-dpant?source=rss-2677decfff0d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*o7lcm9ExwqB5zc2v</url>
            <title>Stories by Deepak Pant on Medium</title>
            <link>https://medium.com/@mail-dpant?source=rss-2677decfff0d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 14:01:52 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mail-dpant/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[System design interview]]></title>
            <link>https://mail-dpant.medium.com/distributed-system-for-system-design-interview-68a018c8c65c?source=rss-2677decfff0d------2</link>
            <guid isPermaLink="false">https://medium.com/p/68a018c8c65c</guid>
            <category><![CDATA[interview-questions]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[distributed-computing]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[interview-preparation]]></category>
            <dc:creator><![CDATA[Deepak Pant]]></dc:creator>
            <pubDate>Thu, 18 Jan 2024 22:54:50 GMT</pubDate>
            <atom:updated>2024-01-27T02:29:35.019Z</atom:updated>
            <content:encoded><![CDATA[<p>Acing the system design interview need right set of knowledge , a mindset shift and knowing the basics of</p><ol><li>“Single (node) system design”</li><li>Multi node system design i.e Distributed system design.</li></ol><p>My goal with this series is to shift the way you think about system design and we will work with three pillars of reasoning through out (And they are why? , when? and how?.</p><ol><li><strong>Why?</strong> (why do you need the system )</li><li><strong>When?</strong> (When will use the system and when you will not. What are the tradeoffs )</li><li><strong>How? </strong>(How is the system able to do the task at the desired speed and scale)</li></ol><p>These three pillar are the key to understand any computer system. We will keep coming back to these questions again and again.</p><ol><li>Single node system design example involve designing a (single node) Database system, designing a file system like ext4 etc. Although this looks simple understanding these are the key to understanding the large scale distributed system and lot of ideas are borrowed from these single node “high performance” system to the distributed systems.</li></ol><p>2. Understanding a distributed system is essential in designing, implementing and maintaining a large scale system. Hence there is no surprise lot of tech companies focus their system design interviews around it. My goal for this series of blog are</p><ol><li>Improve the readers understanding the distributed systems.</li><li>Improve the readers ability to answer distributed system questions with confidence and necessary knowledge.</li></ol><p>There will be about 50 different related posts which will be best consumed sequentially. I will also have Q&amp;A style post to access your knowledge.</p><p>Lets get started:</p><ol><li><a href="https://mail-dpant.medium.com/why-using-distributed-systems-are-used-in-big-tech-f96fc7e574fa">Why and when Distributed Systems are used</a>?</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=68a018c8c65c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why and when Distributed Systems are used ?]]></title>
            <link>https://mail-dpant.medium.com/why-using-distributed-systems-are-used-in-big-tech-f96fc7e574fa?source=rss-2677decfff0d------2</link>
            <guid isPermaLink="false">https://medium.com/p/f96fc7e574fa</guid>
            <category><![CDATA[interview-preparation]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[interview-tips]]></category>
            <category><![CDATA[interview-questions]]></category>
            <category><![CDATA[distributed-computing]]></category>
            <dc:creator><![CDATA[Deepak Pant]]></dc:creator>
            <pubDate>Thu, 18 Jan 2024 22:51:57 GMT</pubDate>
            <atom:updated>2024-01-19T06:55:21.000Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Why and when Distributed Systems are used ?</strong></p><p>Distributed systems emerged from the need to scale <strong>computation and storage for large-scale data processing</strong>.</p><p>We should always frame our software system having two distinct components: Compute (usually done on CPU , GPU + RAM ) and Storage (Hard disk , SSD etc)</p><p>As a software architect you should consider using distributed systems iff either of the following two things holds true:</p><ol><li>After applying program optimization (say multi-threading, algorithmic optimization) techniques you still have slower than expected processing times. OR based on the rough calculation it is implied that single machine can’t handle the compute within the reasonable time.</li><li>Data sizes exceed what can feasibly be stored on a single machine. The threshold depends on the data and use case. If data is in TB i think it is worth considering <strong>data storage distribution</strong></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/836/1*8_T6LZTIPaL91B5m3PUm3g.png" /><figcaption>Pillar of distributed system</figcaption></figure><p>Keep in mind that the <strong>“data growth or rate of growth” is an important aspect to consider.</strong> A data based on user click and activity is most likely to grow faster than the user registration data. Given same amount of initial data in your system, which one is more prone to reach capacity errors as user registration data OR user activity (click/browsing) data?</p><p>Now lets ask what is the key fundamental enabler of <strong>distributed computing</strong>?</p><p><strong>Divide and Conquer (merge).</strong> We should be able to divide the task / data and somehow merge the results back from each node to get the final results. As long as you can think of a way to divide and conquer your task in hand you can implement it using distributed systems. This strategy is usually application independent and hence the standard library and framework of distributed systems implement this.</p><p>Lets turn our attention to second pillar <strong>Distribution data storage</strong></p><p>Q) How do we build a storage system of 10 TB, capacity if we have many machines which are only equipped with a 1 TB hard disk, what should we do then?</p><p><strong>Expand horizontally (And not vertically by adding capacity to single system) ! </strong>Instead of getting a 10 TB hard drive single system, build one with smaller 1 TB systems. This has several advantages !</p><ol><li>Economy (smaller disks systems are cheaper).</li><li>It Distributes data so it resides in the same machine/node OR at least rack where data is being processed.</li><li>Higher IO throughput can be achieved as IO tasked can be done in parallel.</li></ol><p><strong>Lets take a classical concrete example</strong></p><p>Given <strong>“1 million documents each of which have 10 MB of text and your job is to create a word frequency count of the corpus” </strong>This is kind of problem which is very classic and canonical for search engines.</p><p><strong>Q) Do you think this can be done by just a single machine with 16 CPUs in less than 10 mins?</strong></p><p>Lets try to estimate. 1 Million (files) X 10 MB (per file) == 10 TB of total data.</p><p>How much do you think it will take to load this to memory from a fast SSD?</p><p><strong>Fast SSD can load 1GB per second </strong>so 10 TB = 10 x 1000 seconds to load = <strong>166 mins. </strong>This does not include any processing time etc. its time to just load the data with state of art SSD’s. I think you got the point. At some point it will be impractical to get the work done by single computer for such a large scale task! Hence we need two or more computers working together for common goal forming distributed computer.</p><p>One aspect to notice in the above problem is <strong>clear division of work</strong> in smaller chunks . You can imagine a set of few files processed by a single machine (using multi-threading) and hence the entire set of 1 Million files are distributed to N machines and later combined to get the final results. Hence this type of problem is very well suited for distributed computing ( we will talk more about it in map-reduce paradigm)</p><p><strong>Q) Is there a high level of guidance on when to use distributed systems vs single machine system?</strong></p><p>Here is my thumb rule on deciding which type of system might be needed based on the size of data?</p><ul><li>In GBs: If the performance goals are not too aggressive, Single CPU might do the job with careful optimizations!</li><li>Low TBs: Small-scale distributed systems, or high-performance data warehousing needed to achieve decent performance</li><li>High TBs: Small-to-medium-scale distributed systems is needed to achieve decent performance</li><li>in PB: Large-scale distributed systems are needed to achieve decent performance</li></ul><p>Question to ponder and consider?</p><p>Q1) What are the key challenges in distributed storage?</p><p>Q2) Can you outline the difference between multitasking, multiprocessing , and multi threading</p><p><strong>This blog is part of the </strong><a href="https://mail-dpant.medium.com/distributed-system-for-system-design-interview-68a018c8c65c"><strong>distributed system series </strong></a><strong>here. I highly encourage to consume the content in the order to gain maximal understanding.</strong></p><p><strong>Further reading:</strong></p><p><a href="https://github.com/donnemartin/system-design-primer?tab=readme-ov-file#latency-numbers-every-programmer-should-know">Latency and throughput number every programmer need to know</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f96fc7e574fa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sqlite Commands and concepts.]]></title>
            <link>https://mail-dpant.medium.com/sqlite-commands-and-concepts-721ae8325484?source=rss-2677decfff0d------2</link>
            <guid isPermaLink="false">https://medium.com/p/721ae8325484</guid>
            <category><![CDATA[sqlitedatabase]]></category>
            <category><![CDATA[sqlite3]]></category>
            <category><![CDATA[sqlite]]></category>
            <dc:creator><![CDATA[Deepak Pant]]></dc:creator>
            <pubDate>Sun, 07 Mar 2021 23:33:37 GMT</pubDate>
            <atom:updated>2021-03-08T06:29:12.725Z</atom:updated>
            <content:encoded><![CDATA[<p>TLDR: sqlite3 can be a OK choice when the size of database is less than ~10 GB or ~100M rows and your webpage or requirement is not having lot of concurrency.</p><p><strong>Installation</strong></p><pre>pip3 install sqlalchemy<br>sudo apt-get install sqlite3<br>sudo apt install sqlitebrowser<br>sudo apt install sqlitebrowser</pre><p><strong>Turn on header</strong></p><pre>sqlite3&gt; .h on</pre><p><strong>Create/open a database</strong></p><pre>sqlite3 db_name.db</pre><p><strong>List all table and their schema</strong></p><pre>.schema</pre><p><strong>Understand your query bottleneck</strong></p><p>Following can help you understand the bottleck and if index are applied during the query processing</p><pre>sqlite&gt; EXPLAIN QUERY PLAN  &lt;QUERY&gt; </pre><pre>sqlite&gt; PRAGMA index_list(&#39;stock_price_minute_data&#39;);</pre><pre>sqlite&gt; PRAGMA index_info(&#39;sqlite_autoindex_stock_price_minute_data_1&#39;);</pre><p><strong>Read a sql script and execute it</strong></p><pre>.r &lt;my_sql_script.sql&gt;</pre><p><strong>Do VACCUM (compaction)</strong></p><p>Useful when you dropped lot of tables (to reclaim the storage)</p><pre>$sqlite3 /path/to/db/foo.db &#39;VACUUM;&#39;</pre><p>Attaching multiple databases with one cursor (command)</p><pre>ATTACH &#39;/home/dpant/stock_trade/dbf/ticker.db&#39; AS tickerdb</pre><p><strong>Show all the attached db</strong></p><pre>.databases</pre><p><strong><em>Pros of sqlitedb</em></strong></p><p>In process database, easy to start with.</p><p>Decent choice to use when db size is &lt; 10 GB.</p><p><strong>Is sqlite3 right and adequate for you?</strong></p><p><a href="http://Appropriate Uses For SQLite SQLite is not directly comparable to client/server SQL database engines such as MySQL, Oracle, PostgreSQL, or SQL…sqlite.org">read </a>here more about it</p><p><strong><em>Some shortcoming of sqlitedb</em></strong></p><p>Easily corruptable when db file size grows. My db got corrupted when the file size grew &gt; 30GB. usage of sqlitebrowser in big database file also corrupt it. If you choose to use sqlite for large databases please backup frequently!</p><p>You can’t change column datatype after you created the table. Workaround is to created new table and copy the data</p><p>you can’t change drop constraint after you apply them to table.</p><pre>INSERT INTO &lt;new_table&gt; SELECT *  FROM &lt;old_table&gt;;</pre><p><strong>Concurrency &amp; write locks</strong></p><p>Write ops locks the entire database, and it will not be available for read. if you are doing bulk write for extended period of time your db will be unavailable for that period of time</p><p><strong>storage:</strong> I found the storage used by sqlite3 more than postgres. Most of this difference comes from index size. sqlite3 usually have 35% size used for index. I found that only 25% for postgres (for same schema and data)</p><p><strong>Word of caution about composite index</strong></p><p>If you are making composite index (column1, column2) it matter what is the first field in the composite index. your query will only use the index if</p><pre>select * from table_name where column1 = &#39;x&#39;<br>OR <br>select * from table_name where column1 = &#39;x&#39; and column2 = &#39;y&#39;</pre><p>when you use query like, it will not use index</p><pre>select * from table_name where column2 = &#39;y&#39;<br>OR <br>select * from table_name where column1 = &#39;x&#39; OR column2 = &#39;y&#39;</pre><p><strong>Performance</strong></p><p>For details about sqlite3 performace please <a href="https://sqlite.org/speed.html">read</a>. Gist is sqlite is not much slower, but in practise it become more unstable (frequent db corruption) when database size grows.</p><p>Insertions (Write performace) will become slower when table grows (&gt; 5GB) and if it have index (PK). Read this stackoverflow <a href="https://stackoverflow.com/questions/784173/what-are-the-performance-characteristics-of-sqlite-with-very-large-database-file">answer</a> which is similar conclusion i made.</p><p>if you want to do bulk insert drop all indexes ( including primary key which create implicit index) and do insert. dropping index is not allowed so create new table copy data and delete the old table</p><p><strong>Use sqlite3_analyzer </strong>to know exact storage usage from sqlite3</p><pre>sudo apt-get install lib32z1<br>and then download the sqlite3_analyzer from the official website</pre><p><strong>Sqlite3 query optimizer overview</strong></p><p>Read this <a href="https://sqlite.org/optoverview.html">document </a>which will give you more insight how queries are processed. this is an amazing read.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=721ae8325484" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My experience with timescaledb Compression]]></title>
            <link>https://mail-dpant.medium.com/my-experience-with-timescaledb-compression-68405425827?source=rss-2677decfff0d------2</link>
            <guid isPermaLink="false">https://medium.com/p/68405425827</guid>
            <category><![CDATA[timescaledb]]></category>
            <category><![CDATA[postgres]]></category>
            <dc:creator><![CDATA[Deepak Pant]]></dc:creator>
            <pubDate>Sat, 06 Mar 2021 02:59:25 GMT</pubDate>
            <atom:updated>2021-03-06T06:00:20.948Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>TLDR</strong>: I got a response from Michael about the the space inflation problem i am observing. You can see the response in the comment. The problem here is my chunks are too small &lt;1 MB and compress_segmentby by stock ticker will make each segment too small, hence a lot of overhead at db level. Either use orderby option or <a href="https://docs.timescale.com/api#set_chunk_time_interval">set_chunk_time_interval</a> to make the chunk time interval bigger value</p><p><strong>Full story.</strong></p><p>I took ~28 Million data points of stock price data and put it in postgres.</p><p>It was all tradable stocks daily data going max back in the history.The total size of data was ~1.8GB.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/908/1*GwHVAbD6Sn7qAH1TGhBKDw.png" /></figure><p>The schema looks like this</p><pre>CREATE TABLE stock_price_daily_all_tradable (<br>        ticker TEXT NOT NULL,<br>        date TIMESTAMP NOT NULL,<br>        open REAL NOT NULL, <br>        high REAL, <br>        low REAL , <br>        close REAL, <br>        volume FLOAT,<br>        PRIMARY KEY (date , ticker)<br>    );</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/741/1*f2d9meo9LKicL61ed9LCdg.png" /><figcaption>SELECT query in the table</figcaption></figure><p>I migrated this to timescaledb hyper tables using this tutorial in the <a href="https://docs.timescale.com/latest/getting-started/migrating-data">webpage</a></p><p><strong>Short summary of migration</strong></p><pre>CREATE TABLE new_table (LIKE old_table INCLUDING DEFAULTS INCLUDING CONSTRAINTS EXCLUDING INDEXES);<br>-- Assuming &#39;time&#39; is the time column for the dataset SELECT create_hypertable(&#39;new_table&#39;, &#39;time&#39;); </pre><pre> -- Insert everything from old_table <br>INSERT INTO new_table SELECT * FROM old_table;</pre><p><strong>Timescale hypertable size</strong></p><p>The hypertable size is much higher than the postgre. Roughly ~2.3G.This looks to be a big hit in space ~500 MB</p><pre>daily_price=# SELECT hypertable_detailed_size(‘stock_price_hyper’) ;<br> (2024120320,264527872,25296896,<strong>2313945088</strong>,)</pre><p>Now i thought turning on compression mode will help but i didn’t, in reality it increased the size</p><pre>daily_price=# ALTER TABLE stock_price_hyper SET ( timescaledb.compress,<br>timescaledb.compress_segmentby = &#39;<strong>ticker</strong>&#39;<br>);</pre><pre>SELECT add_compression_policy(&#39;stock_price_hyper&#39;, INTERVAL &#39;7 days&#39;);</pre><p>The total size actually doubled.</p><pre>daily_price=# SELECT hypertable_detailed_size(&#39;stock_price_hyper&#39;) ;<br> (4452524032,238190592,50585600,<strong>4741300224</strong>,)</pre><p>All the chunks are already compressed as seen in the following command</p><pre>SELECT before_compression_total_bytes,after_compression_total_bytes, node_name<br>FROM chunk_compression_stats(‘stock_price_hyper’);</pre><pre>                         606208 |                       1105920 | <br>                         499712 |                       1114112 | <br>                         606208 |                       1114112 | <br>                         606208 |                       1114112 | <br>                         606208 |                       1114112 |</pre><p>The problem here is my chunks are too small &lt;1 MB and compress_segmentby by stock ticker will make each segment too small, hence a lot of overhead at db level. Either use orderby option or <a href="https://docs.timescale.com/api#set_chunk_time_interval">set_chunk_time_interval</a> to make the chunk time interval bigger value</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=68405425827" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Summary of experience in writing trading app storage layer]]></title>
            <link>https://mail-dpant.medium.com/summary-of-experience-in-writing-trading-app-storage-layer-840a929ac612?source=rss-2677decfff0d------2</link>
            <guid isPermaLink="false">https://medium.com/p/840a929ac612</guid>
            <category><![CDATA[database]]></category>
            <category><![CDATA[trading-system]]></category>
            <category><![CDATA[postgres]]></category>
            <category><![CDATA[timescaledb]]></category>
            <category><![CDATA[sqlite]]></category>
            <dc:creator><![CDATA[Deepak Pant]]></dc:creator>
            <pubDate>Fri, 05 Mar 2021 22:51:09 GMT</pubDate>
            <atom:updated>2021-03-07T22:38:01.591Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>System setup</strong>. Windows 10 Home (host) + VM (Virtualbox 6.2) running ubuntu 20. 20 GB RAM and a I5 processor 12 threads. Both windows and VM are installed in SSD (1TB)</p><p><strong>Data is hard to acquire:</strong> It is very hard to get good reliable datasource for stock data. I am using yfinance (not official yahoo api) for daily data and polygon.io ($199/month) for minute data. I am quite happy with their performance. Its not cheap, i could not find any cheaper (free) alternative for data source.</p><p><strong>sqlite:</strong> works well (speed) when the size of the database &lt; 10G. My daily data of all ~9K ticker records for (max history) is ~4 GB So it works very well. For the minute data only 550 tickers, going back 5 years in time is around 35 G. This is where sqlite start to chock. (Slow write performance, ~200 Writes/Sec). In a smaller size DB (&lt;10GB size) it is 2–3K Writes/Sec. Also notice the size of DB grows very fast, if i have choose to store all tradable symbols minute data for 5 year i am going to have a DB size of ~900 G.</p><p>Sqlite does not have good concurrency support. My webapp goes offline (read ops) as db returns error while my data fetcher scripts update the DB (every night) with new data</p><p>sqlite database is easily corruptible. Many time it got corrupted when the sqlitebrowser got hung and i have to kill it. I was not able to read the db again. Luckily i have a backup (copy of the db file)</p><p>Storing 5 year historical data of SNP 500 is not trivial , its almost 300 Million data points . There are multiple ways to handle this. Make separate database for every year or month or week(time period) and making different tables based on symbols will help for speed. This increase the code complexity a lot as you are doing sharding yourself. This makes migration (to other databases) also hard (as you might want to merge this all tables and db to single dbs). In sqlite3 Tables in multple dbs can use ATTACH to bind all these database to same connection objects. There is a max limit on how many ATTACH one can do in a single connection object.</p><p>Following query in a (single) combined 28G table will be extremely fast and resolves in sub seconds</p><pre>select count(*) from stock_price_minute_data where ticker = &#39;SNPS&#39;;</pre><p><strong>Storage overhead:</strong></p><p>The is a considerable overhead of storing data in sqlite3 (or any database) the overhead comes from variety of reasons: index, padding, empty db pages etc. some of this storage (usually ~10% max) can be recovered by using VACUUM command (works both in postgre and sqlite3). There is an option of auto VACUUM too.</p><p>I tried VACCUM command which usually reclaims about 10% of space by removing the empty page overhead and rearranging the rows etc</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/760/1*5UFmn4FDGNeGg-M18F_J2w.png" /><figcaption>VACUUM in sqlite3. Saves a bit in DB size</figcaption></figure><p>To give a concrete example when i calculate the raw size of data for one of my storage table (row size * # of rows) it turn out to be 17MB while the sqlite3 took almost 47 MB to store it. Used following query to find the size of sqllite3 table size (Notice following command output does not includes the index overhead etc)</p><pre>SELECT SUM(&quot;pgsize&quot;) FROM &quot;dbstat&quot; WHERE name=&#39;stock_price_minute_data_A&#39;;</pre><p>Another important take away is even though sqlite3 is not a type strict database for application using lot of data it is important to specify the type in schema. This makes a lot of difference in the database size (or table size)</p><p>My initial schema was mentioned below. Notice the fields which are not specified will be interpreted as text and due to floating point nature of numbers in stocks it might take lot of space. This also create problem while migration to other database which are type strict (postgres)</p><pre>CREATE TABLE stock_price_daily_all_tradable (<br>        ticker TEXT NOT NULL,<br>        date TIMESTAMP NOT NULL,<br>        open NOT NULL, <br>        high, <br>        low , <br>        close, <br>        volume,<br>        PRIMARY KEY (ticker , date)<br>    );</pre><p>So the correct way to specify a schema is</p><pre>CREATE TABLE stock_price_daily_all_tradable (<br>        ticker TEXT NOT NULL,<br>        date TIMESTAMP NOT NULL,<br>        open REAL NOT NULL, <br>        high REAL, <br>        low REAL, <br>        close REAL, <br>        volume REAL,<br>        PRIMARY KEY (ticker , date)<br>    );</pre><p>Above schema changed the table size from 2.3 GB to 2.2 GB (relative minor savings), but this will be a major saving when we import the data to postgres.</p><p>Since my database size is 3.3 GB roughly a 1GB of space is going for index?</p><p>sqlite3_analyzer is another good tool to figure out what % of storage is going where.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/817/1*YvB5ez-Ok6VnxPQeD8n_NA.png" /><figcaption>sqlite3_analyzer results</figcaption></figure><p>Postgres is bit better with storage usage. For my daily stock price (all tickers, max history) sqlite3 took ~3.5 GB of total space, postgres was 1.8GB table size + 890 MB (index size) = 2.6 GB total space so it is more efficient storage wise.</p><p>postgres index size can be checked using following command</p><pre># Gives index size</pre><pre>testdb ==&gt; SELECT pg_indexes_size(&#39;stock_price_daily_all_tradable&#39;)</pre><pre># Gives table size</pre><pre>testdb ==&gt;\dt+</pre><p><strong>Data strorage compression</strong></p><p>So compressing this further is not possible natively. sqlite3 does not provide any built in capabilities for compression during storage. There are some hacky way to compress using extensions, but i don’t know how stable they are. same is true to postgres. To use real compression in postgres (for full table) you need to have postgres pro version.</p><p><strong>Connection object: (A word of caution)</strong></p><p>One should create sqlite3 connection object local to the function you are using. if you create a global object and using it across the function you will end up having race condition when multiple function start using database at same time (very common in webapp and cronjob scenerio). connection object and cursor are run in thread and if you share it across you are cobbling the data.</p><p><strong>Migration from sqlite3 → postgres</strong></p><p>While sqlite3 is a good alternative to start your storage solution, you will quickly release (due to above mentioned reasons) that postgres is a better choice for storage.</p><p>Migration is a bit pain in database world, it takes time and you might have to write some custom scripts to do it. Also sqlite3 is not that type strict while postgres is so same SQL syntax for creating table (CREATE TABLE ….) will not work in both without modification</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=840a929ac612" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Setting up PostgreSQL + timescaledb (extension)]]></title>
            <link>https://mail-dpant.medium.com/setting-up-postgresql-timescaledb-extension-10ac3b85a791?source=rss-2677decfff0d------2</link>
            <guid isPermaLink="false">https://medium.com/p/10ac3b85a791</guid>
            <category><![CDATA[timescaledb]]></category>
            <category><![CDATA[postgresql]]></category>
            <dc:creator><![CDATA[Deepak Pant]]></dc:creator>
            <pubDate>Fri, 05 Mar 2021 05:23:31 GMT</pubDate>
            <atom:updated>2021-03-10T20:21:21.275Z</atom:updated>
            <content:encoded><![CDATA[<p>This blog capture my efforts and lessons learned during the migration of stock trading data from sqlite3 → Postgres + timescaledb extension</p><p><strong>Installation and setup</strong></p><blockquote><strong>update source repos</strong></blockquote><pre>echo “deb <a href="http://apt.postgresql.org/pub/repos/apt/">http://apt.postgresql.org/pub/repos/apt/</a> $(lsb_release -c -s)-pgdg main” | sudo tee /etc/apt/sources.list.d/pgdg.list</pre><pre>wget — quiet -O — <a href="https://www.postgresql.org/media/keys/ACCC4CF8.asc">https://www.postgresql.org/media/keys/ACCC4CF8.asc</a> | sudo apt-key add -</pre><pre>sudo apt-get update</pre><pre>sudo add-apt-repository ppa:timescale/timescaledb-ppa</pre><pre>sudo apt-get update</pre><blockquote><strong>Install postgreSQL and addon timescaledb</strong></blockquote><pre>sudo apt install timescaledb-2-postgresql-13</pre><pre>tuneup the timescaledb</pre><pre>sudo timescaledb-tune </pre><p><strong>Basic command of PostgreSQL</strong></p><p><em>logging into the postgreSQL using postgres user. Follow this </em><a href="https://wajeeh-ahsan.medium.com/fatal-peer-authentication-failed-for-user-postgres-954e061c7368"><em>blog</em></a></p><p>bottomline is the default user postgres does not comes with password and you just have to login from your machine sudo password to get the database shell and change its password</p><pre>sudo -u postgres psql</pre><pre>postgres<strong>=#</strong> <strong>ALTER</strong> <strong>USER</strong> postgres PASSWORD &#39;NewPassword&#39;;<br><strong>ALTER</strong> <strong>ROLE</strong></pre><p>OR</p><pre>\password postgres</pre><p><strong>Create a database and giving access to a another db user</strong></p><p>This <a href="https://medium.com/coding-blocks/creating-user-database-and-adding-access-on-postgresql-8bfcd2f4a91e">blog</a> is helpful.</p><pre>sudo -u postgres psql<br>postgres=# create database mydb;<br>postgres=# create user myuser with encrypted password ‘mypass’;<br>postgres=# grant all privileges on database mydb to myuser;</pre><p><strong>List all databases</strong></p><pre>\l+</pre><p><strong>Change database</strong></p><pre>postgre=# \c &lt;database_name&gt; </pre><p>eg \c nyc_data</p><p><strong>list all database users</strong></p><pre>postgre=# <strong>\du+</strong></pre><p><strong>list all tables in a database along with size</strong></p><pre>postgre=# \dt+</pre><p><strong>List table schema (including constraints)</strong></p><pre>my_database=&gt;\d+ table_name</pre><p><strong>More advanced command</strong></p><pre>ALTER TABLE snp_500_tickers ADD PRIMARY KEY (Symbol);</pre><pre>DELETE FROM &lt;TABLE_NAME&gt;</pre><pre>SELECT table_name, column_name , data_type   from information_schema.columns WHERE table_name = &#39;stock_all_tradable&#39;;</pre><pre>DROP SEQUENCE &lt;sequence_name&gt; ;</pre><pre>CREATE SEQUENCE stock_id_sequence START WITH 9495;</pre><pre>ALTER TABLE stock_all_tradable ALTER COLUMN id SET DEFAULT nextval(&#39;stock_id_sequence&#39;);</pre><pre>\pset # list the current configuration of display</pre><pre>\pset tuple_only # make sure to set it off</pre><pre>EXPLAIN PLAN &lt;QUERY&gt;</pre><p><strong>Attach timescale db extension to database</strong></p><p>After creating a database if you want to use the timescaledb extension you need to use. Go inside the particular database you want to use</p><pre>\c my_database<br>CREATE EXTENSION IF NOT EXISTS timescaledb CASCADE;</pre><p><strong>Configure the postgres admin UI (pgadmin4)</strong></p><pre>sudo apt-get install curl</pre><pre>sudo curl <a href="https://www.pgadmin.org/static/packages_pgadmin_org.pub">https://www.pgadmin.org/static/packages_pgadmin_org.pub</a> | sudo apt-key add</pre><pre>sudo sh -c &#39;echo &quot;deb <a href="https://ftp.postgresql.org/pub/pgadmin/pgadmin4/apt/$(lsb_release">https://ftp.postgresql.org/pub/pgadmin/pgadmin4/apt/$(lsb_release</a> -cs) pgadmin4 main&quot; &gt; /etc/apt/sources.list.d/pgadmin4.list &amp;&amp; apt update&#39;</pre><pre>sudo apt install pgadmin4</pre><pre>#Launch the webserver and visit the admin page</pre><pre>sudo /usr/pgadmin4/bin/setup-web.sh</pre><pre><a href="http://127.0.0.1/pgadmin4">http://127.0.0.1/pgadmin4</a></pre><p><strong>Migrating data using pgloader</strong></p><p>Before migration: Make sure your table from sqlite3 have correct datatypes. Also make sure the database you want to migrate the tables to should exist in postgres. Also lot of time i had migration error because of datatype conversion not possible.</p><pre>pgloader pgloader_script</pre><p>pgloader_script will look like</p><pre>load database <br>    from sqlite:///home/dpant/stock_trade/dbf/daily_price.db<br>    into postgresql:///minute_price_data_db<br>with include drop, create tables, create indexes, reset sequences      <br>set work_mem to &#39;16MB&#39;, maintenance_work_mem to &#39;512 MB&#39;;</pre><pre>PS: This blog post will continuously update for next few days</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=10ac3b85a791" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Design a Search Engine]]></title>
            <link>https://mail-dpant.medium.com/design-a-search-engine-c99c121d99df?source=rss-2677decfff0d------2</link>
            <guid isPermaLink="false">https://medium.com/p/c99c121d99df</guid>
            <category><![CDATA[system-design-interview]]></category>
            <dc:creator><![CDATA[Deepak Pant]]></dc:creator>
            <pubDate>Sun, 13 Dec 2020 18:44:20 GMT</pubDate>
            <atom:updated>2020-12-13T18:44:20.664Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Major components of search engine are</strong></p><p>Crawler ← → Indexer ← → Query processing Engine</p><p>before you run indexer in the crawled documents you need to</p><ol><li>clean the noise (remove hyperlink and other infomation which is not needed)</li><li>remove the stop words (The,is,a,….) They convey no information and are bad for the index (blow up memory)</li><li>Do stemming of the works : eg quickly and quick should be represented as same</li></ol><p><strong>Indexer: (is the heart of any search system). See Lucene architecture for more detail</strong></p><p>Will index all the document and create a inverted index for fast searching</p><p><strong>Inverted index</strong> <strong>Data structure in C++ this can be</strong></p><p><strong>unordered_map&lt;string,list&lt;int,int&gt;&gt; invertedIndex;</strong></p><p>the key is all the terms (strings) in the your documents.</p><p>The list represent two integer .&lt;<strong>doc_id,position_in_doc&gt;</strong>. <strong>These list are sorted by document id. This helps later in merge operation ( phrase queries)</strong></p><p><strong>How to handle suffix queries? eg “las*”</strong></p><p>in that case you need to have the inverted index like. Here you can apply the binary search in the map keys.</p><p>map&lt;string,list&lt;int,int&gt;&gt; inverted-Index.</p><p><strong>Distributed index?</strong></p><p>Mostly the index stay on memory (RAM) for fast performance. if the collection is too large (internet) you need to have this index in multiple systems (shard) and merge the results after the query is done in each index shard. A lot of effort and energy is poured in to compact the data structures so more index is packed in the memory of one shard.</p><p>Another interesting fact is how to snapshot the shard of a index? we need a way to recover from induvial shard failure</p><p>Incremental indexing is another interesting features of a indexers. How do you accumulate changes done in a collection of documents without running the full indexing again?</p><p>An extremely good short course to understand all the indexing related issue are explained in the following videos</p><p><a href="https://www.youtube.com/playlist?list=PLBv09BD7ez_448q9kRfZRxYb3cbeEanRb">(165) IR7 Inverted Indexing — YouTube</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c99c121d99df" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Links to Study]]></title>
            <link>https://mail-dpant.medium.com/links-to-study-7521abb75d12?source=rss-2677decfff0d------2</link>
            <guid isPermaLink="false">https://medium.com/p/7521abb75d12</guid>
            <dc:creator><![CDATA[Deepak Pant]]></dc:creator>
            <pubDate>Sun, 15 Mar 2020 20:24:37 GMT</pubDate>
            <atom:updated>2020-03-15T20:24:37.271Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://medium.com/techlog/chord-building-a-dht-distributed-hash-table-in-golang-67c3ce17417b">Chord: Building a DHT (Distributed Hash Table) in Golang</a></p><p>Cassandra modelling</p><ul><li><a href="https://tech.ebayinc.com/engineering/cassandra-data-modeling-best-practices-part-1/">Cassandra Data Modeling Best Practices, Part 1</a></li><li><a href="https://www.rubyscale.com/post/143067470585/basic-time-series-with-cassandra">Basic Time Series with Cassandra</a></li></ul><p>Write heavy workload. <strong>Choose DB with LSM indexed DB</strong></p><ul><li><a href="https://www.quora.com/Which-NoSQL-DB-is-more-advantageous-for-IoT-data">Which NoSQL DB is more advantageous for IoT data?</a></li><li><a href="http://bytecontinnum.com/2016/02/choosingtorechoice/">Art of choosing a datastore</a></li></ul><p><strong>General difference between sql and no-sql</strong></p><p><a href="https://www.sitepoint.com/sql-vs-nosql-differences/">SQL vs NoSQL: The Differences - SitePoint</a></p><p><strong>dropbox system design by Naren</strong></p><p><a href="https://imgur.com/a/pzKb4f7">Imgur</a></p><p><strong>Netflix stream processsing</strong></p><p><a href="https://www.infoq.com/presentations/apache-flink-streaming-app/">Patterns of Streaming Applications</a></p><p>SHA perfomance metrics</p><p><a href="https://automationrhapsody.com/md5-sha-1-sha-256-sha-512-speed-performance/">MD5, SHA-1, SHA-256 and SHA-512 speed performance | Automation Rhapsody</a></p><p>Youtube scaling</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fw5WVu624fY8%3Ffeature%3Doembed&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Dw5WVu624fY8&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fw5WVu624fY8%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/fdafe621cce7bbcc853c1e3597581635/href">https://medium.com/media/fdafe621cce7bbcc853c1e3597581635/href</a></iframe><p>Indexing / Search Engine</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F5444z-L2V2A%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D5444z-L2V2A&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F5444z-L2V2A%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/e862af5557a72cb04cdc57e336995904/href">https://medium.com/media/e862af5557a72cb04cdc57e336995904/href</a></iframe><p>ngnx</p><p><a href="https://www.nginx.com/blog/inside-nginx-how-we-designed-for-performance-scale/">Inside NGINX: Designed for Performance &amp; Scalability</a></p><p>Haproxy architecure</p><p><a href="http://www.haproxy.org/download/1.2/doc/architecture.txt">http://www.haproxy.org/download/1.2/doc/architecture.txt</a></p><p>Strore session in centralied location</p><p><a href="https://www.lecloud.net/post/7295452622/scalability-for-dummies-part-1-clones">Scalability for Dummies - Part 1: Clones</a></p><p>Load Balancer</p><p><a href="http://wtarreau.blogspot.com/2006/11/making-applications-scalable-with-load.html">Making applications scalable with Load Balancing</a></p><p>HAProxy Config</p><p><a href="https://www.haproxy.com/blog/load-balancing-affinity-persistence-sticky-sessions-what-you-need-to-know/">Load Balancing, Affinity, Persistence, Sticky Sessions: What You Need to Know - HAProxy Technologies</a></p><p><strong>Scaling storage</strong></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FDg76cNaeB4s%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DDg76cNaeB4s&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FDg76cNaeB4s%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/c4cc22e2d2ebaa7ea85dce8652e3f4f6/href">https://medium.com/media/c4cc22e2d2ebaa7ea85dce8652e3f4f6/href</a></iframe><p>Scale timeseries databases in netflix</p><p><a href="https://netflixtechblog.com/scaling-time-series-data-storage-part-i-ec2b6d44ba39">Scaling Time Series Data Storage — Part I</a></p><p>Netflix timeseries db</p><p><a href="https://netflixtechblog.com/scaling-time-series-data-storage-part-i-ec2b6d44ba39">Scaling Time Series Data Storage — Part I</a></p><p><strong>Kafka Design</strong></p><p><a href="https://www.signal.co/dev-log/kafka-consumer-assignments/">Kafka Consumer Assignments - Signal</a></p><p><strong>Live stream architecure.</strong></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FIO4teCbHvZw%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DIO4teCbHvZw&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FIO4teCbHvZw%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/c86a6afea6a8be095faf3a95bede7a81/href">https://medium.com/media/c86a6afea6a8be095faf3a95bede7a81/href</a></iframe><p>Location based search + <strong>quadtree</strong></p><p><a href="http://engblog.yext.com/post/geolocation-caching">Improved Location Caching with Quadtrees</a></p><p><strong>Generating Global Unique ID</strong></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fvideoseries%3Flist%3DPLOE1GTZ5ouRPbpTnrZ3Wqjamfwn_Q5Y9A%26start%3D0&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DW6qURtqrldc&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FW6qURtqrldc%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/9865072bf5847994df12e32559a668bc/href">https://medium.com/media/9865072bf5847994df12e32559a668bc/href</a></iframe><ol><li>clocks across different computer are not synchronous all the time</li><li>NTP sometime roll back the time if it detect the computer clock is diverging (due to clock skew drift issues)</li><li>Using get_time_of_day() <strong>usec+counter+machine_name</strong> might be globally unique but slow because get_time_of_day() is slow. Also it might not be monotonically increasing (see #2)</li><li>get UUID in windows / DB’s can generate system specific globlal UID</li><li>if you need <strong>monotonically increasing global ids (you want to sequence events), </strong>best option is to just have a single server from where everyone ask for a unique id</li><li>gettimeofday() gives UTC time (sec,microsecond). but gettimeofday is slower. So you can just use machine_name+counter if you want speed. you have to backup the counter state once in a while.</li></ol><p><strong>Flikr approach: (distributed unique primary keys)</strong></p><p>Use mysql auto incr counter with only storing the last incremented number in DB (so that the size of the db dont grow). Use REPLACE INTO command</p><ul><li><a href="https://code.flickr.net/2010/02/08/ticket-servers-distributed-unique-primary-keys-on-the-cheap/">Ticket Servers: Distributed Unique Primary Keys on the Cheap</a></li><li><a href="https://www.callicoder.com/distributed-unique-id-sequence-number-generator/">Generating unique IDs in a distributed environment at high scale</a></li></ul><p><strong>Zookeeper.</strong></p><ol><li>Writes goes to the leader. OK is only sent when quorum writes happes.</li></ol><p>2. Read happens with any server. read can be stale for a while(eventual consitent)</p><p>3 Watch can be set for any ephimeral node</p><p>4. can be used for service discovery</p><p><a href="http://www.corejavaguru.com/bigdata/zookeeper/how-zookeeper-works">How Apache Zookeeper Works internally?</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7521abb75d12" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Designing Twitter]]></title>
            <link>https://mail-dpant.medium.com/designing-twitter-cbf7fe954aba?source=rss-2677decfff0d------2</link>
            <guid isPermaLink="false">https://medium.com/p/cbf7fe954aba</guid>
            <category><![CDATA[system-design-interview]]></category>
            <dc:creator><![CDATA[Deepak Pant]]></dc:creator>
            <pubDate>Sun, 26 Jan 2020 18:00:29 GMT</pubDate>
            <atom:updated>2020-01-26T18:36:06.230Z</atom:updated>
            <content:encoded><![CDATA[<p>Think of 5 most important features a product have Just list them</p><ol><li>Post a tweet</li></ol><p>2. Generate Home timeline</p><p>3. Add Following functionality</p><p>3. Search functionality</p><p>4. User Authentication and creation service</p><p>5. Ads</p><p>You only have to focus of 1 to 3 of these in a interview settings. Which one of them will come from the interviewer. So Ask!</p><p><strong>Make API (REST)</strong></p><p>twitter.com/tweet</p><p>twitter.com/home</p><p>User id and authentication (session_id) goes in header.</p><p>Make basic RDBMS based schema. Most likely it wont scale for 1 B + user</p><ol><li><strong>Precompute timeine for all active users once a tweet arrives:</strong></li></ol><p><strong>Fanout and build timeline once the tweet is done. Also dump the tweet to a DB for persistency.</strong></p><p>Do home timeline in in-memory DB with Redis as twitter do. Key is to precompute the hometime line for active users. Any tweet done by user X will update the timeline (stored as Redis List) of all the user who are following X. To improve the space utilization you can keep only last 3 days or (past 30 tweets) in the rediss cluster.</p><p>One Redis node will not be able to hold the timeline of all the users. So you need to <strong>Shard</strong>.</p><p><strong>what if the fanout is too high (Think Justin bebber).</strong></p><p>You have multiple ways to do this. Handle in batches (10K each in every 2 mins) slowely.</p><p>Only update timeline of users who are active in last 1 day.</p><p><strong>2. Building timeline on the fly.</strong></p><p>Also if we decide to generate the timeline on the fly we need the follwing information very fast . Last 30 tweets from a user X. so if a user U [who is folloing X1… Xn] viewing his timeline we have to call the LastestTweet(X1)…. LastestTweet(XN). and merge them. Notice it generates the requirment of quering lastest tweet by a userid. How to get that? We need some sort of index on creation time</p><p><strong>What to shard on:</strong></p><p><strong>Userid?</strong> This can be not a good way to store the a user in same shard. Some user can be very popular. We have to fetch their tweets to update many followers timeline.</p><p><strong>tweetId?</strong></p><p>Now same persion tweet will be sharded to very different server. This will increase the latency because to generate your self timeline you have to hit 20 different servers!</p><p><strong>timestamp [32bits]+ tweetid [auto incr counter]</strong></p><p>The above will make the range query for the latest tweet faster as we just have to just index the timestamp_tweetid. and apply range query. We still have to query many servers to generate the timeline. But we dont need a secondary index on the creation time. (this increase the write speed)</p><p>you also need to replicate the timeline ateach shard. This is for the resilency (if any node Redis node fails we still want to keep serving the time with the same speed)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u295YDxNFkMXr5FgJQAdfw.png" /></figure><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FKmAyPUv9gOY%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DKmAyPUv9gOY&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FKmAyPUv9gOY%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/4d5f9b08396114f907a3d2f428f17756/href">https://medium.com/media/4d5f9b08396114f907a3d2f428f17756/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cbf7fe954aba" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Designing Online Game (System Design)]]></title>
            <link>https://mail-dpant.medium.com/designing-online-game-system-design-d23247cce9ff?source=rss-2677decfff0d------2</link>
            <guid isPermaLink="false">https://medium.com/p/d23247cce9ff</guid>
            <category><![CDATA[online-game-design]]></category>
            <category><![CDATA[design-systems]]></category>
            <dc:creator><![CDATA[Deepak Pant]]></dc:creator>
            <pubDate>Fri, 24 Jan 2020 04:04:27 GMT</pubDate>
            <atom:updated>2020-01-24T04:04:27.406Z</atom:updated>
            <content:encoded><![CDATA[<p>It is crutial to recognize that multiplayer online game need synchronization of their states across various players with the following constraints.</p><ol><li>Latency should be minimal.</li><li>Minimal bandthwidth taken for synchronization</li><li>Less jitter and choppyness in state update</li></ol><p>First lests model our game as bunch of objects (character, scenes elements etc) and each of this object have certian location , orientitaiton and other attribute. All we have to do is to synchronize these object across all the players. Synchronization can be though of a certain server. We can imagine this as a MVC kind of architechure in front end as well as backend. Model is the object states in a game for a player X, Controller running in the Server (validating the state changes) and sending update request to all the other players to update their model (and in turn views of all other players). Most single user Game can be also modelled in MVC kind of pattern.</p><p><strong>What should you do to minimize latency:</strong></p><p>Based on the speed of light and current technology:</p><ul><li>it takes atleast 40ms to reach from east to west coast.</li><li>75 ms to reach from US to Europe</li><li>150 ms from US to Asia</li></ul><p>Hence keeping your user near to the Gaming server is the key for reducing the latency!</p><p><strong>Why Do you need a gaming server, can you synchronize the states P2P within the players? </strong>This is one of the option but it is less secure. Server can act as a AS (authoritative server) to validate the inputs of the user. Remember User can hack the system and some trusted authority must validate the moves. Servers does that</p><p><strong>What can you do to reduce the bandthwidth?</strong></p><p>Can we just transmit the actions of each users say in a bitvector of 64 possible actions.? This is a good idea to do as it need very small amout of data. We have to timestamp the data to that we know the sequence in which we have to apply this. So the datastructure is &lt;command_bit_vector,timestamp,useid&gt; <strong>This is</strong> <strong>called deterministic lockstep .</strong></p><p>The problem is that system state can diverge if some of the <strong>action_bitvectors are not applied (in order). </strong>In this case the system states for all the players can diverge.</p><p><strong>State Synchronization</strong></p><p>Object_state: &lt;position,orientation,linear velocity, angular velocity&gt;</p><p>Synchronize the state of objects. you can recreate the scene just by knowing the state information for the **all the objects** This takes lot of data to synchronized. (Maybe in MB’s). You can do smart encoding to compress.</p><p>You can synchronize the state of objects 30 times a second or so.You can still have jitter for inbetween time. You need a prediction module for interpolation</p><p><strong>Do i have to use TCP?</strong></p><p>TCP will block the access to packets with id N+1 if the id Nth packet is missing. Retransmission can cause lot of latency for the packet N, untill than the whole game will stall. One solution is to have a playout buffer in which we buffer K packets from the stream and then only apply them smoothly. This is same idea as buffring the movie. (This does introduce some latency due to buffering)</p><p>We can also use UDP with redundant information or a relaible UDP (RUDP) for smoother information.</p><p><strong>Rules of game:</strong></p><p>you have to do lot of if,else for each state of object. This can make the code messy.</p><p><strong>Use state machine rather than if else of code to handle the combination of various state,action pairs in different objects.</strong></p><p>So think object in every object as a <strong>state</strong>. And for each state you can define the possibley of options and actions. <strong>Use State design Pattern for this</strong></p><p><strong>Backend Design</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/631/1*j2uw29g6FBuGwRS7bcK9bQ.png" /></figure><p>Notice we need CDN to distribute the resources (game patches and game installers). CDN is not streaming games like movies because game is a dynamic system</p><p><strong>Patch server </strong>make sure all the player are running the same version of the game.</p><p><strong>Login Server</strong> is doing auth of the user login and password</p><p><strong>Loadbalancer + proxy server (API gateway)</strong></p><p>You Need API gateway to terminate the TCP/UDP connection.</p><p><strong>WordServers</strong> is the main server which keeps the complete index mapping of <strong>&lt;user_id,game_session_id&gt; → Area Game server</strong></p><p><strong>Area Game</strong> <strong>server </strong>is serving a region (think geographic region) of a big game area. This help is scalablity as not all players are in same area of the game. So we shard based on geo-location.</p><p>Do we have to do static assignment of the region → AreaGame Server or we need dynamic?</p><p>Static can waste resouce as it might be that few users are in one area and other area have lot of of users. Maybe do dynamic region assignment (which will be more complex)</p><p>Also Area game servers need to pass information of the various player states to the adjecent region Area Game servers.</p><p><strong>References:</strong></p><p><strong>Cover most of frontend and communication part of game design</strong></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FEU81tjgoKoI%3Fstart%3D2164%26feature%3Doembed%26start%3D2164&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DEU81tjgoKoI&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FEU81tjgoKoI%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/085e5ddcca06245f8bd763ef033ec0da/href">https://medium.com/media/085e5ddcca06245f8bd763ef033ec0da/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FK3Z1PY2vr3Q%3Ffeature%3Doembed&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DK3Z1PY2vr3Q&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FK3Z1PY2vr3Q%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/5580fcf3e2178eab5a9cb73b088f6577/href">https://medium.com/media/5580fcf3e2178eab5a9cb73b088f6577/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d23247cce9ff" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>