<?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"><channel><title><![CDATA[Lokesh Sanapalli]]></title><description><![CDATA[Hey there,

Thanks for checking my blog. My name is Lokesh Sanapalli. I am a software engineer with 8+ years of experience in building software systems that are]]></description><link>https://blog.lokesh1729.com</link><generator>RSS for Node</generator><lastBuildDate>Mon, 16 Nov 2026 00:34:22 GMT</lastBuildDate><atom:link href="https://blog.lokesh1729.com/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[System Design Interview : Multi-version Concurrency Control in Databases — The icebreaker for deciding which relational database to choose]]></title><description><![CDATA[Multi version concurrency control plays an important role in choosing relational databases. Each database management system chooses different approach]]></description><link>https://blog.lokesh1729.com/system-design-interview-multi-version-concurrency-control-in-databases-the-icebreaker-for-deciding-which-relational-database-to-choose</link><guid isPermaLink="true">https://blog.lokesh1729.com/system-design-interview-multi-version-concurrency-control-in-databases-the-icebreaker-for-deciding-which-relational-database-to-choose</guid><category><![CDATA[System Design]]></category><category><![CDATA[Databases]]></category><category><![CDATA[System Architecture]]></category><dc:creator><![CDATA[Lokesh Sanapalli]]></dc:creator><pubDate>Wed, 07 Oct 2026 06:54:25 GMT</pubDate><content:encoded><![CDATA[<img src="https://cdn.hashnode.com/uploads/covers/5ba38b8d61e0316151445985/ad8604d8-c3c2-48b9-b960-6443c5d73273.png" alt="" style="display:block;margin:0 auto" />

<ul>
<li><p>The goal of MVCC in a DBMS is to allow multiple transactions to read and write to the database simultaneously without interfering with each other when possible.</p>
</li>
<li><p>The basic idea of MVCC is that the DBMS never overwrites existing rows. Instead, for each (logical) row, the DBMS maintains multiple (physical) versions in the same or different disk pages.</p>
</li>
<li><p>When the application executes a query, the DBMS determines which version to retrieve to satisfy the request according to some version ordering (timestamp, transaction ids etc...). The benefit of this approach is that multiple queries can read older versions of rows (snapshot) without getting blocked by another query updating it.</p>
</li>
</ul>
<img src="https://learn.lokesh1729.com/images/databases/mvcc-version-chains.png" alt="MVCC: one logical row with many physical versions, and each snapshot reading the version it may see" style="display:block;margin:0 auto" />

<p>MVCC boils down to these questions</p>
<ol>
<li><p>How to store updates to the existing rows?</p>
</li>
<li><p>How to find the correct version of a row for a query at runtime?</p>
</li>
<li><p>Whether to update indexes to point to multiple versions or point to clustered index and fetch the versions from there?</p>
</li>
<li><p>How to remove expired versions that are no longer visible?</p>
</li>
</ol>
<h2>PostgreSQL</h2>
<ul>
<li><p>PostgreSQL follows the append-only method of copying the same row, applies the updates to the copied row, stores in the same tablespace, updates it's version and updates the version chain. The database engine forms a singly-linked list for the version chain.</p>
</li>
<li><p>Copying of the whole row whenever one column updates adds massive data duplication and increases storage. Whereas MySQL and Oracle stores a compact delta between the two rows instead of copying the whole tuple.</p>
</li>
<li><p>At the query time, the database engine traverse through the version chain and finds the latest version.</p>
</li>
<li><p>Old row versions also pollute the buffer cache. A sequential scan reads every page of a table, including pages that hold mostly old versions. Each such page can evict a useful page from the cache, so the cache fills with pages that carry little live data.</p>
</li>
<li><p>PostgreSQL has a protection mechanism for this. Sequential scans use a buffer access strategy with a small ring of buffers (256 kB by default) and reuse only those buffers. A large scan therefore cannot flush the working set out of the cache.</p>
</li>
<li><p>There are two ways a version chain can be stored. Newest-to-oldest (N2O) or oldest-to-newest (O2N).</p>
</li>
</ul>
<h3>New-to-old (N2O) vs old-to-new (O2N)</h3>
<p>Indexes always point to the head of the version chain. The head is the latest version in N2O, and the oldest version in O2N.</p>
<table>
<thead>
<tr>
<th></th>
<th>New-to-Old (N2O)</th>
<th>Old-to-New (O2N)</th>
</tr>
</thead>
<tbody><tr>
<td>Pointer direction</td>
<td>each version points to its previous version</td>
<td>each version points to its new version</td>
</tr>
<tr>
<td>Chain head</td>
<td>the latest version</td>
<td>the oldest version</td>
</tr>
<tr>
<td>Index</td>
<td>points at the head, so a new version moves the head → every index on that row must be updated</td>
<td>points at the head, which never changes → no index update on a new version</td>
</tr>
<tr>
<td>Where the new version goes</td>
<td>becomes the new head</td>
<td>appended at the tail</td>
</tr>
<tr>
<td>Lookup</td>
<td>head already holds the newest version, no traversal</td>
<td>walk the chain to find the version visible to the snapshot</td>
</tr>
<tr>
<td>Used by</td>
<td>most DBMSs, including Oracle and MySQL</td>
<td>PostgreSQL</td>
</tr>
</tbody></table>
<p>The O2N trade-off is the lookup cost: the DBMS may walk a long version chain before it finds the version that the snapshot may see. N2O reads the head directly, but pays an index update on every version.</p>
<img src="https://learn.lokesh1729.com/images/databases/mvcc-index-pointers.png" alt="N2O and O2N: both indexes point at the head of the version chain, and only N2O must update the index when a new version arrives" style="display:block;margin:0 auto" />

<h3>PostgreSQL - Heap-Only Tuple Optimisation</h3>
<ul>
<li><p>PostgreSQL stores the next version pointer in <a href="https://www.postgresql.org/docs/current/storage-page-layout.html#STORAGE-TUPLE-LAYOUT"><code>t_ctid</code></a> field in the row header. When a row is updated, PostgreSQL updates this field to the next version.</p>
</li>
<li><p>During the reads, to avoid traversing the entire version chain, <strong>PostgreSQL adds an entry to the leaf nodes of table’s all indexes for each physical version of a row</strong>. But, during the write/updates, the DBMS incurs additional I/O to traverse each index and insert the new entries. Accessing an index introduces lock contention in both the index and the DBMS’s internal data structures such as buffer pool cache.</p>
</li>
<li><p>Imagine having 50 columns and 10 indexes in a table, updating a row creates a new versioned row in the same tablespace, goes to all 10 indexes and creates a new leaf node that point to the new version.</p>
</li>
<li><p>Oracle and MySQL do not have this problem in their MVCC implementation because their secondary indexes do not store the physical addresses of the new versions. Instead, they store a logical identifier that the DBMS then uses to look up the current version’s physical address. But, this will make secondary index reads slower as the DBMS has to resolve the logical identifier to the physical address through the primary key index.</p>
<ul>
<li><p>MySQL’s InnoDB appends the primary key columns to each secondary index record and uses that value to search the row in the clustered (primary key) index.</p>
</li>
<li><p>Oracle stores the primary key as a logical ROWID in its secondary indexes.</p>
</li>
<li><p>The flow appears as below. From the clustered index, the DBMS obtains the physical address, then it checks the version metadata (InnoDB's DB_TRX_ID, Oracle's SCN/ORA_ROWSCN) against the reader's transaction snapshot version. If the current version isn't visible, the DBMS reconstructs the older version from the undo log / rollback segment .</p>
</li>
</ul>
<pre><code class="language-plaintext">secondary index → PK → clustered index → current physical address
                                        ↓
                    check txn id vs snapshot → reconstruct old version from undo if needed
</code></pre>
</li>
<li><p>PostgreSQL tries to avoid adding multiple index entries and storing related versions over multiple pages by creating a new copy in the same disk page (block) as the old version to reduce disk I/O. This is called "heap-only tuple" optimisation.</p>
</li>
<li><p>PostgreSQL uses the HOT approach if an update does not modify any columns referenced by a table’s indexes and the new version is stored on the same disk page as the old version.</p>
</li>
</ul>
<img src="https://learn.lokesh1729.com/images/databases/mvcc-hot.png" alt="PostgreSQL : heap-only tuple optimisation" style="display:block;margin:0 auto" />

<h3>VACUUM - Pruning of stale versions</h3>
<ul>
<li><p>PostgreSQL uses a vacuum procedure that runs periodically to clean up dead tuples from tables. Although this helps but the write-heavy workloads can bloat up the table quickly.</p>
</li>
<li><p>It runs a sequential scan on the table disk pages modified since its last run and finds expired versions using the <code>t_xmin</code> and <code>t_xmax</code> fields in the page header. A version is considered as expired if the row's transaction id is less than the current transaction id.</p>
</li>
<li><p>Even though VACUUM procedure runs periodically and cleans up dead tuples, it cannot relocate and merge the live tuples across multiple pages. It only relocates within a single page. To reclaim and return unused space, we must use VACUUM FULL which rebuilds the entire table to a new space and it comes with performance implications. VACUUM FULL also takes an <code>ACCESS EXCLUSIVE</code> lock on the table, which blocks reads and writes for the whole rebuild, so it needs downtime on the table.</p>
</li>
</ul>
<img src="https://learn.lokesh1729.com/images/databases/mvcc-vacuum.png" alt="VACUUM and VACUUM FULL" style="display:block;margin:0 auto" />

<h3>Case Study : Why Uber moved from PostgreSQL to MySQL</h3>
<ul>
<li><p><strong>Write Amplification</strong> : Every update becomes much larger and costlier when translated to the physical layer. As mentioned above, On every row update, PostgreSQL creates a new version in the same tablespace, updates every index to point to newly created version.</p>
</li>
<li><p><strong>Replication</strong> : DBMS maintains WAL (Write-Ahead Logging) to guarantee consistency and durability. They write each change (insert/update/delete) to an append-only file which will be used to recover the data in case of system crashes. When the updates happen in the master instance, instead of just the row and value updates, WAL pushes the index updates as well. This causes huge network bandwidth consumption when the replicas are not within the same datacenter.</p>
</li>
<li><p><strong>Replica MVCC impacting active transactions</strong> : If a replica has an active transaction, MVCC updates (via WAL) to the rows held by the transaction are blocked until the transaction has ended.</p>
</li>
</ul>
<img src="https://learn.lokesh1729.com/images/databases/uber-postgresql-indexes-layout.jpg" alt="Credits: Uber blog post" style="display:block;margin:0 auto" />

<p><em>Credits: Uber's blog post</em></p>
<h2>MySQL</h2>
<ul>
<li><p>While Postgres directly maps index records to on-disk locations, InnoDB (MySQL Database Engine) maps to the primary key value.</p>
</li>
<li><p>For every index lookup, we need to make two lookups. One on secondary index, second on primary index to find the disk location. That's the disadvantage. The advantage is that the row updates needs to update only the primary index records.</p>
</li>
<li><p><strong>MVCC and Index Handling</strong></p>
<ul>
<li><p>For MVCC, InnoDB copies the older rows to a special area called rollback segment (also called <a href="https://dev.mysql.com/doc/refman/9.7/en/innodb-undo-logs.html">undo logs</a>).</p>
</li>
<li><p>A secondary index does not store a physical address, and it does not store a version pointer. Each secondary index record stores the indexed columns plus a copy of the primary key columns. So the secondary index points to a primary key value, not to a row version.</p>
</li>
<li><p>A clustered index (primary key) record stores the full row plus two hidden columns. <code>DB_TRX_ID</code> holds the transaction id that last changed the row. <code>DB_ROLL_PTR</code> is the pointer into the rollback segment. That undo record pointer holds the data needed to rebuild the older version. The older versions therefore form a chain inside the rollback segment, not inside the index.</p>
</li>
</ul>
<pre><code class="language-plaintext">secondary index record: (indexed columns, PK columns)
        │
        ▼  PK value
clustered index record: (full row, DB_TRX_ID, DB_ROLL_PTR)
        │
        ▼  DB_ROLL_PTR
undo log record  ──►  older undo log record  ──►  ...
</code></pre>
<ul>
<li><p>InnoDB reads the row, compares <code>DB_TRX_ID</code> against the reader's snapshot, and if the version is not visible, follows <code>DB_ROLL_PTR</code> into the undo log. It rebuilds older versions this way until it finds one the snapshot can see.</p>
</li>
<li><p>Let's take an example. One row exists: <code>account (id=1, balance=100)</code>. Three transactions change it:</p>
<ul>
<li><p>T10 inserts the row with <code>balance=100</code>.</p>
</li>
<li><p>T20 updates <code>balance</code> to 200.</p>
</li>
<li><p>T30 updates <code>balance</code> to 300.</p>
</li>
</ul>
</li>
<li><p>The current clustered index record is the newest version. It holds <code>balance=300</code>, <code>DB_TRX_ID=T30</code>, and <code>DB_ROLL_PTR=U30</code>. This record is the head of the version chain (N2O).</p>
</li>
<li><p>Each update writes an undo record. The undo record holds two different things:</p>
<ul>
<li><p>The older values of the changed columns: the values that this update overwrote. T30 changed only <code>balance</code>, so U30 stores <code>balance=200</code>. InnoDB stores only the changed column-value pairs, not the whole row.</p>
</li>
<li><p>The old values of two hidden columns: InnoDB adds <code>DB_TRX_ID</code> and <code>DB_ROLL_PTR</code> to every row as hidden columns. They are not part of the table schema. <code>DB_TRX_ID</code> is the id of the transaction that last changed the row. <code>DB_ROLL_PTR</code> is the pointer to the undo record that holds the previous version. Before an update, InnoDB copies the old values of these two hidden columns into the undo record. For U30 these are <code>DB_TRX_ID=T20</code> and <code>DB_ROLL_PTR=U20</code>.</p>
</li>
</ul>
</li>
<li><p>The example rows below show both parts together. Both parts live in the same undo record:</p>
<ul>
<li><p>U30 holds <code>balance=200</code>, old <code>DB_TRX_ID=T20</code>, old <code>DB_ROLL_PTR=U20</code>.</p>
</li>
<li><p>U20 holds <code>balance=100</code>, old <code>DB_TRX_ID=T10</code>, old <code>DB_ROLL_PTR=U10</code>.</p>
</li>
<li><p>U10 is the insert undo of T10. It has no older version. The chain ends here.</p>
</li>
</ul>
</li>
<li><p>What happens if an older transaction reads. Let's say <code>T25</code> reads the current row:</p>
<ol>
<li><p>The clustered index lookup returns the head: <code>balance=300</code>, <code>DB_TRX_ID=T30</code>, <code>DB_ROLL_PTR=U30</code>.</p>
</li>
<li><p>Compare <code>T30</code> with the snapshot. <code>30 &gt; 25</code>, so a newer transaction changed the row. The current version is not visible.</p>
</li>
<li><p>Fetch the undo record that <code>DB_ROLL_PTR=U30</code> points to, that is U30. U30 holds <code>balance=200</code>, old <code>DB_TRX_ID=T20</code>, and old <code>DB_ROLL_PTR=U20</code>.</p>
</li>
<li><p>Apply U30. This rebuilds the previous version as <code>balance=200</code>, with <code>DB_TRX_ID=T20</code> and <code>DB_ROLL_PTR=U20</code>.</p>
</li>
<li><p>Compare <code>T20</code> with the snapshot. <code>20 &lt;= 25</code>, so this version is visible. Return <code>balance=200</code>. The reader does not reach U20.</p>
</li>
</ol>
</li>
<li><p>Similarly, snapshot T15 walks one version further: <code>30 &gt; 15</code>, so apply U30 to get <code>balance=200, trx=20</code>. <code>20 &gt; 15</code>, so apply U20 to get <code>balance=100, trx=10</code>. <code>10 &lt;= 15</code>, so return <code>balance=100</code>.</p>
</li>
<li><p>Think of the chain is like a linked list made of stored pointers, not a page scan. Each version keeps its own <code>DB_ROLL_PTR</code>. The current row points to the newest undo record. Each undo record stores the old <code>DB_ROLL_PTR</code>, which points to the next older undo record. So the chain runs from newest to oldest through the rollback segment, and the head is always the row in the clustered index (N2O).</p>
</li>
</ul>
</li>
</ul>
<h2>References</h2>
<ul>
<li><p><a href="https://www.cs.cmu.edu/~pavlo/blog/2023/04/the-part-of-postgresql-we-hate-the-most.html">CMU - Part of PostgreSQL we hate the most</a></p>
</li>
<li><p><a href="https://www.uber.com/blog/why-uber-moved-from-postgres-to-mysql/">Why uber moved from Postgres to MySQL</a></p>
</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Personal Finance - My Investment Options for FY2023-24]]></title><description><![CDATA[In this blog post, I am sharing all my investment options across different goals for FY2023-24. I have written a similar blog post for FY2022-23. In…]]></description><link>https://blog.lokesh1729.com/personal-finance-my-investment-options-for-fy2023-24</link><guid isPermaLink="true">https://blog.lokesh1729.com/personal-finance-my-investment-options-for-fy2023-24</guid><dc:creator><![CDATA[Lokesh Sanapalli]]></dc:creator><pubDate>Mon, 03 Jul 2023 03:07:18 GMT</pubDate><content:encoded><![CDATA[<p>In this blog post, I am sharing all my investment options across different goals for FY2023-24. I have written a similar <a target="_blank" href="https://blog.lokesh1729.com/personal-finance-my-investment-options-for-fy2022-23">blog post for FY2022-23</a>.</p>
<h1 id="heading-emergency-fund">Emergency Fund</h1>
<p>In FY2022-23, I invested in liquid funds for an emergency fund, despite they have given the instant redemption feature the returns are very low. So, for this year, I want to go for money market funds because they are offering good returns and I don't want an instant redemption feature.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1688353536492/55a299b2-4481-4c3c-bb64-6e163bfb2a46.png" alt="Emergency Fund" class="image--center mx-auto" /></p>
<p>I have shortlisted only two funds. Even though nippon has 5-star ratings from both agencies, the risk is moderate according to ValueResearch. So, I went ahead with <a target="_blank" href="https://www.valueresearchonline.com/funds/1731/tata-money-market-fund-regular-plan/">Tata Money Market Fund</a>.</p>
<h1 id="heading-short-term-goals">Short Term Goals</h1>
<p>For short-term goals (1-3 years), I decided to use recurring deposits than debt mutual funds because, from this financial year, <a target="_blank" href="https://12ft.io/proxy?q=https%3A%2F%2Findianexpress.com%2Farticle%2Fbusiness%2Fmarket%2Findexation-benefits-debt-mutual-funds-stand-out-against-fixed-deposits-8535261%2F">the government has removed the indexation benefit for debt mutual funds</a> which means that they are taxed as income under the same tax slab. So, there is no difference between RD and debt mutual funds. I did some research and found that Equitas is giving a <a target="_blank" href="https://www.equitasbank.com/sites/default/files/inline-files/domestic-recurring-deposit-rate.pdf">whooping 8.2% interest for RDs</a>. When it comes to security, the DICGC insures principal and interest up to a maximum amount of five lakhs. So, not to worry about it.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1688272757671/411e656a-65fd-4c3f-b216-93041740e482.png" alt="Recurring Deposits" class="image--center mx-auto" /></p>
<p>For other short-term goals like vacation, I selected Kotak Savings Fund because it is rated 5 stars by morning star and NiyoMoney also recommends it.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1688353479540/37c1a111-50b3-4403-a925-6d7429f50db8.png" alt="short-term mutual funds selection" class="image--center mx-auto" /></p>
<h1 id="heading-long-term-goals">Long Term Goals</h1>
<p>For long-term goals, I have been investing in index funds for the past 2 years for so many good reasons. So, for this year too, I will be going <a target="_blank" href="https://www.niyomoney.com/blog/2023-mutual-fund-recommendations-2/">ahead with NiyoMoney recommendations</a>.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1688275293519/bc4a9ccb-cd87-4d07-8bf4-3cd2cd8d7cc3.png" alt="Long term index funds" class="image--center mx-auto" /></p>
<p>Apart from the index funds, I also started investing in equity active funds last year. So, I am continuing with the same funds but wanted to add a midcap fund to the portfolio. Hence, I selected <a target="_blank" href="https://www.valueresearchonline.com/funds/958/quant-mid-cap-fund/">Quant Midcap Fund</a>. Even though Motilal Oswal is giving good returns, there is a negative rating in Morningstar.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1688353581422/3c8abf05-a99d-4eba-ae1a-8737b0d28ca3.png" alt="Midcap mutual funds" class="image--center mx-auto" /></p>
<h1 id="heading-tax-saving-goals">Tax Saving Goals</h1>
<p>The tax saving goals are the same as <a target="_blank" href="https://blog.lokesh1729.com/personal-finance-my-investment-options-for-fy2022-23">FY2022-23</a>. Health Insurance, NPS, 80C.</p>
]]></content:encoded></item><item><title><![CDATA[Personal Finance  - My Investment Options for FY2022-23]]></title><description><![CDATA[In this blog post, I am sharing the mutual funds I selected for the investment across different goals for FY2022-23. For short-term goals, the general…]]></description><link>https://blog.lokesh1729.com/personal-finance-my-investment-options-for-fy2022-23</link><guid isPermaLink="true">https://blog.lokesh1729.com/personal-finance-my-investment-options-for-fy2022-23</guid><category><![CDATA[personal]]></category><dc:creator><![CDATA[Lokesh Sanapalli]]></dc:creator><pubDate>Sat, 01 Jul 2023 19:00:02 GMT</pubDate><content:encoded><![CDATA[<p>In this blog post, I am sharing the mutual funds I selected for the investment across different goals for FY2022-23.</p>
<h1 id="heading-short-term-goals-1-3-years">Short-Term Goals (1-3 Years)</h1>
<p>For short-term goals, the general recommendations are to select debt mutual funds, FD, RD. I prepared an Excel sheet of mutual funds and their returns. For the short-term goals which range from 1-3 years, I chose <a target="_blank" href="https://www.valueresearchonline.com/funds/1306/sundaram-equity-savings-fund/">Sundaram Equity Savings Direct - Growth</a> since it is performing well in the same category, the expense ratio is less and the ratings are good. Also, the reason why I chose the hybrid mutual fund category is that they invest 65% of the money into equity and equity arbitrage and 35% into debt so that the returns would be fair. I also had prepared for the moderate risk and determined not to touch it for at least 2 years.</p>
<p>In the category of short-term debt funds, I selected <a target="_blank" href="https://www.valueresearchonline.com/funds/5923/uti-short-term-income-fund-regular-plan/">UTI short-term mutual fund</a> mainly because the historical returns are very good even though the ratings are not good. Also, be careful with any debt funds except the money-market and liquid funds. They come with some volatility meaning their NAV changes frequently depending on many factors.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1688236751920/fba49f30-629e-4546-9661-b864a2ea2564.png" alt="short term goals mutual funds" class="image--center mx-auto" /></p>
<h1 id="heading-emergency-fund">Emergency Fund</h1>
<p>For emergency funds, it is a no-brainer to go with liquid funds. So, I selected the below 3 for it. Out of these, <a target="_blank" href="https://www.valueresearchonline.com/funds/2174/aditya-birla-sun-life-liquid-fund/">ABSL Liquid Fund</a> and <a target="_blank" href="https://www.valueresearchonline.com/funds/1972/nippon-india-liquid-fund/">Nippon Liquid Fund</a> are recommended by NiyoMoney because they provide an instant redemption option, so I kept them as is but added <a target="_blank" href="https://www.valueresearchonline.com/funds/2939/quant-liquid-fund/">Quant Liquid fund</a> for its historical performance.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1688848450986/3a6cce54-b60f-49a9-be3e-b0cc27e4ab24.png" alt class="image--center mx-auto" /></p>
<h1 id="heading-long-term-goals">Long Term Goals</h1>
<p>For long-term goals which are greater than 5 years, I simply had chosen the index funds. One reason is in the long run, index funds give good returns over any other active funds. They also have a very low expense ratio. Also, there is no headache of rebalancing, taxes computation, etc... <a target="_blank" href="https://www.niyomoney.com/blog/the-2022-list-of-recommended-mutual-funds-on-niyo-money/">NiyoMoney had recommended</a> the same, so I simply went with them.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1688237944706/3107b006-3dec-4ce7-99e6-9ab795683b11.png" alt="long term mutual funds" class="image--center mx-auto" /></p>
<p>Apart from index funds, I wanted to invest in some of the active funds so that my portfolio will be diversified. For this, I selected flexi-cap, small-cap, contra, and focused fund categories.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1688848567832/5874994e-861f-4392-928e-a431d53c33e7.png" alt class="image--center mx-auto" /></p>
<p>I selected <a target="_blank" href="https://www.valueresearchonline.com/funds/19701/parag-parikh-flexi-cap-fund-direct-plan/">Parag Parikh Flexi Cap Direct-Growth</a>, <a target="_blank" href="https://www.valueresearchonline.com/funds/17373/quant-focused-fund-direct-plan/">Quant Focused Fund Direct-Growth</a>, <a target="_blank" href="https://www.valueresearchonline.com/funds/16859/nippon-india-index-fund-sp-bse-sensex-plan-direct-plan/">Nippon Sensex Index Fund Direct-Growth</a>, and <a target="_blank" href="https://www.valueresearchonline.com/funds/22335/axis-small-cap-fund-direct-plan/">Axis Small Cap Direct-Growth</a>. The reasons would be rating by agencies, expense ratio, and historical returns.</p>
<h1 id="heading-tax-saving-goals">Tax Saving Goals</h1>
<h2 id="heading-health-insurance">Health Insurance</h2>
<p>Under Section 80D, we can get deductions of 50,000 for the health insurance of parents and self-family. I bought <a target="_blank" href="https://www.hdfcergo.com/docs/default-source/downloads/brochures/optima-secure-brochure.pdf">HDFC ergo optima secure health insurance</a> for 50,000 and claimed it as an income tax deduction.</p>
<h2 id="heading-nps">NPS</h2>
<p>Very few people know that over and above the 80C limit of 1,50,000 we can get more exemptions. U<a target="_blank" href="https://www.basunivesh.com/nps-tax-benefits-sections-80ccd1-80ccd2-and-80ccd1b/">nder 80CCD(1B), the employee contributions to NPS are exempted up to Rs. 50,000 per year. Also under 80CCD(2), the employer contributions (up to 10% of basic pay) are exempted over and above</a>. So, I opted for both to get more tax savings.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1688848728821/7938ca82-d3cd-48f2-a3bb-24a394895531.jpeg" alt="NPS tax benefits" class="image--center mx-auto" /></p>
<h2 id="heading-term-insurance-elss-mutual-funds-ssy">Term Insurance, ELSS mutual funds, SSY</h2>
<p>I have taken term insurance which I pay 2700 per month and I invest 4000 every month in ELSS mutual funds. I also invest in SSY for my daughter 6000 every month. All of this constitutes 1,50,000 which is the 80C limit. We also have EPF contributions by the employer that comes under 80C.</p>
]]></content:encoded></item><item><title><![CDATA[My personal finance journey]]></title><description><![CDATA[I started my career in 2015. I have tried several ways to track my expenses. I have invested in multiple investment options. In this blog post, I want to…]]></description><link>https://blog.lokesh1729.com/my-personal-finance-journey</link><guid isPermaLink="true">https://blog.lokesh1729.com/my-personal-finance-journey</guid><category><![CDATA[finance]]></category><category><![CDATA[personal finance]]></category><dc:creator><![CDATA[Lokesh Sanapalli]]></dc:creator><pubDate>Sat, 01 Jul 2023 11:03:30 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1688209377830/546e789d-297b-4376-bb42-22345a311774.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>I started my career in 2015. I have tried several ways to track my expenses. I have invested in multiple investment options. In this blog post, I want to share the learnings of my personal finance journey so far.</p>
<h1 id="heading-tracking-expenses">Tracking Expenses</h1>
<p>In 2015, I used <a target="_blank" href="https://axio.co.in/walnut/">walnut (now axios)</a> app to track my expenses. I used to track every penny using the app. From net banking, credit card, debit card, and cash transactions, everything I used to track. At that time, I didn't think about investments much and didn't concerned about my data privacy either. Most of us don't realize the impact of giving an app permission to read all the SMS'es and transactional data. It has its pros and cons. One of the pros is that very few good fintech companies that are compliant with government regulations use the data to analyze financial behavior and give better loan offers. But the con is that the data we are giving them is permanent, they can use it for a very long time and may share it with other companies too.</p>
<p>Later, in 2020, I created a spreadsheet to enter the data in a summary format, to get a clear picture. Later, I realized that I should have exported the data from Walnut and put it in the spreadsheet 🤦‍♂️ because the world runs on excel.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1688206688252/0cbacc1d-d6ef-4cf4-bf4c-2a095d39e005.png" alt="Spreadsheet template" class="image--center mx-auto" /></p>
<p>Later in 2021, I improved the template to a better version. But, still, the manual process of entering from Walnut into the spreadsheet exists.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1688235670883/117f9360-6e6e-49a5-9027-e13388fd87ef.png" alt="Spreadsheet template 2" class="image--center mx-auto" /></p>
<p>Later in 2022, I stopped using Walnut, since I moved to iPhone. I started downloading the bank statements, introspecting them, and entering them into the report. Until October 2022, I used to micro-manage the expenses a lot. I used to enter a single rupee into the reports to know the cash-in and cash-out flows. But, I moved to a macro-management approach of tracking only major expenses and budgeting my salary into expenses and investments by keeping them in separate bank accounts. So, when I budget X as living expenses, I kept them in a separate bank account, spend them from it, and look at how much is remaining at the month's end.</p>
<p><strong>The approach of macro-management and budgeting worked for me. It reduced my time to manage my finances and also gave the control over it.</strong></p>
<p>Here's the budget template I use - <a target="_blank" href="https://docs.google.com/spreadsheets/d/107jTWsyzDal5dUOaaP8rXidnaolxMn0WzVgKuCIYzME/edit">https://docs.google.com/spreadsheets/d/107jTWsyzDal5dUOaaP8rXidnaolxMn0WzVgKuCIYzME/edit</a></p>
<h1 id="heading-investments">Investments</h1>
<p>In 2015, I initially started my investment journey with chit funds. I didn't have much control over the finances. My uncle asked me to invest in a chit fund and he rotated that money for interest. I faced a lot of month-end crunches due to it. I had to depend on credit cards, loans from friends, etc... At once, I had over-utilized my credit card limit and took a personal loan to clear it.</p>
<p>In 2018, I again invested in chit funds without knowing how they work. In 2020, I researched them and realized that people who organize chit-funds are the ones who make a lot of money. There is a very high risk involved in it even though they are private limited companies. Also, another problem is it is very hard to redeem them. When I call for redemption in an auction, I was asked to submit a blank cheque or property documents as a guarantee for it.</p>
<p>In 2021, I moved away from chit funds and started investing in mutual funds for the long-term and short-term. I used <a target="_blank" href="https://niyomoney.com">goalwise (now niyomoney)</a> for all mutual fund investments. I followed their recommendations for my investments. I also invest in stocks via <a target="_blank" href="https://kite.zerodha.com/">zerodha</a> and used <a target="_blank" href="https://smallcase.com">smallcase</a> for the recommendations and rebalances. I also invest a good amount of money in physical gold every year. I write a separate post about how I select mutual funds.</p>
<h1 id="heading-financial-discipline">Financial Discipline</h1>
<p><strong>Invest first, Spend later culture -</strong> To inculcate financial discipline, it took a lot of time and so many hurdles for me. I always tried hard to save and invest 75-80% of my salary by keeping some money in the emergency fund and keeping a buffer. I tried to live with minimal expenses, so they are not even 20% of my salary. I divide my investments into emergency, short-term, long-term, and tax-saving. Then, I find the investment options and put them.</p>
]]></content:encoded></item><item><title><![CDATA[How to deploy a Django application]]></title><description><![CDATA[Django is a popular web framework with all batteries included. In this blog post, we will learn how to deploy it to production]]></description><link>https://blog.lokesh1729.com/how-to-deploy-a-django-application</link><guid isPermaLink="true">https://blog.lokesh1729.com/how-to-deploy-a-django-application</guid><category><![CDATA[Python]]></category><category><![CDATA[Django]]></category><dc:creator><![CDATA[Lokesh Sanapalli]]></dc:creator><pubDate>Sat, 25 Mar 2023 04:37:37 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1679719033877/810dc4df-1399-4a94-b937-2160ded86e8a.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-introduction">Introduction</h2>
<p>If you are looking for a guide to deploying a Django application to production, then you are at the right place. This guide assumes that you have a working Django application. You can check if your application is healthy by running this command <code>python manage.py check</code> .</p>
<h2 id="heading-components">Components</h2>
<h3 id="heading-gunicorn">Gunicorn</h3>
<p><code>python manage.py runserver</code> is not ideal for production. We need to run it with gunicorn and wsgi. We can also use <code>gevent</code> workers to take advantage of multiple processors. Remember python's GIL that makes it hard to achieve concurrency?</p>
<pre><code class="lang-bash"><span class="hljs-meta">#!/bin/bash</span>

NAME=<span class="hljs-string">"ProjectName"</span>
DJANGODIR=/root/project_name
USER=root
GROUP=root
NUM_WORKERS=5
DJANGO_SETTINGS_MODULE=config.settings.production
DJANGO_WSGI_MODULE=config.wsgi
<span class="hljs-built_in">echo</span> <span class="hljs-string">"Starting <span class="hljs-variable">$NAME</span> as `whoami`"</span>

<span class="hljs-built_in">cd</span> <span class="hljs-variable">$DJANGODIR</span>
<span class="hljs-built_in">exec</span> venv/bin/python venv/bin/gunicorn <span class="hljs-variable">${DJANGO_WSGI_MODULE}</span>:application --name <span class="hljs-variable">${NAME}</span> --workers <span class="hljs-variable">${NUM_WORKERS}</span> --worker-class gevent --<span class="hljs-built_in">bind</span> unix:///tmp/gunicorn.sock --log-level info --access-logfile <span class="hljs-variable">${DJANGODIR}</span>/logs/django_server_stdout.log --error-logfile <span class="hljs-variable">${DJANGODIR}</span>/logs/django_server_stderr.log --timeout 300
</code></pre>
<h3 id="heading-supervisor">Supervisor</h3>
<p>Supervisor is a utility to manage multiple processes. It is like <code>pm2</code> in node.js. We need to add gunicorn and celery worker if you have any.</p>
<pre><code class="lang-bash">[program:gunicorn]
directory = /root/project_name
<span class="hljs-built_in">command</span> = /bin/bash -c <span class="hljs-string">"/bin/bash gunicorn_start"</span>
user = root
stdout_logfile = /root/project_name/logs/gunicorn_stdout.log
stderr_logfile = /root/project_name/logs/gunicorn_stderr.log
redirect_stderr = <span class="hljs-literal">false</span>
environment = LANG=en_US.UTF-8,LC_ALL=en_US.UTF-8

[program:celery_worker]
<span class="hljs-built_in">command</span> = /bin/bash -c <span class="hljs-string">"/root/project_name/venv/bin/celery -A config.celery worker -c 10 -P gevent -Q openai -n openai_w1@%%h"</span>
directory = /root/project_name
user = root
stdout_logfile = /root/project_name/logs/openai_worker_stdout.log
stderr_logfile = /root/project_name/logs/openai_worker_stderr.log
redirect_stderr = <span class="hljs-literal">false</span>
autostart = False
environment = LANG=en_US.UTF-8,LC_ALL=en_US.UTF-8
</code></pre>
<h3 id="heading-nginx">Nginx</h3>
<p>We need a reverse proxy to route all the requests to the web server.</p>
<pre><code class="lang-bash">server {
    server_name project_name.com;

    location = /favicon.ico { access_log off; log_not_found off; }
    client_max_body_size 4G;
    access_log /root/project_name/logs/nginx_access.log;
    error_log /root/project_name/logs/nginx_error.log;
    location /static/ {
        autoindex on;
        <span class="hljs-built_in">alias</span> /root/project_name/staticfles/;
    }

    location /media/ {
        autoindex on;
        <span class="hljs-built_in">alias</span> /root/project_name/media/;
    }

    location / {
        proxy_redirect off;
        proxy_set_header X-Real-IP <span class="hljs-variable">$remote_addr</span>;
        proxy_set_header X-Forwarded-For <span class="hljs-variable">$proxy_add_x_forwarded_for</span>;
        proxy_set_header Host <span class="hljs-variable">$host</span>;
        proxy_set_header X-Forwarded-Proto <span class="hljs-variable">$scheme</span>;
        proxy_pass http://unix:/tmp/gunicorn.sock;
    }

    listen 80;
}

server {

    <span class="hljs-keyword">if</span> (<span class="hljs-variable">$host</span> = www.project_name.com) {
        <span class="hljs-built_in">return</span> 301 http://<span class="hljs-variable">$host</span><span class="hljs-variable">$request_uri</span>;
    }

    server_name www.domain.com;
    listen 80;
    <span class="hljs-built_in">return</span> 404;
}
</code></pre>
<h2 id="heading-glue-them-all">Glue them All</h2>
<pre><code class="lang-bash"><span class="hljs-comment"># OS dependencies</span>
sudo apt-get install software-properties-common
sudo apt-add-repository universe    
sudo apt-get update
sudo apt-get upgrade
sudo apt-get install -y gcc libpq-dev make build-essential libssl-dev zlib1g-dev libbz2-dev libreadline-dev libsqlite3-dev wget curl llvm libncurses5-dev libncursesw5-dev xz-utils tk-dev libffi-dev liblzma-dev python-openssl git python3 python-dev python3-dev libxml2-dev libxslt1-dev zlib1g-dev python-pip libmysqlclient-dev gcc libpq-dev python-dev python-pip python-wheel python3-dev python3-pip python3-venv python3-wheel
<span class="hljs-comment"># install nginx and supervisor</span>
sudo apt-get install nginx supervisor
</code></pre>
<p>By default, nginx runs with the user <code>www-data</code> and other processes run on <code>root</code> or a different user. So, all the static files give 403 forbidden because of it. To fix this, we need to create a new group, add <code>www-data</code> and <code>root</code> to it and add it to the permissions of static files.</p>
<pre><code class="lang-bash">sudo groupadd nginx
sudo usermod -a -G nginx root
sudo usermod -a -G nginx www-data
sudo chown root:nginx /root
<span class="hljs-comment"># assuming that your project is in root</span>
sudo chown root:nginx /root/project_name
sudo chown -R root:nginx /root/project_name/projectfiles
sudo chmod 755 /root
sudo chmod 770 /root/project_name
sudo chmod 770 -R /root/project_name/staticfiles
</code></pre>
<p>Copy the above supervisor config to <code>/etc/supervisor/conf.d/django.conf</code> and nginx config to <code>/etc/nginx/sites-available/project_name.conf</code> using the below command.</p>
<pre><code class="lang-bash">cp django.conf /etc/supervisor/conf.d/django.conf
cp project_name.conf /etc/nginx/sites-available/project_name.conf
ln -s /etc/nginx/sites-available/project_name.conf /etc/nginx/sites-enabled/project_name.conf
</code></pre>
<p>Start gunicorn and nginx</p>
<pre><code class="lang-bash">supervisorctl start gunicorn celery_worker
sudo service nginx restart
</code></pre>
<p>If you are using Ubuntu, check if the firewall is enabled using <code>ufw status</code> command. Allow ports 80 and 443 in the firewall using <code>ufw allow 80</code> and <code>ufw allow 443</code> . Many times I used to wonder why the website is inaccessible but accessible inside the machine. It is because those ports are blocked by the firewall.</p>
<h2 id="heading-redeployment-script">Redeployment Script</h2>
<p>To redeploy on every change, it becomes cumbersome to execute every command. Here is the shell script to execute.</p>
<pre><code class="lang-bash"><span class="hljs-built_in">source</span> venv/bin/activate
<span class="hljs-built_in">source</span> .envrc
git pull origin main
python manage.py check
python manage.py migrate
npm run build
python manage.py collectstatic --no-input
supervisorctl -c /etc/supervisor/supervisord.conf restart gunicorn celery_worker
sudo service restart nginx
</code></pre>
]]></content:encoded></item><item><title><![CDATA[How I built domain hunter using OpenAI on a weekend]]></title><description><![CDATA[I built domain hunter which generates domains available for registration based on the given terms using OpenAI.]]></description><link>https://blog.lokesh1729.com/how-i-built-domain-hunter-using-openai-on-a-weekend</link><guid isPermaLink="true">https://blog.lokesh1729.com/how-i-built-domain-hunter-using-openai-on-a-weekend</guid><category><![CDATA[openai]]></category><category><![CDATA[chatgpt]]></category><category><![CDATA[Python]]></category><category><![CDATA[Django]]></category><dc:creator><![CDATA[Lokesh Sanapalli]]></dc:creator><pubDate>Thu, 23 Mar 2023 16:38:24 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1679589469000/bb5f67cb-639d-474f-8339-f14342830b08.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-introduction">Introduction</h2>
<p>When ChatGPT was released, everyone was in awe, and a few people built production on top of it. I was also in the same hype and created a product. It is called <a target="_blank" href="https://domainhunterr.com">domain hunter</a> — A tool that generates domains that are available for registration using OpenAI. You give terms in the search bar and it generates the domains.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1679590633050/91bfd7c8-c003-4cb4-9923-64c452beebf4.png" alt="An image showing domain hunter homepage" class="image--center mx-auto" /></p>
<h2 id="heading-system-design">System Design</h2>
<h3 id="heading-tech-stack">Tech Stack</h3>
<ol>
<li><p>Python</p>
</li>
<li><p>Django</p>
</li>
<li><p>Celery</p>
</li>
<li><p>Redis</p>
</li>
<li><p>PostgreSQL</p>
</li>
<li><p>TailwindCSS</p>
</li>
<li><p>jQuery</p>
</li>
</ol>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1679587812902/619e020c-e171-489e-9b5a-897d394595dc.png" alt="Domain Hunter System Design" class="image--center mx-auto" /></p>
<p>As explained in the above diagram, the user enters the search terms, they will be put in a rabbitmq queue. They will be picked up by celery workers and call OpenAI for domain suggestions. At this point, we don't know whether all the domains suggested by OpenAI are available or not. So, we need to call domain APIs to get the availability and price.</p>
<p>There are other sets of workers which consume messages from rabbitmq and call domain APIs. Then they put that data in redis and the database. So, the REST API controller will be polling redis for new data. Whenever it is found, it will return to the client.</p>
<h2 id="heading-database-design">Database Design</h2>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1679588571985/cd55d046-712a-4e2e-b713-ade76f9ed446.png" alt="Low Level Design of Domain Hunter" class="image--center mx-auto" /></p>
<ol>
<li><p><code>core_searchterm</code> is the table that stores the terms and <code>max_tokens</code> to be used by OpenAI.</p>
</li>
<li><p><code>core_apiprovider</code> contains the configuration of the API provider. It contains the base URL, token, etc...</p>
</li>
<li><p><code>core_apicallaudit</code> contains other requests and responses of every API call. It has a foreign key to the API provider and search term.</p>
</li>
<li><p><code>core_domainsuggestion</code> contains a foreign key to the search term and its available domain details.</p>
</li>
<li><p><code>core_visitor_search_terms</code> and <code>users_user_search_terms</code> maintains the mapping of user/visitor to search terms.</p>
</li>
</ol>
<h2 id="heading-end-notes">End Notes</h2>
<p>Currently, it has a free and paid plan. I released it 3 weeks ago. So far I did not see a single user sign up. People are visiting the website, searching, and disappearing. It seems I did not find the market fit yet. I am still trying, let's see.</p>
]]></content:encoded></item><item><title><![CDATA[HTTP Retry with Exponential Backoff in Java and Spring Boot]]></title><description><![CDATA[Implementing HTTP retry with exponential backoff in spring boot is not trivial. Let's learn it in this blog post]]></description><link>https://blog.lokesh1729.com/http-retry-with-exponential-backoff-in-java-and-spring-boot</link><guid isPermaLink="true">https://blog.lokesh1729.com/http-retry-with-exponential-backoff-in-java-and-spring-boot</guid><category><![CDATA[Java]]></category><category><![CDATA[Springboot]]></category><category><![CDATA[Spring framework]]></category><category><![CDATA[Spring]]></category><dc:creator><![CDATA[Lokesh Sanapalli]]></dc:creator><pubDate>Thu, 23 Mar 2023 11:42:44 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1679584540494/64849dc4-e212-4c2b-886a-71b9fe071e9c.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In this blog post, we will learn to implement the HTTP retry mechanism in java and spring boot.</p>
<h2 id="heading-rest-template">Rest Template</h2>
<p>Rest template is the popular HTTP client in spring boot. We will create a configuration and create a bean for it so that the spring boot's container picks it up.</p>
<pre><code class="lang-java"><span class="hljs-keyword">package</span> com.abc.config;

<span class="hljs-keyword">import</span> java.time.Duration;
<span class="hljs-keyword">import</span> java.util.ArrayList;
<span class="hljs-keyword">import</span> java.util.List;

<span class="hljs-keyword">import</span> org.springframework.boot.web.client.RestTemplateBuilder;
<span class="hljs-keyword">import</span> org.springframework.context.annotation.Bean;
<span class="hljs-keyword">import</span> org.springframework.context.annotation.Configuration;
<span class="hljs-keyword">import</span> org.springframework.http.client.ClientHttpRequestInterceptor;
<span class="hljs-keyword">import</span> org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
<span class="hljs-keyword">import</span> org.springframework.util.CollectionUtils;
<span class="hljs-keyword">import</span> org.springframework.web.client.RestTemplate;

<span class="hljs-meta">@Configuration</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">RestTemplateConfig</span> </span>{

    <span class="hljs-meta">@Bean</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> RestTemplate <span class="hljs-title">restTemplate</span><span class="hljs-params">()</span> </span>{
        RestTemplate restTemplate =
                <span class="hljs-keyword">new</span> RestTemplateBuilder().setConnectTimeout(Duration.ofSeconds(<span class="hljs-number">30</span>))
                .setReadTimeout(Duration.ofSeconds(<span class="hljs-number">90</span>)).build();
        List&lt;ClientHttpRequestInterceptor&gt; interceptors = restTemplate.getInterceptors();
        <span class="hljs-keyword">if</span> (CollectionUtils.isEmpty(interceptors)) {
            interceptors = <span class="hljs-keyword">new</span> ArrayList&lt;&gt;();
        }
        restTemplate.setInterceptors(interceptors);
        restTemplate.setRequestFactory(<span class="hljs-keyword">new</span> HttpComponentsClientHttpRequestFactory());
        <span class="hljs-keyword">return</span> restTemplate;
    }

}
</code></pre>
<h2 id="heading-retry-config">Retry Config</h2>
<p>We need to add <code>spring-retry</code> and <code>spring-aspects</code> to our dependencies.</p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>org.springframework.retry<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>spring-retry<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">version</span>&gt;</span>1.2.5.RELEASE<span class="hljs-tag">&lt;/<span class="hljs-name">version</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span>

<span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>org.springframework<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>spring-aspects<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">version</span>&gt;</span>5.2.8.RELEASE<span class="hljs-tag">&lt;/<span class="hljs-name">version</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span>
</code></pre>
<pre><code class="lang-java"><span class="hljs-keyword">package</span> com.abc.config;

<span class="hljs-keyword">import</span> org.springframework.beans.factory.annotation.Autowired;
<span class="hljs-keyword">import</span> org.springframework.context.annotation.Bean;
<span class="hljs-keyword">import</span> org.springframework.context.annotation.Configuration;
<span class="hljs-keyword">import</span> org.springframework.retry.backoff.BackOffPolicy;
<span class="hljs-keyword">import</span> org.springframework.retry.backoff.ExponentialBackOffPolicy;
<span class="hljs-keyword">import</span> org.springframework.retry.policy.SimpleRetryPolicy;
<span class="hljs-keyword">import</span> org.springframework.retry.support.RetryTemplate;
<span class="hljs-keyword">import</span> org.springframework.web.client.HttpServerErrorException;

<span class="hljs-keyword">import</span> java.util.HashMap;
<span class="hljs-keyword">import</span> java.util.Map;

<span class="hljs-meta">@Configuration</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">RetryConfig</span> </span>{


    ExceptionClassifierBackoffPolicy exceptionClassifierBackoffPolicy;

    <span class="hljs-meta">@Autowired</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">RetryConfig</span><span class="hljs-params">(ExceptionClassifierBackoffPolicy exceptionClassifierBackoffPolicy)</span> </span>{
        <span class="hljs-keyword">this</span>.exceptionClassifierBackoffPolicy = exceptionClassifierBackoffPolicy;
    }

    <span class="hljs-meta">@Bean</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> RetryTemplate <span class="hljs-title">retryTemplate</span><span class="hljs-params">()</span> </span>{
        RetryTemplate retryTemplate = <span class="hljs-keyword">new</span> RetryTemplate();
        SimpleRetryPolicy simpleRetryPolicy = <span class="hljs-keyword">new</span> SimpleRetryPolicy(<span class="hljs-number">5</span>);
        ExponentialBackOffPolicy exponentialBackOffPolicy = <span class="hljs-keyword">new</span> ExponentialBackOffPolicy();
        exponentialBackOffPolicy.setInitialInterval(<span class="hljs-number">5000L</span>);
        exponentialBackOffPolicy.setMaxInterval(<span class="hljs-number">40000L</span>);

        Map&lt;Class&lt;? extends Throwable&gt;, BackOffPolicy&gt; policyMap = <span class="hljs-keyword">new</span> HashMap&lt;&gt;();
        policyMap.put(HttpServerErrorException.class, exponentialBackOffPolicy);
        exceptionClassifierBackoffPolicy.setPolicyMap(policyMap);
        retryTemplate.setRetryPolicy(simpleRetryPolicy);
        retryTemplate.setBackOffPolicy(exceptionClassifierBackoffPolicy);

        <span class="hljs-keyword">return</span> retryTemplate;
    }
}
</code></pre>
<p><code>ExponentialBackoffPolicy</code> takes the following parameters.</p>
<p><code>initialinterval</code> - The initial number of seconds to wait.</p>
<p><code>maxInterval</code> - The maximum number of seconds to wait.</p>
<p><code>multiplier</code> - The factor to multiply the initial interval with.</p>
<p>We created a hashmap of the exception class and the policy to use and then we added it to our rest template. A point to note here is after setting the exponential backoff policy, the simple retry policy also needs to be set. If it is not set, by default only 3 retries will be made. So, in the above code, we set the max retires as 5 to the simple retry policy because, in the exponential back-off policy, we set 5 seconds as the initial delay. So, on the first retry, it waits for 5, then 10, 20, and 40. Totally 5 retries will be made. Make sure to adjust these numbers that works better for you.</p>
<h2 id="heading-exceptionclassifierbackoffpolicy">ExceptionClassifierBackoffPolicy</h2>
<p>There is a default <a target="_blank" href="https://docs.spring.io/spring-retry/docs/api/current/org/springframework/retry/policy/ExceptionClassifierRetryPolicy.html"><code>ExceptionClassifierRetryPolicy</code></a> using which we can configure policies for exception classes. But we cannot use <code>ExponentialBackOffPolicy</code> it. Because in spring retry, <code>Retry</code> and <code>Backoff</code> are two different policies implementing different interfaces. So, we need to create our own custom <code>ExceptionClassifierBackoffPolicy</code> class for it.</p>
<pre><code class="lang-java"><span class="hljs-keyword">package</span> com.abc.config;

<span class="hljs-keyword">import</span> org.springframework.classify.Classifier;
<span class="hljs-keyword">import</span> org.springframework.classify.ClassifierSupport;
<span class="hljs-keyword">import</span> org.springframework.classify.SubclassClassifier;
<span class="hljs-keyword">import</span> org.springframework.retry.RetryContext;
<span class="hljs-keyword">import</span> org.springframework.retry.backoff.BackOffContext;
<span class="hljs-keyword">import</span> org.springframework.retry.backoff.BackOffInterruptedException;
<span class="hljs-keyword">import</span> org.springframework.retry.backoff.BackOffPolicy;
<span class="hljs-keyword">import</span> org.springframework.retry.backoff.NoBackOffPolicy;

<span class="hljs-keyword">import</span> java.util.HashMap;
<span class="hljs-keyword">import</span> java.util.Map;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ExceptionClassifierBackoffPolicy</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">BackOffPolicy</span> </span>{

    <span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ExceptionClassifierBackoffContext</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">BackOffContext</span>, <span class="hljs-title">BackOffPolicy</span> </span>{
        Classifier&lt;Throwable, BackOffPolicy&gt; exceptionClassifier;
        RetryContext retryContext;

        Map&lt;BackOffPolicy, BackOffContext&gt; contextMap = <span class="hljs-keyword">new</span> HashMap&lt;&gt;();

        ExceptionClassifierBackoffContext(Classifier&lt;Throwable, BackOffPolicy&gt; exceptionClassifier, RetryContext retryContext) {
            <span class="hljs-keyword">this</span>.exceptionClassifier = exceptionClassifier;
            <span class="hljs-keyword">this</span>.retryContext = retryContext;
        }

        <span class="hljs-meta">@Override</span>
        <span class="hljs-function"><span class="hljs-keyword">public</span> BackOffContext <span class="hljs-title">start</span><span class="hljs-params">(RetryContext context)</span> </span>{
            <span class="hljs-keyword">return</span> (BackOffContext) context;
        }

        <span class="hljs-meta">@Override</span>
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">backOff</span><span class="hljs-params">(BackOffContext backOffContext)</span> <span class="hljs-keyword">throws</span> BackOffInterruptedException </span>{
            BackOffPolicy policy = exceptionClassifier.classify(retryContext.getLastThrowable());
            BackOffContext policyContext = contextMap.get(policy);
            <span class="hljs-keyword">if</span> (policyContext == <span class="hljs-keyword">null</span>) {
                policyContext = policy.start(retryContext);
                contextMap.put(policy, policyContext);
            }
            policy.backOff(policyContext);
        }
    }

    <span class="hljs-keyword">private</span> Classifier&lt;Throwable, BackOffPolicy&gt; exceptionClassifier =
            <span class="hljs-keyword">new</span> ClassifierSupport&lt;&gt;(<span class="hljs-keyword">new</span> NoBackOffPolicy());

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setPolicyMap</span><span class="hljs-params">(Map&lt;Class&lt;? extends Throwable&gt;, BackOffPolicy&gt; policyMap)</span> </span>{
        <span class="hljs-keyword">this</span>.exceptionClassifier = <span class="hljs-keyword">new</span> SubclassClassifier&lt;&gt;(policyMap, <span class="hljs-keyword">new</span> NoBackOffPolicy());
    }
    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> BackOffContext <span class="hljs-title">start</span><span class="hljs-params">(<span class="hljs-keyword">final</span> RetryContext context)</span> </span>{
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> ExceptionClassifierBackoffContext(exceptionClassifier, context);
    }

    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">backOff</span><span class="hljs-params">(<span class="hljs-keyword">final</span> BackOffContext backOffContext)</span> <span class="hljs-keyword">throws</span> BackOffInterruptedException </span>{
        ExceptionClassifierBackoffContext classifierBackOffContext = (ExceptionClassifierBackoffContext) backOffContext;
        classifierBackOffContext.backOff(backOffContext);
    }
}
</code></pre>
<h2 id="heading-main-class">Main class</h2>
<p>Now combining all of it, here's the main class.</p>
<pre><code class="lang-java"><span class="hljs-keyword">package</span> com.abc;

<span class="hljs-keyword">import</span> com.abc.config.ExceptionClassifierBackoffPolicy;
<span class="hljs-keyword">import</span> com.abc.config.RestTemplateConfig;
<span class="hljs-keyword">import</span> com.abc.config.RetryConfig;
<span class="hljs-keyword">import</span> org.springframework.http.HttpEntity;
<span class="hljs-keyword">import</span> org.springframework.http.HttpMethod;
<span class="hljs-keyword">import</span> org.springframework.http.ResponseEntity;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">main</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
        RetryConfig retryConfig = <span class="hljs-keyword">new</span> RetryConfig(<span class="hljs-keyword">new</span> ExceptionClassifierBackoffPolicy());
        RestTemplateConfig restTemplate = <span class="hljs-keyword">new</span> RestTemplateConfig();
        HttpEntity&lt;String&gt; resp = <span class="hljs-keyword">new</span> HttpEntity&lt;&gt;(<span class="hljs-keyword">null</span>);
        ResponseEntity&lt;String&gt; newResp =
                retryConfig.retryTemplate().execute(context -&gt; restTemplate.restTemplate().exchange(
                        <span class="hljs-string">"https://abc-test"</span> +
                                <span class="hljs-string">".free"</span> +
                                <span class="hljs-string">".beeceptor"</span> +
                                <span class="hljs-string">".com/test/abc"</span>,
                        HttpMethod.GET,
                        resp,
                        String.class));
        System.out.println(newResp.getBody());
    }
}
</code></pre>
]]></content:encoded></item><item><title><![CDATA[Implement Retry and Logging in Python Requests]]></title><description><![CDATA[Python's requests library is a popular library for making HTTP requests. It is a wrapper on python's built-in urllib module. It gives a clean API with many…]]></description><link>https://blog.lokesh1729.com/implement-retry-and-logging-in-python-requests</link><guid isPermaLink="true">https://blog.lokesh1729.com/implement-retry-and-logging-in-python-requests</guid><category><![CDATA[Python]]></category><category><![CDATA[http]]></category><category><![CDATA[System Architecture]]></category><category><![CDATA[Python 3]]></category><dc:creator><![CDATA[Lokesh Sanapalli]]></dc:creator><pubDate>Wed, 01 Mar 2023 04:52:12 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1677646290748/2c7f931f-b801-4be2-821a-3d875c4fc6fe.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-introduction">Introduction</h2>
<p>Python's requests library is a popular library for making HTTP requests. It is a wrapper on python's built-in <code>urllib</code> module. It gives a clean API with many features. In this post, we will see how to implement retry and logging when using the requests library.</p>
<h2 id="heading-requests-design">Requests Design</h2>
<p><code>requests</code> is designed modularly using different object oriented patterns. All the methods we use such as <code>requests.get</code> , <code>requests.post</code> etc.. are present <code>api.py</code> which <a target="_blank" href="https://github.com/psf/requests/blob/main/requests/api.py#L58">simply creates a session object and sends the request</a>. The <code>Session</code> class present in <code>session.py</code> is the core and heart. It composes <code>HTTPAdapter</code> from urllib3 which is the low-level module in python for sending HTTP requests. It also composes <code>PreparedRequest</code> in models.py which does the preparation of request such as sanitizing input, request body, params etc...</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1677644018693/26e5a0bf-2b5d-4bed-862e-4742dad8db02.png" alt="image showing python requests" class="image--center mx-auto" /></p>
<h2 id="heading-logging">Logging</h2>
<p>Why logging is important? it's a no-brainer! it will be very helpful when troubleshooting issues in a production environment where you can't debug the program. When building distributed systems, if your application communicates with multiple systems then adding logging to HTTP requests is a must. While logging the request, you can send a unique request id in the headers which helps in tracing the whole lifecycle of the request throughout the system — This is called distributed tracing — I will write a separate blog post on this. Let's see how can we add logs to python's requests.</p>
<p><strong>Change the log level of the underlying urllib3 module.</strong></p>
<p>urllib3 provides a handy function called <code>add_stderr_logger</code> which adds a stream handler and sets the level <code>DEBUG</code> by default. We can <a target="_blank" href="https://github.com/urllib3/urllib3/blob/main/src/urllib3/__init__.py#L87">see the code here for the same</a>.</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> requests
<span class="hljs-keyword">import</span> urllib3

urllib3.add_stderr_logger()

resp = requests.get(
    <span class="hljs-string">"https://jsonplaceholder.typicode.com/posts"</span>,
    headers={<span class="hljs-string">"X-Request-ID"</span>: <span class="hljs-string">"abcd123"</span>},
    params={<span class="hljs-string">"foo"</span>: <span class="hljs-string">"bar"</span>},
    timeout=(<span class="hljs-number">10</span>, <span class="hljs-number">30</span>),
)
</code></pre>
<p>The above code prints the following</p>
<pre><code class="lang-plaintext">2023-02-26 23:35:32,110 DEBUG Added a stderr logging handler to logger: urllib3
2023-02-26 23:35:32,166 DEBUG Starting new HTTPS connection (1): jsonplaceholder.typicode.com:443
2023-02-26 23:35:32,352 DEBUG https://jsonplaceholder.typicode.com:443 "GET /posts?foo=bar HTTP/1.1" 200 None
</code></pre>
<p>This does not log the request headers and body which we may require. So, the only alternative way is to manually log the request and response as we desire. Let's write a decorator for it.</p>
<h3 id="heading-inherit-requestssession">inherit requests.Session</h3>
<p>Just like other HTTP libraries (Axios in javascript), requests <a target="_blank" href="https://github.com/psf/requests/blob/main/requests/hooks.py#L16">do provide hooks or interceptors</a>. A hook is a function that will be called when an event has happened. Unfortunately, requests do not have hooks for the <code>request</code> . It only has for <code>response</code>.</p>
<p>The only way to add logging is to extend <code>requests.Session</code> class and add logging.</p>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">RequestSession</span>(<span class="hljs-params">requests.Session</span>):</span>

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">request</span>(<span class="hljs-params">
        self,
        method,
        url,
        params=None,
        data=None,
        headers=None,
        cookies=None,
        files=None,
        auth=None,
        timeout=None,
        allow_redirects=True,
        proxies=None,
        hooks=None,
        stream=None,
        verify=None,
        cert=None,
        json=None,
    </span>):</span>
        logger.debug(<span class="hljs-string">f"Before making HTTP request. url=<span class="hljs-subst">{url}</span> method=<span class="hljs-subst">{method}</span>"</span>
                     <span class="hljs-string">f"params=<span class="hljs-subst">{params}</span> data=<span class="hljs-subst">{data}</span>"</span>
                     <span class="hljs-string">f"headers=<span class="hljs-subst">{headers}</span> json=<span class="hljs-subst">{json}</span> timeout=<span class="hljs-subst">{timeout}</span>"</span>)
        start_time = time.time()
        response = super().request(
            method,
            url,
            params=params,
            data=data,
            headers=headers,
            cookies=cookies,
            files=files,
            auth=auth,
            timeout=timeout,
            allow_redirects=allow_redirects,
            proxies=proxies,
            hooks=hooks,
            stream=stream,
            verify=verify,
            cert=cert,
            json=json,
        )
        logger.debug(<span class="hljs-string">f"After making HTTP request with params url=<span class="hljs-subst">{url}</span> method=<span class="hljs-subst">{method}</span>"</span>
                     <span class="hljs-string">f"params=<span class="hljs-subst">{params}</span> data=<span class="hljs-subst">{data}</span> headers=<span class="hljs-subst">{headers}</span>"</span>
                     <span class="hljs-string">f"json=<span class="hljs-subst">{json}</span> timeout=<span class="hljs-subst">{timeout}</span> response=<span class="hljs-subst">{response.text}</span>"</span>
                     <span class="hljs-string">f"response_status_code=<span class="hljs-subst">{response.status_code}</span>"</span>
                     <span class="hljs-string">f"response_headers=<span class="hljs-subst">{response.headers}</span> total_time_taken=<span class="hljs-subst">{time.time() - start_time}</span> seconds"</span>)
        <span class="hljs-keyword">try</span>:
            response.raise_for_status()
        <span class="hljs-keyword">except</span> requests.HTTPError:
            logger.critical(<span class="hljs-string">f"HTTP request failed. url=<span class="hljs-subst">{url}</span> method=<span class="hljs-subst">{method}</span>"</span>
                            <span class="hljs-string">f"params=<span class="hljs-subst">{params}</span> data=<span class="hljs-subst">{data}</span> headers=<span class="hljs-subst">{headers}</span>"</span>
                            <span class="hljs-string">f"json=<span class="hljs-subst">{json}</span> response=<span class="hljs-subst">{response.text}</span>"</span>
                            <span class="hljs-string">f"response_status_code=<span class="hljs-subst">{response.status_code}</span>"</span>)
        <span class="hljs-keyword">return</span> response
</code></pre>
<p>If required, we can always add more details to the logs. Also, make sure to configure the logging level of the module. The below code sets the log levels.</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> logging
<span class="hljs-keyword">import</span> requests
<span class="hljs-keyword">import</span> sys
<span class="hljs-keyword">import</span> time


logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
handler = logging.StreamHandler(sys.stdout)
handler.setLevel(logging.DEBUG)
formatter = logging.Formatter(<span class="hljs-string">'%(asctime)s - %(name)s - %(levelname)s - %(message)s'</span>)
handler.setFormatter(formatter)
logger.addHandler(handler)

<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">"__main__"</span>:
    <span class="hljs-keyword">with</span> RequestSession() <span class="hljs-keyword">as</span> session:
        resp = session.get(<span class="hljs-string">"https://jsonplaceholder.typicode.com/posts"</span>, headers={<span class="hljs-string">"X-Request-ID"</span>: <span class="hljs-string">"abcd123"</span>},
                           params={<span class="hljs-string">"foo"</span>: <span class="hljs-string">"bar"</span>},
                           data={<span class="hljs-string">"a"</span>: <span class="hljs-number">1</span>, <span class="hljs-string">"b"</span>: <span class="hljs-number">2</span>}, timeout=(<span class="hljs-number">10</span>, <span class="hljs-number">30</span>)
                           )
</code></pre>
<h2 id="heading-retry">Retry</h2>
<p>Having retries with exponential backoff is a must in a distributed system to make systems more resilient and fault-tolerant. Let's see how we can implement retry mechanism with python requests.</p>
<p>The retry mechanism is provided by <code>urllib3</code> package which is the underlying module of <code>requests</code>.</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> requests
<span class="hljs-keyword">from</span> requests.adapters <span class="hljs-keyword">import</span> Retry, HTTPAdapter

retry = Retry(total=<span class="hljs-number">10</span>, connect=<span class="hljs-number">5</span>, read=<span class="hljs-number">5</span>, allowed_methods=[<span class="hljs-string">'GET'</span>, <span class="hljs-string">'POST'</span>, <span class="hljs-string">'PUT'</span>], backoff_factor=<span class="hljs-number">10</span>, status_forcelist=[<span class="hljs-number">500</span>, <span class="hljs-number">502</span>, <span class="hljs-number">503</span>, <span class="hljs-number">504</span>])
session = requests.Session()
session.mount(<span class="hljs-string">"http://"</span>, HTTPAdapter(max_retries=retry))
resp = session.get(<span class="hljs-string">"https://jsonplaceholder.typicode.com/posts"</span>)
print(resp.json())
</code></pre>
<p><code>total</code> - the total number of requests to make in total. This argument takes higher precedence which means if you set the total to 10 and other counts higher, the <code>total</code> will be taken.</p>
<p><code>connect</code> - is the number of retries to make if there is an exception in connecting to the target host.</p>
<p><code>read</code> - is the number of retries to make if after connecting to the host, if there is any exception in reading data.</p>
<p><code>allowed_method</code> - Be careful with this. By default, urllib3 includes only idempotent verbs. According to HTTP RFC, GET, PUT, DELETE are the idempotent verbs. When using this, make sure all your verbs are idempotent.</p>
<p><code>backoff_factor</code> - Number of seconds to wait between two retries. <em>{backoff factor} (2 \</em> ({number of total retries} - 1))* - is the formula to compute backoff time. If <code>backoff_factor</code> is 10, then 5s, 10s, 20s, 40s etc...</p>
<p><code>status_forcelist</code> - It is the list of status codes on which retries are to be made.</p>
<h3 id="heading-how-retry-is-implemented-in-urllib3">How Retry is Implemented in urllib3</h3>
<p>Read this only if you are interested to learn how retry in urllib3 is implemented. In urllib3, <code>connectionpool.py</code> is the core and low-level module for sending HTTP requests. <a target="_blank" href="https://github.com/urllib3/urllib3/blob/main/src/urllib3/connectionpool.py#L844">In the function urlopen</a>, if there is any exception then <code>retries.increment</code> is called followed by <code>retries.sleep</code></p>
<pre><code class="lang-python">retries = retries.increment(method, url, error=new_e, _pool=self, _stacktrace=sys.exc_info()[<span class="hljs-number">2</span>])
retries.sleep()
</code></pre>
<p>The function <code>increment</code> in <code>Retry</code> increments the retry count, checks if the retry limit is exhausted. If yes, then it raises an exception. <a target="_blank" href="https://github.com/urllib3/urllib3/blob/main/src/urllib3/util/retry.py#L450">The code goes on like below.</a></p>
<pre><code class="lang-python">history = self.history + (
    RequestHistory(method, url, error, status, redirect_location),
)

new_retry = self.new(
    total=total,
    connect=connect,
    read=read,
    redirect=redirect,
    status=status_count,
    other=other,
    history=history,
)

<span class="hljs-keyword">if</span> new_retry.is_exhausted():
    reason = error <span class="hljs-keyword">or</span> ResponseError(cause)
    <span class="hljs-keyword">raise</span> MaxRetryError(_pool, url, reason) <span class="hljs-keyword">from</span> reason
</code></pre>
<p>Now let's see <a target="_blank" href="https://github.com/urllib3/urllib3/blob/main/src/urllib3/util/retry.py#L335">what <code>rety.sleep</code> function do</a>. It checks if the response contain <a target="_blank" href="https://github.com/urllib3/urllib3/blob/main/src/urllib3/util/retry.py#L321">the header <code>Retry-After</code></a> and respects that. If it's not present, then it <a target="_blank" href="https://github.com/urllib3/urllib3/blob/main/src/urllib3/util/retry.py#L329">gets the backoff time and sleeps</a>.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">sleep_for_retry</span>(<span class="hljs-params">self, response=None</span>):</span>
    retry_after = self.get_retry_after(response)
    <span class="hljs-keyword">if</span> retry_after:
        time.sleep(retry_after)
        <span class="hljs-keyword">return</span> <span class="hljs-literal">True</span>
    <span class="hljs-keyword">return</span> <span class="hljs-literal">False</span>

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">_sleep_backoff</span>(<span class="hljs-params">self</span>):</span>
    backoff = self.get_backoff_time()
    <span class="hljs-keyword">if</span> backoff &lt;= <span class="hljs-number">0</span>:
        <span class="hljs-keyword">return</span>
    time.sleep(backoff)

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">sleep</span>(<span class="hljs-params">self, response=None</span>):</span>
    <span class="hljs-keyword">if</span> self.respect_retry_after_header <span class="hljs-keyword">and</span> response:
        slept = self.sleep_for_retry(response)
        <span class="hljs-keyword">if</span> slept:
            <span class="hljs-keyword">return</span>
    self._sleep_backoff()
</code></pre>
]]></content:encoded></item><item><title><![CDATA[Caching and Different Patterns]]></title><description><![CDATA[Caching has so many applications in computer science starting from disk page caching to advanced caching operations in redis.]]></description><link>https://blog.lokesh1729.com/caching-patterns</link><guid isPermaLink="true">https://blog.lokesh1729.com/caching-patterns</guid><category><![CDATA[Redis]]></category><category><![CDATA[caching]]></category><category><![CDATA[cache]]></category><category><![CDATA[distributed system]]></category><category><![CDATA[System Architecture]]></category><dc:creator><![CDATA[Lokesh Sanapalli]]></dc:creator><pubDate>Sun, 12 Feb 2023 09:56:07 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1676197610025/46f25d80-1d59-4de3-8e66-0376def682ae.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2>Introduction</h2>
<p>How many heard the phrase "Cache invalidation is the toughest problem in computer science?" I was first introduced to the term "cache" in my computer architecture class in engineering. When I first learned, I did not understand the concept. It took me some years to wholly understood the concept. In this blog post, we will look at the basics of caching and different strategies.</p>
<h2>Basics</h2>
<p>What is caching? caching is a mechanism of storing data in fast and secondary storage temporarily. The main goal of caching is to decrease the response time and increase speed. The fundamental concept is simple, primary storage gives persistence and durability that stores the data permanently. But, they are slow. We need secondary storage that is fast but temporary. That's what the RAMs are designed for. They are fast but the data stored in them is temporary. We also call RAM in-memory. Let's try to understand the mechanism with the diagram below.</p>
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1676030909030/8e98d984-409a-49f0-950f-3c85b3aad914.png" alt="An iamge showing flow of cache" style="display:block;margin:0 auto" />

<p>The above diagram is a no-brainer. We first check in the cache because it's fast, if not found fetch it from primary storage and write it back to the cache.</p>
<p>Caching is implemented in different use cases. A few of them are</p>
<ol>
<li><p><strong>Disk page caching</strong>: Hard disks are cylindrical structures divided into sectors, tracks, and pages. A page is a continuous block of memory. Accessing the hard disk every time requires an I/O overhead and CPU context switching. To optimize this, the UNIX operating system caches the pages in the main memory.</p>
</li>
<li><p><strong>Web server caching</strong>: Web servers like nginx caches the frequently accessed pages to increase speed and responsiveness. They simply store the entire HTML content in the main memory and serve from there.</p>
</li>
<li><p><strong>Application level caching</strong>: Applications like web browsers, code editors and your backend web APIs cache the result in in-memory.</p>
</li>
</ol>
<h2>Cache Eviction Policies</h2>
<p>The capacity of our RAM is of some fixed size. So, when it reaches its size, it needs to omit some data. This process is called eviction. Below are different eviction techniques used.</p>
<h3>Least Recently Used</h3>
<p>As the name says, remove the least recently used entry. A doubly linked list data structure is used commonly to implement this mechanism. The data is stored in the sorted order of access where the most recently used at the beginning and the least recently used at the end. Every time a cache key is accessed, it will be put at the front.</p>
<h3>Least Frequently Used</h3>
<p>A frequency count of each cache key will be maintained. Every time a key is accessed, the frequency count will be updated. Whenever the cache reaches its size, the less frequent item will be removed.</p>
<h2>Caching Patterns</h2>
<p>There are different patterns of caching. We will look at each of them.</p>
<h3>Cache Aside</h3>
<p>This is the most common pattern. We already discussed this in the above flow diagram. We will first check in the cache, and if not found, read from the database and write to the cache again.</p>
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1676194659766/8298fd8e-aa8a-4e3d-9b2b-fbbff16326f6.png" alt="cache aside flow" style="display:block;margin:0 auto" />

<h3>Read Through</h3>
<p>In cache through pattern, the application server asks the cache for the data, in case of a cache miss, the cache itself fetches from the database and saves in the cache. In order to implement this pattern, the caching software should have libraries to integrate with the database technology. Very few caching software implement this pattern. An example is <a href="https://aws.amazon.com/dynamodb/dax/">AWS DAX which integrates with DynamoDB</a>.</p>
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1676194069391/2ab9a892-3f9c-4dc0-942e-e0d95e562c2e.png" alt="cache through pattern explanation" style="display:block;margin:0 auto" />

<h3>Write Behind</h3>
<p>In this pattern, the writes to the cache happen asynchronously through the message queue. The advantage of this pattern is latency is reduced as the writes to the cache are not happening synchronously. But, the downside of this pattern is cache misses increase if there is a lag in writing data to the cache.</p>
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1676195464282/31c89bcd-2b2e-4154-8e76-fddb0d291a43.png" alt="Cache behind mechanism" style="display:block;margin:0 auto" />]]></content:encoded></item><item><title><![CDATA[Database Migrations in Django]]></title><description><![CDATA[Django gives a powerful framework to manage database migrations. We will deep dive into Django migrations and how they work under the hood]]></description><link>https://blog.lokesh1729.com/database-migrations-in-django</link><guid isPermaLink="true">https://blog.lokesh1729.com/database-migrations-in-django</guid><category><![CDATA[Django]]></category><category><![CDATA[Python]]></category><category><![CDATA[Web Development]]></category><dc:creator><![CDATA[Lokesh Sanapalli]]></dc:creator><pubDate>Wed, 08 Feb 2023 17:53:40 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1675878783486/e899fecf-bec5-4b92-a1f0-c62f7c1d7a2d.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-introduction">Introduction</h2>
<p>Django gives a powerful framework to manage database migrations. Without this, managing schema and data changes would be hectic work. Every schema change to the database can be managed through Django. You make a change to your Django model, create a migration and apply that migration to the database. If you want to reverse it, you can do that too. All this is irrespective of the underlying database technology. How simple, beautiful, and declarative isn't it? do you feel it? I can feel it. In this blog post, we will learn how Django migrations work under the hood, and Django's data migrations</p>
<h2 id="heading-why-migrations-are-required">Why Migrations Are Required?</h2>
<p>So, why are migrations required? what will happen without it? Let's say you are working on a Django application, and you make changes to your model but they are not synced to the database.</p>
<ol>
<li><p><strong>Track SQL queries manually:</strong> You need to execute them manually. But, what if you missed executing a query in between and caused a whole chaos? So, you need to track them in some place in a sequential manner. Where do you store it? maybe create a folder and add all <code>.sql</code> files there.</p>
</li>
<li><p><strong>Deploy in multiple environments:</strong> Assume you want to deploy your app on multiple environments such as dev, QA, staging and production, etc... So, you need to execute all these queries manually on each machine in sequential order.</p>
</li>
</ol>
<p>Django's migrations framework solved all the above problems and made it so convenient for users to manage them.</p>
<h2 id="heading-basics">Basics</h2>
<p>In the below code, we have added a new field called <code>about</code> which is a type of <code>TextField</code> . So, After making this change in our models, we need to propagate this change to the database.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1675838735065/8f45ee67-0074-480b-b7cb-52d9b13ff6ee.png" alt="Image showing migrations" class="image--center mx-auto" /></p>
<p>We need to create a migration and apply it. The commands are</p>
<pre><code class="lang-bash">python manage.py makemigrations <span class="hljs-comment"># creates a migration file in `migrations` folder</span>
python manage.py migrate <span class="hljs-comment"># applies the migration to the database by exeucting SQL query</span>
</code></pre>
<p><code>makemigrations</code> command creates a migration file in <code>migrations</code> the folder. <code>migrate</code> the command applies that migration to the database through SQL. If we take a look at the migration file, it looks like this</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> django.db <span class="hljs-keyword">import</span> migrations, models


<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Migration</span>(<span class="hljs-params">migrations.Migration</span>):</span>

    dependencies = [
        (<span class="hljs-string">'job'</span>, <span class="hljs-string">'0002_jobapplication'</span>),
    ]

    operations = [
        migrations.AddField(
            model_name=<span class="hljs-string">'company'</span>,
            name=<span class="hljs-string">'about'</span>,
            field=models.TextField(
                    _(<span class="hljs-string">"About Company"</span>),
                    help_text=_(
                        <span class="hljs-string">"Write about the company. It will be displayed on the web page to the users."</span>
                    ),
                  ),
    ]
</code></pre>
<p>Let's dissect the above code.</p>
<p><strong>Migration Class</strong>: <code>Migration</code> is a class inherited <code>migrations.Migration</code> base class which has the mechanism to apply migrations.</p>
<p><strong>Dependencies:</strong> It has an array <code>dependencies</code> where each item is a tuple of the app name and migration file name. It means that in order for this migration to be executed, the dependencies should be executed first.</p>
<p><em>Why do dependencies are required? Imagine there are no dependencies, say you have a migration to delete or alter a field. Django connects to the database and tries to execute the SQL query but it will fail with</em> <code>field `xyz` does not exist</code> <em>error. Because you may have not run the query to add that column. So, dependencies are important to maintain the consistency of the database.</em></p>
<p><strong>Operations:</strong> is an array of operations. Adding a column, modifying a column and deleting a column, Adding a new table are common operations. Django's migration framework has these methods for each operation. Under the hood, those methods have the logic to generate SQL queries.</p>
<h2 id="heading-django-migrations-graph-data-structure">Django Migrations 🤝 Graph Data Structure</h2>
<p>In order for Django to apply migrations, it needs to know already applied migrations. So, it needs to store the state somewhere. Django stores the data in a table called <code>django_migrations</code> table with <code>app</code> , <code>name</code> and <code>applied</code> timestamp. Every time a migration is applied, it adds a new entry to the table in order. Also, Django uses <a target="_blank" href="https://sourcegraph.com/github.com/django/django@69069a443a906dd4060a8047e683657d40b4c383/-/blob/django/db/migrations/loader.py?L307">the graph data structure to check the consistency</a> of the migrations. <a target="_blank" href="https://sourcegraph.com/github.com/django/django@69069a443a906dd4060a8047e683657d40b4c383/-/blob/django/db/migrations/loader.py?L222">It builds the graph of applied migrations and their dependencies</a> (remember? we give <code>dependencies</code> for each migration) where each node is the migration name and the directed edge is the dependency. It <a target="_blank" href="https://sourcegraph.com/github.com/django/django@69069a4/-/blob/django/db/migrations/loader.py?L338&amp;subtree=true">checks for any conflicts</a> and raises an error if any.</p>
<h3 id="heading-conflicting-migrations-detected-multiple-leaf-nodes-in-the-migration-graph">Conflicting migrations detected; multiple leaf nodes in the migration graph</h3>
<p>The above error is a common error while applying migrations. It occurs when an app has multiple leaf nodes. This commonly happens when you are working in a team and multiple people create the migration simultaneously. Refer to the below diagram.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1675877189574/7f70b57b-4669-4f0a-9342-6b7ddef50d80.png" alt="Image showing migration conflicts in django" class="image--center mx-auto" /></p>
<p>Assume that migration "22" is already applied, Person A had added a migration that adds location to the user model and Person B adds an avatar. Both of the migrations have "22" as the dependency. When Django tries to apply a migration, it doesn't know which one to apply first. What if one migration deletes a field and another migration alters the same field? So, it is impossible to choose a migration. So, that's how the conflict occurs for Django. How does this conflict get resolved? Simple, we need to merge them using the below command and create a single migration.</p>
<pre><code class="lang-bash">python manage.py makemigrations --merge
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1675877665766/83ccb99b-5c17-45e4-9ab8-0d4bf60095d6.png" alt="Image showing conflict resolution of django migrations" class="image--center mx-auto" /></p>
<h2 id="heading-data-migrations">Data Migrations</h2>
<p>Along with database schema changes, we can create migrations for data too. First, we need to create a migration file with the below command.</p>
<pre><code class="lang-bash">python manage.py makemigrations job --empty --name load_job_data
</code></pre>
<p>We are creating an empty data migration which looks like below</p>
<pre><code class="lang-python"><span class="hljs-comment"># Generated by Django 3.2.10 on 2023-02-08 17:39</span>

<span class="hljs-keyword">from</span> django.db <span class="hljs-keyword">import</span> migrations


<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Migration</span>(<span class="hljs-params">migrations.Migration</span>):</span>

    dependencies = [
        (<span class="hljs-string">'job'</span>, <span class="hljs-string">'0004_alter_job_location'</span>),
    ]

    operations = [
    ]
</code></pre>
<p>We need to add our custom function to seed data in the <code>operations</code> list. The function's name can be anything but it should have the following structure. We need to use Django's app registry API to access the models and operate on them as we see below.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">load_job_data</span>(<span class="hljs-params">apps, schema_editor</span>):</span>
    Job = apps.get_model(<span class="hljs-string">"job"</span>, <span class="hljs-string">"Job"</span>)
    resp = requests.get(<span class="hljs-string">"https://jobs.abc.com/api/v1/jobs"</span>)
    <span class="hljs-keyword">for</span> datum <span class="hljs-keyword">in</span> resp.data:
        Job.objects.create(url=datum.url, location=datum.location)
</code></pre>
]]></content:encoded></item><item><title><![CDATA[Decorators in python (part-2)]]></title><description><![CDATA[This is part-2 of decorators in python. In this post, we will learn about decorators with arguments and some of the applications]]></description><link>https://blog.lokesh1729.com/decorators-in-python-part-2</link><guid isPermaLink="true">https://blog.lokesh1729.com/decorators-in-python-part-2</guid><category><![CDATA[Python]]></category><category><![CDATA[Python]]></category><dc:creator><![CDATA[Lokesh Sanapalli]]></dc:creator><pubDate>Sat, 04 Feb 2023 14:09:52 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1675520069614/5a4e309d-d6c9-4ffa-8c1f-a4fcd099fabf.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-introduction">Introduction</h2>
<p>If you have not read <a target="_blank" href="https://lokesh1729.com/posts/python-decorators">the previous post</a>, please go through it because it is a prerequisite for this. In this post, we will go into some more depth and learn about decorators with arguments.</p>
<h2 id="heading-functoolswraps-decorator">functools.wraps decorator</h2>
<p>We learned from the previous blog post that when a function is decorated with a decorator, the representation of it will be changed to <code>decorator.&lt;locals&gt;.wrapper at 0x109e233a0&gt;</code> which looks ugly. How can we keep the original string representation of the function? Here comes <code>functools.wraps</code> the decorator. It is a decorator — again, so many decorators huh? — which restores the original function name. We will use it like the one below.</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> functools

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">decorator</span>(<span class="hljs-params">func</span>):</span>
<span class="hljs-meta">    @functools.wraps(func)</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">wrapper</span>(<span class="hljs-params">*args, **kwargs</span>):</span>
        <span class="hljs-keyword">pass</span>
    <span class="hljs-keyword">return</span> wrapper
</code></pre>
<p>In a nutshell, what it does is simply sets <code>__name__</code> , <code>__doc__</code> and <code>__module__</code> properties of the wrapper function to the original one.</p>
<pre><code class="lang-python">wrapper.__name__ = func.__name__
wrapper.__doc__ = func.__doc__
wrapper.__module__ = func.__module__
</code></pre>
<h2 id="heading-decorators-with-arguments">Decorators with arguments</h2>
<p>First, let's write a retry decorator which makes an API call and retries on failure.</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> requests
<span class="hljs-keyword">import</span> time
<span class="hljs-keyword">import</span> logging


logger = logging.getLogger(__name__)

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">retry</span>(<span class="hljs-params">make_http_call</span>):</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">wrapper</span>(<span class="hljs-params">*args, **kwargs</span>):</span>
        curr_retry_count = <span class="hljs-number">0</span>
        max_retries = <span class="hljs-number">5</span>
        retry_interval = <span class="hljs-number">10</span>
        <span class="hljs-keyword">while</span> init_retry_count &lt;= max_retries:
            <span class="hljs-keyword">try</span>:
                response = make_http_call(*args, **kwargs)
                <span class="hljs-keyword">if</span> response.status_code <span class="hljs-keyword">in</span> [<span class="hljs-number">200</span>, <span class="hljs-number">201</span>]:
                    <span class="hljs-keyword">return</span> response
            <span class="hljs-keyword">except</span> requests.RequestException:
                logger.error(<span class="hljs-string">"error in making call"</span>)
            time.sleep(retry_interval * (math.pow(<span class="hljs-number">2</span>, curr_retry_count - <span class="hljs-number">1</span>))) <span class="hljs-comment"># retry_interval * 2^(n-1) -&gt; exponential backoff</span>
            curr_retry_count += <span class="hljs-number">1</span>
        <span class="hljs-keyword">raise</span> requests.RequestException(<span class="hljs-string">"problem in making HTTP call please check logs"</span>)
    <span class="hljs-keyword">return</span> wrapper
</code></pre>
<p>In the above code snippet, <code>retry</code> is a function accepting <code>make_http_call</code> as a parameter. Assume that <code>make_http_call</code> triggers an HTTP request. The code is a no-brainer, it makes an HTTP request in a loop until the request is a success or the maximum retries are reached. It waits for some time until the next retry i.e. exponential backoff.</p>
<p>We want to make <code>retry</code> customizable by accepting <code>max_retry_count</code> and <code>retry_interval</code> because they may vary depending upon the usecase. How do we do that? simple, we will create another function which takes two parameters and simply wrap the above function inside it.</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> requests
<span class="hljs-keyword">import</span> time
<span class="hljs-keyword">import</span> logging


logger = logging.getLogger(__name__)


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">retry</span>(<span class="hljs-params">max_retries, retry_interval</span>):</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">inner</span>(<span class="hljs-params">make_http_call</span>):</span>
        <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">wrapper</span>(<span class="hljs-params">*args, **kwargs</span>):</span>
            curr_retry_count = <span class="hljs-number">0</span>
            <span class="hljs-keyword">while</span> init_retry_count &lt;= max_retries:
                <span class="hljs-keyword">try</span>:
                    response = make_http_call(*args, **kwargs)
                    <span class="hljs-keyword">if</span> response.status_code <span class="hljs-keyword">in</span> [<span class="hljs-number">200</span>, <span class="hljs-number">201</span>]:
                        <span class="hljs-keyword">return</span> response
                <span class="hljs-keyword">except</span> requests.RequestException:
                    logger.error(<span class="hljs-string">"error in making call"</span>)
                time.sleep(retry_interval * (math.pow(<span class="hljs-number">2</span>, curr_retry_count - <span class="hljs-number">1</span>))) <span class="hljs-comment"># retry_interval * 2^(n-1) -&gt; exponential backoff</span>
                curr_retry_count += <span class="hljs-number">1</span>
            <span class="hljs-keyword">raise</span> requests.RequestException(<span class="hljs-string">"problem in making HTTP call please check logs"</span>)
        <span class="hljs-keyword">return</span> wrapper
    <span class="hljs-keyword">return</span> inner


<span class="hljs-meta">@retry(10, 60)</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">make_http_request</span>(<span class="hljs-params">url, params=None, data=None</span>):</span>
    <span class="hljs-keyword">pass</span>
</code></pre>
<p>Mathematically, the above function <code>make_http_request</code> becomes <code>make_http_request = retry(10, 60)(make_http_request)</code> and calling that function would be like</p>
<pre><code class="lang-python">make_http_request(
    <span class="hljs-string">"https://api.twitter.com/v2/users"</span>,
    params={<span class="hljs-string">"username"</span>: <span class="hljs-string">"lsanapalli"</span>}
) = retry(<span class="hljs-number">10</span>, <span class="hljs-number">60</span>)(make_http_request)(
    <span class="hljs-string">"https://api.twitter.com/v2/users"</span>,
    params={<span class="hljs-string">"username"</span>: <span class="hljs-string">"lsanapalli"</span>}
)
</code></pre>
<h2 id="heading-using-multiple-decorators">Using multiple decorators</h2>
<p>Can we decorate a function with multiple decorators? yes. What will be the order of execution? simple, let's consider an example and stick to our basics.</p>
<pre><code class="lang-python"><span class="hljs-meta">@decorator3</span>
<span class="hljs-meta">@decorator2</span>
<span class="hljs-meta">@decorator1</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">myfunc</span>(<span class="hljs-params">a, b</span>):</span>
    <span class="hljs-keyword">pass</span>
</code></pre>
<p>Consider we have a function <code>myfunc</code> decorated with 3 decorators as above. Firstly, <code>myfunc</code> will be passed as an argument to <code>decorator1</code> and the result of that will be passed to <code>decorator2</code> and so on...</p>
<p><code>myfunc = decorator3(decorator2(decorator1(myfunc)))</code></p>
<p>If you prefer a video version, I made a video on the same topic.</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://www.youtube.com/watch?v=puMqIA4NNmc">https://www.youtube.com/watch?v=puMqIA4NNmc</a></div>
<p> </p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://youtu.be/4EiEUyvD0KU">https://youtu.be/4EiEUyvD0KU</a></div>
]]></content:encoded></item><item><title><![CDATA[Decorators in python (part-1)]]></title><description><![CDATA[Decorators in python are very useful in reducing boilerplate code. They extend the functionality of a function. In this blog post, we will deep dive i]]></description><link>https://blog.lokesh1729.com/python-decorators</link><guid isPermaLink="true">https://blog.lokesh1729.com/python-decorators</guid><category><![CDATA[Python]]></category><category><![CDATA[decorators]]></category><category><![CDATA[design patterns]]></category><dc:creator><![CDATA[Lokesh Sanapalli]]></dc:creator><pubDate>Sat, 04 Feb 2023 10:47:27 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1675507589761/ee0c97c1-105e-4943-8d65-cc7d0fb8ec17.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-introduction">Introduction</h2>
<p>As usual, let's stick to the first principles. Let's start with what was taught in our schools. What is a function in mathematics? <code>f(x) -&gt; y</code> spelled as <code>f of x</code> is a function that takes <code>x</code> as input and returns <code>y</code> as output. Right, It's the same thing in programming. A function takes some parameters as input and returns a value or object as output.</p>
<p>Let's understand the difference between the definition and the calling of a function.</p>
<pre><code class="lang-python"> <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">make_http_request</span>(<span class="hljs-params">url: str</span>) -&gt; http.Response:</span>
    resp = http.request(url)
    <span class="hljs-keyword">if</span> resp.status_code == <span class="hljs-number">200</span>:
        <span class="hljs-keyword">return</span> resp
    <span class="hljs-keyword">return</span> <span class="hljs-literal">None</span>
</code></pre>
<p>In the above code snippet, we defined a function <code>make_http_request</code> that takes <code>url</code> as the "parameter" and returns <code>http.Response</code> the object as output. As the definition we mean, the function will be registered with in-memory (RAM) when the program run. The calling of a function happens when we supply the "arguments" to the function as shown in the below code.</p>
<pre><code class="lang-python">resp = make_http_request(<span class="hljs-string">"https://twitter.com/api/users"</span>)
print(resp)
</code></pre>
<p><em>notice the difference between parameter and argument. "parameters" are the variables passed to the function, they are not the real values. "arguments" are the real values passed to the function. It's not much important to differentiate them as some people use both words interchangeably.</em></p>
<h2 id="heading-function-basics">Function Basics</h2>
<p>Functions are <a target="_blank" href="https://en.wikipedia.org/wiki/First-class_citizen">first-class citizens</a> in python. It means that they can be assigned to a variable, passed as an argument to a function, and returned from another function.</p>
<h3 id="heading-assign-function-to-a-variable">Assign function to a variable</h3>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">fetch_movies_by_actor</span>(<span class="hljs-params">actor_name, movie_db</span>):</span>
    <span class="hljs-keyword">if</span> actor_name == <span class="hljs-string">''</span> <span class="hljs-keyword">or</span> actor_name <span class="hljs-keyword">is</span> <span class="hljs-literal">None</span>:
        <span class="hljs-keyword">raise</span> ValueError(<span class="hljs-string">"actor name shouldn't be empty'"</span>)
    <span class="hljs-keyword">return</span> filter(<span class="hljs-keyword">lambda</span> movie: actor_name <span class="hljs-keyword">in</span> movie[<span class="hljs-string">"actors"</span>], movie_db)

<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">"__main__"</span>:
    obj = fetch_movies_by_actor
<span class="hljs-string">'''
<span class="hljs-meta">&gt;&gt;&gt; </span>print(obj)
&lt;function fetch_movies_by_actor at 0x109f01280&gt;
<span class="hljs-meta">&gt;&gt;&gt; </span>print(fetch_movies_by_actor)
&lt;function fetch_movies_by_actor at 0x109f01280&gt;
'''</span>
</code></pre>
<p>As seen from the above snippet, we defined a function named <code>fetch_movies_by_actor</code> and assigned it to a variable called <code>obj</code>. When I print both, they both printed the same.</p>
<h3 id="heading-pass-as-an-argument">Pass as an argument</h3>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">fetch_movies_by_actor</span>(<span class="hljs-params">actor_name, movie_db</span>):</span>
    <span class="hljs-keyword">if</span> actor_name == <span class="hljs-string">''</span> <span class="hljs-keyword">or</span> actor_name <span class="hljs-keyword">is</span> <span class="hljs-literal">None</span>:
        <span class="hljs-keyword">raise</span> ValueError(<span class="hljs-string">"actor name shouldn't be empty'"</span>)
    <span class="hljs-keyword">return</span> filter(<span class="hljs-keyword">lambda</span> movie: actor_name <span class="hljs-keyword">in</span> movie[<span class="hljs-string">"actors"</span>], movie_db)

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">fetch_movie_details</span>(<span class="hljs-params">actor_name, func</span>):</span>
    <span class="hljs-keyword">if</span> func <span class="hljs-keyword">is</span> <span class="hljs-keyword">not</span> <span class="hljs-literal">None</span>:
        print(func)
        movies = func(actor_name)
        <span class="hljs-keyword">return</span> movies
    <span class="hljs-keyword">return</span> []

<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">"__main__"</span>:
    result = fetch_movie_details(<span class="hljs-string">"Tom Cruise"</span>, fetch_movies_by_actor)
</code></pre>
<p>As seen in the above example, <code>fetch_movies_by_actor</code> the function is passed as an argument to <code>fetch_movie_details</code> and it is called there.</p>
<h3 id="heading-returning-from-another-function">Returning from another function</h3>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">fetch_movie_genres_by_year</span>(<span class="hljs-params">year</span>):</span>
    filtered_movies = list(filter(<span class="hljs-keyword">lambda</span> movie: movie[<span class="hljs-string">"year"</span>] == year, movie_db))
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">get_genres_by_movie_name</span>(<span class="hljs-params">movie_name</span>):</span>
        movie = list(filter(<span class="hljs-keyword">lambda</span> movie: movie[<span class="hljs-string">"name"</span>] == movie_name ,filtered_movies))[<span class="hljs-number">0</span>]
        <span class="hljs-keyword">return</span> movie[<span class="hljs-string">"genre"</span>]
    <span class="hljs-keyword">return</span> get_genres_by_movie_name
</code></pre>
<p>As seen in the above code snippet, the function <code>fetch_movie_genres_by_year</code> returned another function <code>get_genres_by_movie_name</code> . To obtain the final result, we need to do this 👇.</p>
<pre><code class="lang-python">movie_genres = fetch_movie_genres_by_year(<span class="hljs-number">2009</span>)(<span class="hljs-string">"XYZ"</span>)
</code></pre>
<p>Let's try to understand what's happening there. In mathematical terms, <code>f(x) -&gt; g(x) -&gt; result</code> the function <code>f(x)</code> returned <code>g(x)</code> which returned the result. So, to get the final result, we need to call <code>f(x)</code> and then <code>g(x)</code> that's what we did above.</p>
<h2 id="heading-decorators">Decorators</h2>
<p>What is a decorator? A decorator is a function, which takes a function as a parameter and returns another function. It may be slightly confusing at this point, but everything will be clear at the end. Why do decorators exist? What are its uses? <strong>Decorators extend the functionality of a function which reduces the lines of code to write</strong>. When to use decorators? Simple, when you see a lot of repetitive code.</p>
<p>Let's say you have hundreds of functions defined and you want to log the parameters of the function and the result of it for troubleshooting purposes. Using decorators, you can add them in a single place and apply them to all the functions.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">decorator</span>(<span class="hljs-params">func</span>):</span> <span class="hljs-comment"># decorator is a function, taking another function "func" as a parameter</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">wrapper</span>(<span class="hljs-params">*args, **kwargs</span>):</span>
        <span class="hljs-comment"># do something before evaluating function</span>
        result = func(*args, **kwargs)
        <span class="hljs-comment"># do something with result or some other stuff</span>
        <span class="hljs-keyword">return</span> result
    <span class="hljs-keyword">return</span> wrapper <span class="hljs-comment"># decorator is returning another function</span>

<span class="hljs-meta">@decorator</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">myfunc</span>(<span class="hljs-params">a, b</span>):</span>
    <span class="hljs-comment"># function body</span>
    <span class="hljs-keyword">pass</span>
<span class="hljs-string">'''
myfunc's identity will be changed as myfunc = decorator(myfunc)
'''</span>
</code></pre>
<p>In the above code snippet, <code>myfunc</code> is decorated with the decorator named <code>decorator</code> using <code>@</code> symbol which is syntactic sugar to use decorators in python. So, What happens when you decorate a function? Let's understand it.</p>
<pre><code class="lang-python"><span class="hljs-meta">@decorator</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">myfunc</span>(<span class="hljs-params">a, b</span>):</span>
    <span class="hljs-comment"># function body</span>
    <span class="hljs-keyword">pass</span>

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">myfunc2</span>(<span class="hljs-params">a, b</span>):</span>
    <span class="hljs-comment"># function body</span>
    <span class="hljs-keyword">pass</span>

<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">"__main__"</span>:
    print(myfunc)
    print(myfunc2)

<span class="hljs-string">'''
<span class="hljs-meta">&gt;&gt;&gt; </span>print(myfunc)
&lt;function decorator.&lt;locals&gt;.wrapper at 0x109e233a0&gt;
<span class="hljs-meta">&gt;&gt;&gt; </span>print(myfunc2)
&lt;function myfunc2 at 0x109e23430&gt;
'''</span>
</code></pre>
<p>As seen in the above code snippet, <code>myfunc</code> is printed with the name of the decorator and the function returned by the decorator i.e. <code>wrapper</code>. Whereas <code>myfunc2</code> is printed as usual.</p>
<p>It is clear that when a function is decorated with a decorator, the original function's definition will change to <code>myfunc = decorator(myfunc)</code> i.e. <code>myfunc = decorator(myfunc) -&gt; wrapper</code> . <strong>If we look at the decorator's definition, the</strong> <code>func</code> <strong>parameter is nothing but the original function which is decorated.</strong></p>
<p>Calling the original function will be equal to <code>myfunc(*args, **kwargs) = decorator(myfunc)(*args, **kwargs)</code> i.e. <code>myfunc(*args, **kwargs) = decorator(myfunc) -&gt; wrapper(*args, **kwargs)</code>. <strong>If we look at the decorator definition again, the arguments passed to the</strong> <code>wrapper</code> <strong>function inside the decorator are nothing but the arguments passed to the original function.</strong> Also, be sure to call the original function in the inner function of the decorator else the whole purpose of the decorator will be lost.</p>
<h3 id="heading-logger-example">Logger Example</h3>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> logging


logger = logging.getLogger(__name__)

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">CustomException</span>(<span class="hljs-params">Exception</span>):</span>
    <span class="hljs-keyword">pass</span>

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">exception_logger</span>(<span class="hljs-params">func</span>):</span>
    <span class="hljs-string">"""decorator to log the exceptions"""</span>

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">wrapper</span>(<span class="hljs-params">*args, **kwargs</span>):</span>
        <span class="hljs-keyword">try</span>:
            <span class="hljs-keyword">return</span> func(*args, **kwargs)
        <span class="hljs-keyword">except</span> Exception <span class="hljs-keyword">as</span> exc:
            logger.exception(
                <span class="hljs-string">"Unhandled exception in function %s , exception is %s"</span>, func.__name__, exc
            )
            <span class="hljs-keyword">raise</span> CustomException(<span class="hljs-string">"Unhandled exception in function %s"</span> % func.__name__) <span class="hljs-keyword">from</span> exc

    <span class="hljs-keyword">return</span> wrapper
</code></pre>
<p>In the above code snippet, the original function is called in between try and except block where we are catching and logging the exceptions.</p>
<p>Let's use the decorator and see what happens.</p>
<pre><code class="lang-python"><span class="hljs-meta">@exception_logger</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">func</span>(<span class="hljs-params">a, b</span>):</span> <span class="hljs-comment"># func = exception_logger(func)</span>
    <span class="hljs-keyword">return</span> a / b

print(func(<span class="hljs-number">1</span>, <span class="hljs-number">0</span>)) <span class="hljs-comment"># func(1, 0) = exception_logger(func)(1,0)</span>

<span class="hljs-string">'''
Unhandled exception in function func , exception is division by zero
Traceback (most recent call last):
  File "&lt;ipython-input-1-5525c8c2a27e&gt;", line 14, in inner
    return func(*args, **kwargs)
  File "&lt;ipython-input-3-e825ef26bd9c&gt;", line 3, in func
    return a / b
ZeroDivisionError: division by zero
'''</span>
</code></pre>
<p>As we see from the above snippet, the exception was logged by the decorator. When the program runs, firstly the <code>func</code> will be changed to <code>func = exception_logger(func)</code> . When we call the original function, we are indirectly calling the <code>wrapper</code> function of the decorator.</p>
<h3 id="heading-timing-example">Timing Example</h3>
<p>Let's write a decorator to measure the time taken by a function. Below is the code snippet for it. It is self-explanatory.</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> functools
<span class="hljs-keyword">import</span> time


<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">timeit</span>(<span class="hljs-params">func</span>):</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">wrapper</span>(<span class="hljs-params">*args, **kwargs</span>):</span>
        before_calling = time.time()
        result = func(*args, **kwargs)
        after_calling = time.time()
        print(<span class="hljs-string">"function %s has took %s seconds"</span> % (func.__name__, (after_calling - before_calling)))
        <span class="hljs-keyword">return</span> result
    <span class="hljs-keyword">return</span> wrapper
</code></pre>
<p>If you prefer a video version, check out 👇</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://www.youtube.com/watch?v=puMqIA4NNmc">https://www.youtube.com/watch?v=puMqIA4NNmc</a></div>
<p> </p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://youtu.be/4EiEUyvD0KU">https://youtu.be/4EiEUyvD0KU</a></div>
]]></content:encoded></item><item><title><![CDATA[Kafka Internals - Learn kafka in-depth (Part-2)]]></title><description><![CDATA[In my previous post, we learned about the basics of kafka. In this post, let's deep dive into the internals of kafka. How it is designed in such a way]]></description><link>https://blog.lokesh1729.com/kafka-internals-learn-kafka-in-depth-part-2</link><guid isPermaLink="true">https://blog.lokesh1729.com/kafka-internals-learn-kafka-in-depth-part-2</guid><category><![CDATA[Apache Kafka]]></category><dc:creator><![CDATA[Lokesh Sanapalli]]></dc:creator><pubDate>Sat, 28 Jan 2023 10:06:59 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1674900121973/ff7138f7-569f-4012-93cf-fe4b9745609d.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-introduction">Introduction</h2>
<p><a target="_blank" href="https://lokesh1729.com/posts/kafka-internals-learn-kafka-in-depth">In my previous blog post</a>, we learned the basics of kafka and covered vital concepts. If you haven't read it, it is a prerequisite, please read it. In this blog post, we will deep dive into the internals of kafka and learn how kafka works under the hood. At the end of the blog post, your perspective about kafka will change so that you feel kafka is not complex as you think.</p>
<h3 id="heading-basic-setup">Basic Setup</h3>
<p>Let's get started by installing kafka. <a target="_blank" href="https://www.apache.org/dyn/closer.cgi?path=/kafka/3.3.1/kafka_2.13-3.3.1.tgz">Download</a> the latest Kafka release and extract it. Open a terminal and start kafka and zookeeper.</p>
<pre><code class="lang-shell">$ cd $HOME
$ tar -xzf kafka_&lt;version&gt;.tgz
$ cd kafka_&lt;version&gt;
$ bin/zookeeper-server-start.sh config/zookeeper.properties
# open another terminal session and start kafka
$ bin/kafka-server-start.sh config/server.properties
</code></pre>
<p>Let's create a topic in a new terminal tab.</p>
<pre><code class="lang-shell"># Open another terminal and create a topic.
$ bin/kafka-topics.sh --create --topic payments --partitions 10 --replication-factor 1 \
 --bootstrap-server localhost:9092
</code></pre>
<blockquote>
<p>If you are wondering how the above command is constructed with those arguments, it's very simple. Just do, <code>bin/kafka-topics.sh --help</code> you will see all the arguments with descriptions. It's the same case with all the shell utilities present in <code>bin</code> folder.</p>
</blockquote>
<p>Now let's see what happens under the hood.</p>
<p>Go to <code>/tmp/kafka-logs</code> directory and do <code>ls</code> we will see the below result.</p>
<pre><code class="lang-sql">cleaner-offset-checkpoint        payments-0    payments-3    payments-6     payments-9
log-<span class="hljs-keyword">start</span>-<span class="hljs-keyword">offset</span>-checkpoint      payments<span class="hljs-number">-1</span>    payments<span class="hljs-number">-4</span>    payments<span class="hljs-number">-7</span>     <span class="hljs-keyword">recovery</span>-point-<span class="hljs-keyword">offset</span>-checkpoint
meta.properties                  payments<span class="hljs-number">-2</span>    payments<span class="hljs-number">-5</span>    payments<span class="hljs-number">-8</span>     <span class="hljs-keyword">replication</span>-<span class="hljs-keyword">offset</span>-checkpoint
</code></pre>
<blockquote>
<p><code>/tmp/kafka-logs</code> is the default directory where kafka stores the data. We can configure it to a different directory in <code>config/server.properties</code> for kafka and <code>config/zookeeper.properties</code> for zookeeper.</p>
</blockquote>
<h3 id="heading-recovery-point-offset-checkpoint">recovery-point-offset-checkpoint</h3>
<p>This file is used internally by the kafka broker to track the number of logs that are flushed to the disk. The format of the file is like this.</p>
<pre><code class="lang-sql">&lt;version&gt;
&lt;total entries&gt;
&lt;topic name&gt; &lt;partition&gt; offset
</code></pre>
<h3 id="heading-replication-offset-checkpoint">replication-offset-checkpoint</h3>
<p>This file is used internally by the kafka broker to track the number of logs that are replicated to all the brokers in the cluster. The format of this file is the same as the <code>recovery-point-offset-checkpoint</code> file mentioned above.</p>
<h3 id="heading-topic-amp-partitions">topic &amp; partitions</h3>
<p>As we see from the above result, <code>payments-0</code>, <code>payments-1</code> .... <code>payments-10</code> are the partitions that are nothing but the directories in the filesystem. As I highlighted in my previous blog post, the topic is a logical concept in kafka. It does not exist physically, only partitions do. A topic is a logical grouping of all partitions.</p>
<h2 id="heading-producer">Producer</h2>
<p>Now, let's produce some messages to the topic using the below command.</p>
<pre><code class="lang-shell">$ cd $HOME/kafka
$ bin/kafka-console-producer.sh --bootstrap-server localhost:9092 --topic payments
&gt; hello
&gt; world
&gt; hello world
&gt; hey there!
</code></pre>
<p>We produced four messages on the topic. Let's see how they are stored in the filesystem. It's hard to find out to which partition a message went because kafka uses a round-robin algorithm to distribute the data to the partitions. The simple way is to find the size of all partitions (directories) and pick the largest ones.</p>
<pre><code class="lang-shell">$ cd /tmp/kafka-logs
$ du -hs *
8.0K    payments-0
8.0K    payments-1
 12K    payments-2
8.0K    payments-3
 12K    payments-4
8.0K    payments-5
8.0K    payments-6
 12K    payments-7
8.0K    payments-8
 12K    payments-9
</code></pre>
<p>As we see from the above snippet, our messages went to partitions 2, 4, 7 &amp; 9. Let's see what's inside each of the partitions.</p>
<pre><code class="lang-shell">$ ls payments-7

00000000000000000000.index     00000000000000000000.log
00000000000000000000.timeindex leader-epoch-checkpoint
partition.metadata
$ cat 00000000000000000000.log
=
��Mr���Mr����������������
world%
$ cat partition.metadata
version: 0
topic_id: tbuB6k_uRsuEE03FsechjA
$ cat leader-epoch-checkpoint
0
1
0 0
$ cat 00000000000000000000.index
$ cat 00000000000000000000.timeindex
</code></pre>
<h3 id="heading-partition-metadata">Partition Metadata</h3>
<p><code>partition.metadata</code> file contains a <code>version</code> and a <code>topic_id</code>. This topic id is the same for all the partitions.</p>
<h3 id="heading-log-file">Log file</h3>
<p>This is where the data written by the producers are stored in a binary format. Let's try to view the contents of these files using command-line tools provided by kafka.</p>
<pre><code class="lang-shell">$ bin/kafka-dump-log.sh --files data/kafka/payments-7/00000000000000000000.log,data/kafka/payments-7/00000000000000000000.index --print-data-log

Dumping data/kafka/payments-7/00000000000000000000.log
Starting offset: 0
baseOffset: 0 lastOffset: 0 count: 1 baseSequence: -1 lastSequence: -1 producerId: -1
producerEpoch: -1 partitionLeaderEpoch: 0 isTransactional: false isControl: false position: 0
CreateTime: 1672041637310 size: 73 magic: 2 compresscodec: none crc: 456919687 isvalid: true | offset: 0
CreateTime: 1672041637310 keySize: -1 valueSize: 5 sequence: -1 headerKeys: [] payload: world
</code></pre>
<p>The explanation of the above output is self-explanatory except for a few properties. <code>payload</code> is the actual data that was pushed to kafka. <code>offset</code> tells how far the current message is from the zero indexes. <code>producerId</code> and <code>produerEpoch</code> are used in delivery guarantee semantics. We will discuss them in later blog posts. We will learn about <code>.index</code> and <code>.timeindex</code> files below.</p>
<h3 id="heading-partition-key">Partition Key</h3>
<p>We learned that kafka distributes data in a round-robin fashion to the partitions. But, what if we want to send data grouped by a key? that's where the partition key comes in. When we send data along with a partition key, kafka puts them in a single partition. How does kafka find the partition key? it computes using <code>hash(partition_key) % number_of_partitions</code>. If no partition key is present, then it uses a round-robin algorithm.</p>
<p>We may wonder, what is the use-case of a partition key? Kafka guarantees the ordering of messages only at a partition level, not at a topic level. The application of the partition key is to ensure the ordering of the messages across all partitions.</p>
<p>Let's see how this works under the hood. Let's produce some messages.</p>
<pre><code class="lang-shell">$ bin/kafka-console-producer.sh --bootstrap-server localhost:9092 --topic payments --property parse.key=true --property key.separator=\|
&gt; lokesh1729|{"message": "lokesh1729 : order placed"}
&gt; lokesh1729|{"message": "lokeh1729 : logged in"}
&gt; lokesh1729|{"message": "lokesh1729 : logged out"}
&gt; lokesh1729|{"message": "lokesh1729 : payment success"}
</code></pre>
<blockquote>
<p><code>parse.key</code> tells kafka to parse the key by the separator. By default <code>key.separator</code> is set to tab, we are overriding to pipe.</p>
</blockquote>
<p>Let's look at the data using the same <code>kafka-dump-log</code> command. We need to find the partition by executing the command in all 10 partitions because we don't know to which partition it went.</p>
<pre><code class="lang-shell">$ $ bin/kafka-dump-log.sh --files data/kafka/payments-7/00000000000000000000.log,data/kafka/payments-7/00000000000000000000.index --print-data-log
baseOffset: 2 lastOffset: 2 count: 1 baseSequence: -1 lastSequence: -1 producerId: -1 producerEpoch: -1 partitionLeaderEpoch: 0
isTransactional: false isControl: false position: 147 CreateTime: 1672057287522 size: 118 magic: 2 compresscodec: none crc: 2961270358
isvalid: true | offset: 2 CreateTime: 1672057287522 keySize: 10 valueSize: 40 sequence: -1 headerKeys: [] key: lokesh1729
payload: {"message": "lokesh1729 : order placed"}

baseOffset: 3 lastOffset: 3 count: 1 baseSequence: -1 lastSequence: -1 producerId: -1 producerEpoch: -1 partitionLeaderEpoch: 0
isTransactional: false isControl: false position: 265 CreateTime: 1672057301944 size: 114 magic: 2 compresscodec: none crc: 204260463
isvalid: true | offset: 3 CreateTime: 1672057301944 keySize: 10 valueSize: 36 sequence: -1 headerKeys: [] key: lokesh1729
payload: {"message": "lokeh1729 : logged in"}

baseOffset: 4 lastOffset: 4 count: 1 baseSequence: -1 lastSequence: -1 producerId: -1 producerEpoch: -1 partitionLeaderEpoch: 0
isTransactional: false isControl: false position: 379 CreateTime: 1672057311110 size: 116 magic: 2 compresscodec: none crc: 419761401
isvalid: true | offset: 4 CreateTime: 1672057311110 keySize: 10 valueSize: 38 sequence: -1 headerKeys: [] key: lokesh1729 payload: {"message": "lokesh1729 : logged out"}

baseOffset: 5 lastOffset: 5 count: 1 baseSequence: -1 lastSequence: -1 producerId: -1 producerEpoch: -1 partitionLeaderEpoch: 0
isTransactional: false isControl: false position: 495 CreateTime: 1672057327354 size: 121 magic: 2 compresscodec: none crc: 177029556
isvalid: true | offset: 5 CreateTime: 1672057327354 keySize: 10 valueSize: 43 sequence: -1 headerKeys: [] key: lokesh1729 payload: {"message": "lokesh1729 : payment success"}
</code></pre>
<p>As we see from the above log, all the messages with key <code>lokesh1729</code> went to the same partition i.e. partition 7.</p>
<h3 id="heading-index-and-timeindex-files">Index and Timeindex files</h3>
<p>Let's produce more messages with this <a target="_blank" href="https://gist.github.com/lokesh1729/977e146cab41b5001210810685b8c36d#file-producer-py">script</a> and dump the data using the above command.</p>
<pre><code class="lang-shell">$ bin/kafka-dump-log.sh --files data/kafka/payments-8/00000000000000000000.log,data/kafka/payments-8/00000000000000000000.index --print-data-log
Dumping data/kafka/payments-8/00000000000000000000.index
offset: 33 position: 4482
offset: 68 position: 9213
offset: 100 position: 13572
offset: 142 position: 18800
offset: 175 position: 23042
offset: 214 position: 27777
offset: 248 position: 32165
offset: 279 position: 36665
offset: 313 position: 40872
offset: 344 position: 45005
offset: 389 position: 49849
offset: 422 position: 54287
offset: 448 position: 58402
offset: 485 position: 62533
</code></pre>
<p>As we see from the above output, the index file stores the offset and its position of it in the <code>.log</code> file. Why is it needed? We know that consumers process messages sequentially. When a consumer asks for a message, kafka needs to fetch it from the log i.e. it needs to perform a disk I/O. Imagine, kafka reading each log file line by line to find an offset. It takes <code>O(n)</code> (where n is the number of lines in the file) time and latency of disk I/O. It will become a bottleneck when the log files are of gigabytes size. So, to optimize it, kafka stores the offset to position mapping in the <code>.index</code> file so that if a consumer asks for any arbitrary offset it simply does a binary search on the <code>.index</code> file in the <code>O(log n)</code> time and goes to the <code>.log</code> file and performs the binary search again.</p>
<p>Let's take an example, say a consumer is reading 190th offset. Firstly, the kafka broker reads the index file (refer to the above log) and performs a binary search, and either finds the exact offset or the closest to it. In this case, it finds offset as 175 and its position as 23042. Then, it goes to the <code>.log</code> file and performs the binary search again given the fact that the <code>.log</code> the file is an append-only data structure stored in ascending order of offsets.</p>
<p>Now, let's look at the <code>.timeindex</code> file. Let's dump the file using the below command.</p>
<pre><code class="lang-shell">$ bin/kafka-dump-log.sh --files data/kafka/payments-8/00000000000000000000.timeindex --print-data-log

Dumping data/kafka/payments-8/00000000000000000000.timeindex
timestamp: 1672131856604 offset: 33
timestamp: 1672131856661 offset: 68
timestamp: 1672131856701 offset: 100
timestamp: 1672131856738 offset: 142
timestamp: 1672131856772 offset: 175
timestamp: 1672131856816 offset: 213
timestamp: 1672131856862 offset: 247
timestamp: 1672131856901 offset: 279
timestamp: 1672131856930 offset: 312
timestamp: 1672131856981 offset: 344
timestamp: 1672131857029 offset: 388
timestamp: 1672131857076 offset: 419
timestamp: 1672131857102 offset: 448
timestamp: 1672131857147 offset: 484
timestamp: 1672131857185 offset: 517
timestamp: 1672131857239 offset: 547
</code></pre>
<p>As we see from the above result, <code>.timeindex</code> the file stores the mapping between the epoch timestamp and the offset in the <code>.index</code> file. When the consumer wants to replay the event based on the timestamp, kafka first finds the offset by doing a binary search in the <code>.timeindex</code> file, find the offset, and finds the position by doing a binary search on the <code>.index</code> file.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1674900335139/10ad7d9c-4e91-42ee-9a94-4701187832a7.png" alt="An image representing how .index and .timeindex files work in kafka" class="image--center mx-auto" /></p>
<h2 id="heading-consumer">Consumer</h2>
<p>Let's start the consumer using the below command</p>
<pre><code class="lang-shell">$ bin/kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic payments --group payments-consumer --from-beginning
{"message": "lokesh1729 : order placed"}
{"message": "lokeh1729 : logged in"}
{"message": "lokesh1729 : logged out"}
{"message": "lokesh1729 : payment success"}
</code></pre>
<blockquote>
<p>Note that <code>--from-beginning</code> argument is used to read from the start. If not used, the consumer reads the latest messages i.e. messages produced after the consumer is started.</p>
</blockquote>
<p>Now, let's take a look at the filesystem. We can observe that there will be new folders created with the name <code>__consumer_offsets-0</code>, <code>__consumer_offsets-1</code> .... <code>__consumer_offsets-49</code>. Kafka stores the state of each consumer offset in a topic called <code>__consumer_offsets</code> with a default partition size of 50. If we look at what's inside the folder, the same files will be present as in the <code>payments</code> topic we have seen above.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1674900368833/89f5cf3a-ddd3-4bd5-b0f8-fbab377aea99.png" alt="An image depicting the interaction between kafka broker and consumer" class="image--center mx-auto" /></p>
<p>As we see from the above image, the consumer polls for the records and commits the offset whenever it's done processing. Kafka is flexible such that we can configure how many records to fetch in a single poll, auto-committing interval, etc... We will discuss all these configurations in a separate blog post.</p>
<p>When a consumer is committing the offset, it sends the topic name, partition &amp; offset information. Then, the broker uses it to construct the key as <code>&lt;consumer_group_name&gt;, &lt;topic&gt;, &lt;partition&gt;</code> and value as <code>&lt;offset&gt;,&lt;partition_leader_epoch&gt;,&lt;metadata&gt;,&lt;timestamp&gt;</code> and store it in the <code>__consumer_offsets</code> topic.</p>
<p>When the consumer is crashed or restarted, it sends the request to the kafka broker and the broker finds the partition in <code>__consumer_offsets</code> by doing <code>hash(&lt;consumer_group_name&gt;, &lt;topic&gt;, &lt;partition&gt; ) % 50</code> and fetches the latest offset and returns it to the consumer.</p>
<h2 id="heading-disk-io-optimization">Disk I/O Optimization</h2>
<p>Kafka uses the hard disk as its primary data store. We know that disk I/O is slow compared to the main memory. So, we may wonder how kafka is achieving low latency at high throughput. Let's dive into it.</p>
<ol>
<li><p><a target="_blank" href="https://kafka.apache.org/documentation/#design_filesystem">Sequential disk reads can be faster than random memory access.</a> Modern operating systems provide capabilities to read data from disk in multiple blocks.</p>
</li>
<li><p>Modern operating systems use free main memory for disk caching and divert disk I/O through this cache.</p>
</li>
<li><p>Relying on the disk cache is more optimal than the main memory because the disk cache stays warm even if the service had crashed or restarted.</p>
</li>
<li><p>Kafka uses index files for faster access. We discussed them above already.</p>
</li>
<li><p>Kafka batches disk writes.</p>
</li>
</ol>
<p>Below is a sample log from the <code>.log</code> file. Let's dissect it.</p>
<p><code>baseOffset</code> - the starting offset to start with</p>
<p><code>lastOffset</code> - self-explanatory</p>
<p><code>count</code> - the total number of messages in the batch</p>
<p><code>CreateTime</code> - the epoch timestamp of created date</p>
<p><code>size</code> - total size of the messages in the batch in bytes</p>
<pre><code class="lang-sql">baseOffset: 1992 lastOffset: 1995 count: 4 baseSequence: -1 lastSequence: -1 producerId: -1 producerEpoch: -1 partitionLeaderEpoch: 0 isTransactional: false isControl: false position: 260309 CreateTime: 1672131859025 size: 474 magic: 2 compresscodec: none crc: 36982599 isvalid: true
| offset: 1992 CreateTime: 1672131859022 keySize: 12 valueSize: 84 sequence: -1 headerKeys: [] key: craigpearson payload: {"username": "craigpearson", "address": "0414 Fischer Rest\nZacharyshire, MN 38196"}
| offset: 1993 CreateTime: 1672131859024 keySize: 11 valueSize: 80 sequence: -1 headerKeys: [] key: gregoryjoel payload: {"username": "gregoryjoel", "address": "827 Nelson Burg\nSherrimouth, OK 49255"}
| offset: 1994 CreateTime: 1672131859025 keySize: 11 valueSize: 83 sequence: -1 headerKeys: [] key: gregoryjoel payload: {"username": "gregoryjoel", "address": "8306 Reed Trail\nFitzgeraldstad, PA 18715"}
| offset: 1995 CreateTime: 1672131859025 keySize: 12 valueSize: 84 sequence: -1 headerKeys: [] key: craigpearson payload: {"username": "craigpearson", "address": "0533 Crystal Forks\nJasminefort, NV 54576"}
</code></pre>
<h2 id="heading-bonus">Bonus</h2>
<ol>
<li><p><a target="_blank" href="https://www.kafkatool.com/download.html">Offset Explorer</a> - A useful tool to view topic and consumer information.</p>
</li>
<li><p><a target="_blank" href="https://hub.docker.com/r/bitnami/kafka">Kafka Docker images by Bitnami</a></p>
</li>
</ol>
]]></content:encoded></item><item><title><![CDATA[Change Data Capture Using Debezium]]></title><description><![CDATA[One of the popular Change Data Capture (CDC) systems is debezium. In this blog post, we will discuss how to setup debezium and how it works internally]]></description><link>https://blog.lokesh1729.com/change-data-capture-using-debezium</link><guid isPermaLink="true">https://blog.lokesh1729.com/change-data-capture-using-debezium</guid><category><![CDATA[debezium]]></category><category><![CDATA[cdc]]></category><category><![CDATA[change data capture]]></category><dc:creator><![CDATA[Lokesh Sanapalli]]></dc:creator><pubDate>Sat, 28 Jan 2023 09:46:59 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1674899459818/adf5ac8c-f36c-4ce6-9ed1-47006f739965.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-introduction">Introduction</h2>
<p>What is change data capture? A change that occurred in one data source will be captured and replicated in another data source. Let's understand it with a picture.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1674888598990/05b669d9-1037-4c46-955d-865744b1dce3.png" alt class="image--center mx-auto" /></p>
<p><strong>A</strong>: Databases maintain transactional log where it writes all DDL &amp; DML queries. MySQL maintains binlog and PostgreSQL maintains WAL (write-ahead logs).</p>
<p><strong>B &amp; C</strong>: The source connector connects to the database and reads the transaction logs. It then prepares an in-memory structure of the change and writes to the message broker. Generally, CDC systems maintain a single schema for the change so that different database connectors transform the data into it.</p>
<p><strong>D &amp; E</strong>: The sink connector connects to the message broker, reads the data, and writes the change to the target database.</p>
<h2 id="heading-use-cases-of-cdc">Use-cases of CDC</h2>
<p>Let's think about different use cases of CDC in software engineering.</p>
<ol>
<li><p>OLAP (online analytical processing) systems use CDC to migrate data from transactional databases to analytical databases.</p>
</li>
<li><p>OLTP (online transactional processing) systems can also use CDC as an event bus to replicate data in a different data store. For example, from MySQL to Elasticsearch.</p>
</li>
</ol>
<p>One of the popular and widely-used systems is <a target="_blank" href="https://debezium.io/documentation/reference/stable/index.html">debezium</a>. In this blog post, we will discuss how to set up debezium and how it works internally.</p>
<h2 id="heading-debezium">Debezium</h2>
<p>Debezium works on top of kafka connect. Kafka Connect is a framework for streaming data between multiple systems. When deployed, it provides REST APIs to manage connectors. There are two connectors, the source, and the sink. As we saw from the above diagram, the source connector reads the source database and writes the data to the kafka topics. The sink connectors read from those kafka topics and write to the target database. Debezium is built using the kafka connect framework. It comes with connectors for different databases.</p>
<p>Debezium can only be installed through docker. The installation is very easy. Just pull the image from the registry and run it. More instructions are given <a target="_blank" href="https://debezium.io/documentation/reference/stable/tutorial.html">here</a>. Once deployed, the debezium server will be running on port 8083 by default. We can hit its REST API to create connectors.</p>
<pre><code class="lang-bash"><span class="hljs-comment"># view connectors</span>
curl -i -X GET localhost:8083/connectors
<span class="hljs-comment"># create a connector</span>
curl -i -X POST -H <span class="hljs-string">"Accept:application/json"</span> -H <span class="hljs-string">"Content-Type:application/json"</span> localhost:8083/connectors/ -d @mysql-connector.json
<span class="hljs-comment"># delete a connector</span>
curl -i -X DELETE localhost:8083/connectors/&lt;connector name&gt;
</code></pre>
<h2 id="heading-debezium-and-mysql">Debezium and MySQL</h2>
<p>MySQL maintains a binary log (binlog) that writes all the schema changes and data changes in the same order as they happened. The debezium MySQL connector reads the binlog and produces change events for every schema and row-level change.</p>
<h3 id="heading-create-a-mysql-user">Create a MySQL User</h3>
<p>In order for debezium to read binlog, it should have a user with specific permissions. Before we deploy our MySQL connector, let's create a user with the following commands.</p>
<pre><code class="lang-bash">CREATE USER <span class="hljs-string">'user'</span>@<span class="hljs-string">'localhost'</span> IDENTIFIED BY <span class="hljs-string">'password'</span>;
GRANT SELECT, RELOAD, SHOW DATABASES, LOCK TABLES, REPLICATION SLAVE, REPLICATION CLIENT ON *.* TO <span class="hljs-string">'user'</span> IDENTIFIED BY <span class="hljs-string">'password'</span>;
FLUSH PRIVILEGES;
</code></pre>
<h3 id="heading-enable-binlogs">Enable binlogs</h3>
<p>The procedure for enabling binlogs in a self-hosted environment is easy. The instructions are given <a target="_blank" href="https://debezium.io/documentation/reference/stable/connectors/mysql.html#enable-mysql-binlog">here</a>. If you are using managed services like AWS, <a target="_blank" href="https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_LogAccess.MySQL.BinaryFormat.html">you can enable it from the console</a>. Also, AWS RDS gives a few stored procedures to set this.</p>
<pre><code class="lang-bash"><span class="hljs-comment"># show rds config</span>
call mysql.rds_show_configuration;
<span class="hljs-comment"># set binlog retention period</span>
call mysql.rds_set_configuration(<span class="hljs-string">'binlog retention hours'</span>, 96);
</code></pre>
<h3 id="heading-deploy-mysql-connector">Deploy MySQL Connector</h3>
<p>Before deploying a MySQL connector, we need to prepare the JSON.</p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"name"</span>: <span class="hljs-string">"debezium-connector1"</span>,
  <span class="hljs-attr">"config"</span>: {
    <span class="hljs-attr">"connector.class"</span>: <span class="hljs-string">"io.debezium.connector.mysql.MySqlConnector"</span>,
    <span class="hljs-attr">"database.hostname"</span>: <span class="hljs-string">"localhost"</span>,
    <span class="hljs-attr">"database.port"</span>: <span class="hljs-string">"3306"</span>,
    <span class="hljs-attr">"database.user"</span>: <span class="hljs-string">"debezium"</span>,
    <span class="hljs-attr">"database.password"</span>: <span class="hljs-string">"abc123"</span>,
    <span class="hljs-attr">"database.server.id"</span>: <span class="hljs-string">"130"</span>,
    <span class="hljs-attr">"topic.prefix"</span>: <span class="hljs-string">"prod-debezium"</span>,
    <span class="hljs-attr">"database.include.list"</span>: <span class="hljs-string">"mydatabase"</span>,
    <span class="hljs-attr">"table.include.list"</span>: <span class="hljs-string">"mydatabase.users,mydatabase.orders"</span>,
    <span class="hljs-attr">"snapshot.mode"</span>: <span class="hljs-string">"initial"</span>,
    <span class="hljs-attr">"schema.history.internal.kafka.bootstrap.servers"</span>: <span class="hljs-string">"localhost:9092,locahost:9093,localhost:9094"</span>,
    <span class="hljs-attr">"schema.history.internal.kafka.topic"</span>: <span class="hljs-string">"dbhistory.debezium"</span>,
    <span class="hljs-attr">"provide.transaction.metadata"</span>: <span class="hljs-string">"true"</span>,
    <span class="hljs-attr">"topic.creation.default.replication.factor"</span>: <span class="hljs-number">2</span>,
    <span class="hljs-attr">"topic.creation.default.partitions"</span>: <span class="hljs-number">10</span>,
    <span class="hljs-attr">"database.history.skip.unparseable.ddl"</span>: <span class="hljs-string">"true"</span>,
    <span class="hljs-attr">"event.processing.failure.handling.mode"</span>: <span class="hljs-string">"warn"</span>,
    <span class="hljs-attr">"snapshot.lock.timeout.ms"</span>: <span class="hljs-number">180000</span>,
  }
}
</code></pre>
<p>Let's try to understand the meaning of each configuration. I skip self-explanatory configs and mention only the important ones.</p>
<p><code>connector.class</code> - This is the path to the connector in the debezium code. When this connector is deployed, that particular class will run and process the data. So, it is important to give this config correctly.</p>
<p><code>database.server.id</code> - The unique identifier of the connector. This differentiates the other MySQL connector.</p>
<p><code>topic.prefix</code> - In older versions, it used to be <code>database.server.name</code> . This provides a namespace for the current instance of the connector. Debezium creates kafka topics by appending this prefix with the table name i.e. <code>&lt;topic.prefix&gt;.&lt;table_name&gt;</code>. This should be unique for a connector else debezium assumes it is an existing connector and tries to resume from where it stopped.</p>
<h3 id="heading-database-history-topic">Database History Topic</h3>
<p>A client connects to the database and reads its current schema. But the schema can change anytime. So, the debezium connector cannot just read the current schema because it may be processing the older change events from the database. It needs to correlate the current change with the exact schema. So, It needs to store the schema changes somewhere.</p>
<p>We know that MySQL emits the schema changes along with the row level changes to the binlog. Debezium reads the DDL statements, prepares an in-memory representation of the table, and also stores them in a separate topic along with the binlog position. This topic is called database history topic. It is configured with <code>schema.history.internal.kafka.topic</code> .</p>
<p>When the connector restarts, it reads the schema history topic and starts rebuilding the in-memory representation of each table, and resumes reading the binlog where it left off. <strong>The debezium connector emits the schema along with the row-level change so that the consumer systems can rebuild the whole table.</strong></p>
<p>A very important note about the history topic is it is only for debezium internal use and <strong>it should not be partitioned</strong>. Meaning, it should have a partition of only one. Why? because in kafka the ordering of messages is guaranteed only at the partition level, not at the topic level. So, if it is partitioned, then the order of schema changes will be mixed which leads to chaos.</p>
<p>This is how the data from the schema history topic looks</p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"source"</span> : {
    <span class="hljs-attr">"server"</span> : <span class="hljs-string">"prod-debezium"</span>
  },
  <span class="hljs-attr">"position"</span> : {
    <span class="hljs-attr">"transaction_id"</span> : <span class="hljs-literal">null</span>,
    <span class="hljs-attr">"ts_sec"</span> : <span class="hljs-number">1674648853</span>,
    <span class="hljs-attr">"file"</span> : <span class="hljs-string">"mysql-bin-changelog.106869"</span>,
    <span class="hljs-attr">"pos"</span> : <span class="hljs-number">69735280</span>,
    <span class="hljs-attr">"server_id"</span> : <span class="hljs-number">1229362390</span>
  },
  <span class="hljs-attr">"databaseName"</span> : <span class="hljs-string">"licious"</span>,
  <span class="hljs-attr">"ddl"</span> : <span class="hljs-string">"CREATE TABLE `user_groups` (\n\t`id` bigint(20) NOT NULL AUTO_INCREMENT PRIMARY KEY,\n\t`user_id` bigint(20),\n\t`customer_key` varchar(25) NOT NULL,\n\tCONSTRAINT FOREIGN KEY `fk_user_id` (user_id) REFERENCES `users`(id) ON DELETE CASCADE,\n\tCONSTRAINT UNIQUE KEY `unique_user_group_id` (user_id, customer_key)\n) ENGINE=InnoDB DEFAULT CHARSET=latin1"</span>,
  <span class="hljs-attr">"tableChanges"</span> : [ ]
}
</code></pre>
<h3 id="heading-schema-change-topic">Schema Change Topic</h3>
<p>As the schema history topic is for the internal use of debezium, it provides a schema change topic where external consumers can consume the schema change events. The topic name can be configured with <code>topic.prefix</code> (earlier <code>database.server.name</code>)</p>
<h3 id="heading-snapshots">Snapshots</h3>
<p>Debezium stores the snapshots of the database to provide high fault tolerance. In order to perform a snapshot, the connector first tries to get the global read lock that blocks the writes by the other clients and then reads the schema of all the tables and releases the lock. Acquiring a lock is very important because it helps in maintaining consistency as it blocks writes during that period. In case the global read lock is not possible, then it acquires table-level locks. More about it <a target="_blank" href="https://debezium.io/documentation/reference/stable/connectors/mysql.html#mysql-snapshots">here</a>.</p>
<p>There are different modes of snapshots. It can be configured with <code>snapshot.mode</code> . The most used modes are</p>
<p><code>initial</code> used when you need the schema changes and the row level changes from the beginning. Schema changes are written to schema history and schema change topics and the data changes are written to <code>&lt;topic.prefix&gt;.&lt;table_name&gt;</code> .</p>
<p><code>schema_only</code> takes the snapshot of only schema. This is useful if you don't want the entire data of the tables instead you only need the data from the moment you deployed. This mode is used if your tables contain dynamic data in an OLTP system.</p>
<p><code>when_needed</code> takes the snapshot whenever it's necessary i.e. when the binlogs are deleted or the schema history topic is deleted etc...</p>
<h2 id="heading-troubleshooting-debezium">Troubleshooting Debezium</h2>
<h3 id="heading-the-mysql-server-is-not-configured-to-use-a-row-binlogformat-which-is-required-for-this-connector-to-work-properly">The MySQL server is not configured to use a ROW binlog_format, which is required for this connector to work properly</h3>
<pre><code class="lang-plaintext">io.debezium.DebeziumException: The MySQL server is not
configured to use a ROW binlog_format, which is required for this
connector to work properly. Change the MySQL configuration to use a
binlog_format=ROW and restart the connector.     at
io.debezium.connector.mysql.MySqlConnectorTask.validateBinlogConfiguration(MySqlConnectorTask.java:262) at
io.debezium.connector.mysql.MySqlConnectorTask.start(MySqlConnectorTask.java:86) at
io.debezium.connector.common.BaseSourceTask.start(BaseSourceTask.java:130)     at
org.apache.kafka.connect.runtime.WorkerSourceTask.execute(WorkerSourceTask.java:232)     at
</code></pre>
<p>Change the MySQL configuration either through <code>/etc/mysql.cnf</code> or by executing the below command in the MySQL shell.</p>
<p><code>SET GLOBAL binlog_format = 'ROW';</code></p>
<p>Refer - <a target="_blank" href="https://dev.mysql.com/doc/refman/8.0/en/binary-log-setting.html">MySQL Documentation</a></p>
<h3 id="heading-database-history-topic-retentionmshttpretentionms-should-be-1-or-greater-than-5-years"><em>Database history topic</em> <a target="_blank" href="http://retention.ms"><em>retention.ms</em></a> <em>should be ‘-1’ or greater than 5 years</em></h3>
<pre><code class="lang-plaintext">2022-01-06 13:08:55,904 WARN   ||  Database history topic
'dbhistory.dev-jigyasa-licious' option 'retention.ms' should be '-1' or greater than '157680000000' (5 years)
but is '604800000'   [io.debezium.relational.history.KafkaDatabaseHistory]
</code></pre>
<p>Set the <code>retention.ms</code> property of database history topic to -1 via kafka CLI.</p>
<h3 id="heading-the-connector-is-trying-to-read-binlog-but-this-is-no-longer-available-on-the-server"><em>The connector is trying to read binlog but this is no longer available on the server.</em></h3>
<pre><code class="lang-plaintext">2022-01-06 13:08:56,405 ERROR  || 
WorkerSourceTask{id=jigyasa-mysql-connector-licious-2-0} Task threw an uncaught and unrecoverable exception.
Task is being killed and will not recover until manually restarted  
[org.apache.kafka.connect.runtime.WorkerTask] io.debezium.DebeziumException:
The connector is trying to read binlog starting at SourceInfo [currentGtid=null,
currentBinlogFilename=mysql-bin-changelog.032256, currentBinlogPosition=53270, currentRowNumber=0,
serverId=0, sourceTime=null, threadId=-1, currentQuery=null, tableIds=[], databaseName=null],
but this is no longer available on the server. Reconfigure the connector to use a snapshot when needed.  


2022-01-06 13:08:56,405 INFO   ||  Connector requires binlog file
'mysql-bin-changelog.032256', but MySQL only has mysql-bin-changelog.032918, mysql-bin-changelog.032919,
mysql-bin-changelog.032920   [io.debezium.connector.mysql.MySqlConnectorTask]
</code></pre>
<ol>
<li><p>Extend the binlog retention time using the commands mentioned above.</p>
</li>
<li><p>Delete the connector and re-deploy it again using REST API.</p>
</li>
</ol>
<h3 id="heading-could-not-find-the-first-log-file-name-in-the-binary-log-index-file-error-code-1236-sqlstate-hy000"><em>Could not find the first log file name in the binary log index file Error code: 1236; SQLSTATE: HY000.</em></h3>
<pre><code class="lang-plaintext">org.apache.kafka.connect.errors.ConnectException: An exception occurred in the change event producer. This connector will be stopped.
    at io.debezium.pipeline.ErrorHandler.setProducerThrowable(ErrorHandler.java:42)
    at io.debezium.connector.mysql.MySqlStreamingChangeEventSource$ReaderThreadLifecycleListener.onCommunicationFailure(MySqlStreamingChangeEventSource.java:1217)
    at com.github.shyiko.mysql.binlog.BinaryLogClient.listenForEventPackets(BinaryLogClient.java:980)
    at com.github.shyiko.mysql.binlog.BinaryLogClient.connect(BinaryLogClient.java:599)
    at com.github.shyiko.mysql.binlog.BinaryLogClient$7.run(BinaryLogClient.java:857)
    at java.base/java.lang.Thread.run(Thread.java:829)
Caused by: io.debezium.DebeziumException: Could not find first log file name in binary log index file Error code: 1236; SQLSTATE: HY000.
    at io.debezium.connector.mysql.MySqlStreamingChangeEventSource.wrap(MySqlStreamingChangeEventSource.java:1172)
    ... 5 more
Caused by: com.github.shyiko.mysql.binlog.network.ServerException: Could not find first log file name in binary log index file
    at com.github.shyiko.mysql.binlog.BinaryLogClient.listenForEventPackets(BinaryLogClient.java:944)
    ... 3 more
</code></pre>
<p>This generally happens if you had upgraded MySQL, and cleaned up the binlogs. Delete the connector and re-deploy it again using REST API.</p>
<h3 id="heading-iodebeziumdebeziumexception-failed-to-read-next-byte-from-position-1640249837"><em>io.debezium.DebeziumException: Failed to read next byte from position 1640249837</em></h3>
<pre><code class="lang-plaintext">org.apache.kafka.connect.errors.ConnectException: An exception occurred in the change event producer. This connector will be stopped.
    at io.debezium.pipeline.ErrorHandler.setProducerThrowable(ErrorHandler.java:42)
    at io.debezium.connector.mysql.MySqlStreamingChangeEventSource$ReaderThreadLifecycleListener.onCommunicationFailure(MySqlStreamingChangeEventSource.java:1217)
    at com.github.shyiko.mysql.binlog.BinaryLogClient.listenForEventPackets(BinaryLogClient.java:980)
    at com.github.shyiko.mysql.binlog.BinaryLogClient.connect(BinaryLogClient.java:599)
    at com.github.shyiko.mysql.binlog.BinaryLogClient$7.run(BinaryLogClient.java:857)
    at java.base/java.lang.Thread.run(Thread.java:829)
Caused by: io.debezium.DebeziumException: Failed to read next byte from position 1640249837
    at io.debezium.connector.mysql.MySqlStreamingChangeEventSource.wrap(MySqlStreamingChangeEventSource.java:1172)
    ... 5 more
Caused by: java.io.EOFException: Failed to read next byte from position 1640249837
    at com.github.shyiko.mysql.binlog.io.ByteArrayInputStream.read(ByteArrayInputStream.java:213)
    at com.github.shyiko.mysql.binlog.io.ByteArrayInputStream.readInteger(ByteArrayInputStream.java:52)
    at com.github.shyiko.mysql.binlog.event.deserialization.EventHeaderV4Deserializer.deserialize(EventHeaderV4Deserializer.java:35)
    at com.github.shyiko.mysql.binlog.event.deserialization.EventHeaderV4Deserializer.deserialize(EventHeaderV4Deserializer.java:27)
    at com.github.shyiko.mysql.binlog.event.deserialization.EventDeserializer.nextEvent(EventDeserializer.java:221)
    at io.debezium.connector.mysql.MySqlStreamingChangeEventSource$1.nextEvent(MySqlStreamingChangeEventSource.java:230)
    at com.github.shyiko.mysql.binlog.BinaryLogClient.listenForEventPackets(BinaryLogClient.java:952)
    ... 3 more
</code></pre>
<p>This happens if the binlog contains any special character that the connector is not able to process. One way to resolve this is to set <code>event.processing.failure.handling.mode</code> to warn in the connector configuration.</p>
<h3 id="heading-mysqltransactionrollbackexception-lock-wait-timeout-exceeded-try-restarting-transaction"><em>MySQLTransactionRollbackException: Lock wait timeout exceeded; try restarting transaction</em></h3>
<pre><code class="lang-plaintext">org.apache.kafka.connect.errors.ConnectException:An exception occurred in the change event producer. This connector will be
stopped.
    at
io.debezium.pipeline.ErrorHandler.setProducerThrowable(ErrorHandler.java:42)
    at
io.debezium.pipeline.ChangeEventSourceCoordinator.lambda$start$0(ChangeEventSourceCoordinator.java:115)
    at
java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:515)
    at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
    at
java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
    at
java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
    at java.base/java.lang.Thread.run(Thread.java:829)
Caused by:
io.debezium.DebeziumException: com.mysql.cj.jdbc.exceptions.MySQLTransactionRollbackException: Lock wait
timeout exceeded; try restarting transaction
    at
io.debezium.pipeline.source.AbstractSnapshotChangeEventSource.execute(AbstractSnapshotChangeEventSource.java:85)
    at
io.debezium.pipeline.ChangeEventSourceCoordinator.doSnapshot(ChangeEventSourceCoordinator.java:153)
    at
</code></pre>
<p>This happens when the debezium connector failed to get the global read lock or table level lock.</p>
<ol>
<li><p>Increase the <a target="_blank" href="http://snapshot.lock.timeout.ms"><code>snapshot.lock.timeout.ms</code></a> to 10-15 minutes and re-deploy the connector so that the debezium connector waits for some more time to acquire the lock.</p>
</li>
<li><p>If the above solution did not help, it means that the database is busy. Simply, kill all those clients and re-deploy the connector.</p>
</li>
</ol>
<pre><code class="lang-sql"><span class="hljs-keyword">show</span> <span class="hljs-keyword">open</span> <span class="hljs-keyword">tables</span> <span class="hljs-keyword">where</span> in_use&gt;<span class="hljs-number">0</span>;
<span class="hljs-keyword">show</span> <span class="hljs-keyword">full</span> <span class="hljs-keyword">processlist</span>;
<span class="hljs-keyword">kill</span> &lt;pid&gt;;
</code></pre>
]]></content:encoded></item><item><title><![CDATA[Rate Limiting - Different Approaches and Implementation]]></title><description><![CDATA[In software engineering, rate limiting has so many use cases. A few examples are Limiting the number of times OTP is sent to mobile numbers. Protecting the…]]></description><link>https://blog.lokesh1729.com/rate-limiting</link><guid isPermaLink="true">https://blog.lokesh1729.com/rate-limiting</guid><category><![CDATA[Redis]]></category><category><![CDATA[Python]]></category><category><![CDATA[ratelimit]]></category><dc:creator><![CDATA[Lokesh Sanapalli]]></dc:creator><pubDate>Tue, 24 Jan 2023 12:42:58 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1674564157433/eec7fe32-0344-4e46-9d90-5812135a173e.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-introduction">Introduction</h2>
<p>In software engineering, rate limiting has so many use cases. A few examples are</p>
<ol>
<li><p>Limiting the number of times OTP is sent to mobile numbers.</p>
</li>
<li><p>Protecting the systems from DDOS (distributed denial of service) attacks.</p>
</li>
<li><p>Enterprise SaaS has pricing based on the number of requests per minute - so it is directly related to the business.</p>
</li>
</ol>
<p>In this blog post, we will discuss different approaches of rate limiting.</p>
<h2 id="heading-first-principle-approach">First Principle Approach</h2>
<p>Let's start with very basic first-principle thinking. What is rate limiting? let's break it down. Rate is the velocity at which an object is moving. We measure the velocity of the car in km per hour. Similarly, in computer science, the rate at which the requests are entered into a system is measured in requests per second. Limiting is self-explanatory. So, the problem statement is to control the rate at which the requests are coming to a system.</p>
<p>To measure the rate, we need to store the data somewhere. What are the options we have? hard disk and main memory. The disks are slow — This is not always true! it depends on how we use it! sequential reads and writes are relatively faster in the disk and we can further optimize it with the operating system's page caching into main memory — so the only option we have is main memory.</p>
<p>There are two popular libraries that store data in the main memory with high-level abstractions. They are Memcached and Redis. We need to leverage them to implement rate limiting. Let's see how we can do that.</p>
<h2 id="heading-token-bucket-algorithm">Token Bucket Algorithm</h2>
<p>The idea is simple, we will store the rate limit "X" at a cache key with an expiry of "T" seconds. The cache key can be an API key or a combination of user id, visitor cookie, IP address, etc... with the current minute as a suffix. For example, "u_lokesh1729:04" where the "u_lokesh1729" is the username of the user and "04" is the current minute.</p>
<ol>
<li><p>Get the rate limit of a given cache key.</p>
</li>
<li><p>If the key is not found</p>
<ol>
<li><p>set the key with "T" seconds as TTL</p>
</li>
<li><p>set the value as "X"</p>
</li>
</ol>
</li>
<li><p>If the key is found</p>
<ol>
<li><p>If the limit has been breached, reject the request.</p>
</li>
<li><p>If not, allow the request</p>
</li>
</ol>
</li>
</ol>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> os
<span class="hljs-keyword">import</span> redis

RATE_LIMIT = os.env.get(<span class="hljs-string">"RATE_LIMIT"</span>, <span class="hljs-number">50</span>)

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">rate_limit</span>(<span class="hljs-params">key, rate</span>):</span>
    res = redis.get(key)
    <span class="hljs-keyword">if</span> res <span class="hljs-keyword">is</span> <span class="hljs-keyword">not</span> <span class="hljs-literal">None</span> <span class="hljs-keyword">and</span> res &gt; RATE_LIMIT:
        <span class="hljs-keyword">raise</span> TooManyRequestsException(<span class="hljs-string">"rate limit breached"</span>)
    redis.incr(key)
    redis.expiry(key, <span class="hljs-number">60</span>)
</code></pre>
<h2 id="heading-modified-token-bucket-algorithm">Modified Token Bucket Algorithm</h2>
<p>There is a slightly different approach for the same algorithm. Instead of adding the current minute to the key, we store two cache keys. One is mapping between the API key and the number of tokens. Another is a mapping between the API key and the last filled timestamp of the bucket in the epoch.</p>
<p>An example would be, "u_lokesh1729 -&gt; 100" and "u_lokesh1729 -&gt; 1674378362".</p>
<p>How do we determine the breach?</p>
<ol>
<li><p>Get the count and the created timestamp.</p>
</li>
<li><p>If the count is greater than the limit, reject the request.</p>
</li>
<li><p>Else, find the diff between the current timestamp and the last filled timestamp of the bucket.</p>
</li>
<li><p>If the diff is greater than "T" seconds meaning the last window had already crossed.</p>
<ol>
<li>Reset the rate limit and timestamp. There is no need to set the expiry. These are persistent keys.</li>
</ol>
</li>
<li><p>Else</p>
<ol>
<li>Compute and set the remaining tokens. How to compute? Say, the rate limit is "x" req/minute, and the diff between the bucket timestamp and the current timestamp is "y" seconds. The remaining tokens would be <code>(y/1000) * x</code></li>
</ol>
</li>
</ol>
<h2 id="heading-sliding-window-approach">Sliding Window Approach</h2>
<h3 id="heading-burst-at-edges">Burst at edges</h3>
<p>The downside of the above approach is that it is missing an edge case. The corners of adjacent windows can breach the rate limit but the algorithm won't be able to identify that. Refer to the below picture.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1674557699221/28d4b64c-e754-40c2-8392-f0856d951735.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-no-atomicity">No Atomicity</h3>
<p>Redis provides <code>MULTI</code> the command which wraps multiple redis commands and executes them as a single atomic block. So, all of them succeed or fail not partially. But, if we look at the above approaches, they cannot be fit in an atomic block because there is a business logic (checking the timestamp, tokens, etc...) happening outside. It can be solved with LUA scripting but that would complicate things.</p>
<h3 id="heading-redis-sorted-sets">Redis sorted sets</h3>
<p>Redis provides a data structure called sorted sets. It is nothing but an array of tuples sorted by the score. An example would be</p>
<pre><code class="lang-javascript">{
    <span class="hljs-string">"key"</span>: [
        (<span class="hljs-number">10</span>, <span class="hljs-string">"abcd"</span>),
        (<span class="hljs-number">11</span>, <span class="hljs-string">"def"</span>),
        (<span class="hljs-number">15</span>, <span class="hljs-string">"xyz"</span>)
    ]
}
</code></pre>
<p>The <code>key</code> is the redis key at which the sorted set is stored. The TTL is set at the key level. The first item in the tuple is the score by which the list is stored. The second item in the tuple is the member associated with the score.</p>
<p>So, how do we use sorted sets to implement rate limiting? simple, we will use the epoch value of the timestamp as the score.</p>
<ol>
<li><p>Remove the older entries which pass the current time using <code>ZREMRANGEBYSCORE key -inf &lt;curr_timestamp - 1 minute&gt;</code> .</p>
</li>
<li><p>Add the current timestamp to the set using <code>ZADD key &lt;timestamp&gt; &lt;timestamp&gt;</code> . We use the timestamp both as the score and the member.</p>
</li>
<li><p>Set the expiry of the key to one minute (or T seconds) using <code>EXPIRE key 60</code></p>
</li>
<li><p>Get the count of the current values in the sorted set using <code>ZCARD key</code></p>
</li>
</ol>
<p>Using the count we got above, we can determine whether to allow or reject the request. Also, all the above commands are to be run in a single <code>MULTI</code> command.</p>
<p>What if the application is using Memcached? we can implement the above approach in the application code like this.</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> cache
<span class="hljs-keyword">import</span> time

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">rate_limit</span>(<span class="hljs-params">key, ttl, rate_limit</span>):</span>
    items = cache.get(key, [])
    time = int(time.time())
    <span class="hljs-comment"># delete the items occurred one interval ago</span>
    <span class="hljs-keyword">while</span> items <span class="hljs-keyword">and</span> items[<span class="hljs-number">-1</span>] &lt; time:
        items.pop()
    <span class="hljs-comment"># add the current timestamp</span>
    items.append(time)
    <span class="hljs-keyword">if</span> len(items) &gt; rate_limit:
        <span class="hljs-keyword">raise</span> TooManyRequestsException(<span class="hljs-string">"rate limit breached"</span>)
    <span class="hljs-comment"># store the items with ttl</span>
    cache.set(key, items, ttl)
    <span class="hljs-keyword">return</span> <span class="hljs-literal">True</span>
</code></pre>
]]></content:encoded></item><item><title><![CDATA[Achieving high parallelism with kafka]]></title><description><![CDATA[In this post, we'll discuss consumer groups and how to achieve parallelism using them in Kafka. If you haven't read my previous blog posts about kafka, you…]]></description><link>https://blog.lokesh1729.com/achieving-high-parallelism-with-kafka</link><guid isPermaLink="true">https://blog.lokesh1729.com/achieving-high-parallelism-with-kafka</guid><category><![CDATA[kafka]]></category><category><![CDATA[Apache Kafka]]></category><category><![CDATA[System Architecture]]></category><category><![CDATA[System Design]]></category><category><![CDATA[distributed system]]></category><dc:creator><![CDATA[Lokesh Sanapalli]]></dc:creator><pubDate>Wed, 28 Dec 2022 17:54:33 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1672250023035/ab5c403d-1605-4b91-b661-3d6ae920cd40.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In this post, we'll discuss consumer groups and how to achieve parallelism using them in Kafka. If you haven't read my previous blog posts about kafka, you will find them in the end.</p>
<h2 id="heading-consumer-groups">Consumer Groups</h2>
<p>As the name says, a consumer group is nothing but a group of consumers. Each consumer group is given a name. You can create as many consumer groups as you desire to listen to the same topic. Each consumer group can be at different offsets. That's the beauty of kafka. Here's how the consumer group works.</p>
<ol>
<li><p>When you start a consumer, you give a name to it.</p>
</li>
<li><p>The consumer sends a request to the kafka broker by sending the consumer's name, topic, and partition number.</p>
</li>
<li><p>The kafka broker identifies the consumer by looking at its <code>__consumer_offsets</code> topic and returns the offset.</p>
</li>
<li><p>The consumer gets the offset and sends another request to get the payload and continues with the processing of the message.</p>
</li>
</ol>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1672249817492/a68ba9cf-5cfe-4ad5-820f-077931a996b1.png" alt class="image--center mx-auto" /></p>
<h2 id="heading-relationship-between-consumer-group-and-partitions">Relationship between consumer group and partitions</h2>
<p>There is always either a one-to-one or one-to-many relationship between the consumers in a consumer group and partition. Meaning, one consumer can read one partition or one consumer can read many partitions. But, multiple consumers belonging to a consumer group cannot read the same partition. Can you guess why? It is a design decision taken by the kafka engineering team to implement message delivery guarantee semantics. There are 3 delivery guarantees any message queue system can provide.</p>
<ol>
<li><p>At least once - has the possibility of duplicate events to be consumed/produced</p>
</li>
<li><p>At most once - has the possibility of losing events</p>
</li>
<li><p>Exactly once - the ideal scenario</p>
</li>
</ol>
<p>Assume that kafka allows one partition to be consumed by many consumers in a consumer group. In order to deliver "exactly once" semantics it needs to maintain the state of each message at multiple consumer levels. This becomes convoluted and makes the system complex. To avoid that, the kafka team had taken the decision to restrict one partition to be consumed by only one consumer in a consumer group. This way, the kafka broker needs to maintain a single offset (integer) for a partition.</p>
<h2 id="heading-achieving-high-parallelism">Achieving High Parallelism</h2>
<p>Parallelism is the ability to do multiple tasks at once. High parallelism guarantees high consistency in high throughput systems. Let's take a practical example where parallelism is very important. Consider an aggregator service in an e-commerce system consuming events from different services. If the aggregator service is consuming events at a slower pace, it results in a huge lag in the consumers thus serving inconsistent information to the end-users. So, it is important to have high parallelism in the system to maintain high consistency.</p>
<p>How do we achieve it in kafka? The number of partitions in a kafka topic is directly proportional to the parallelism. Based on the use case, we need to define the number of partitions at the beginning. Though it is possible to modify the partitions later, it takes downtime to do that because kafka needs to rebalance the data among partitions and replicas. Also, it is important not to create too many partitions. We can calculate the partitions required based on the throughput of messages.</p>
<h2 id="heading-additional-read">Additional Read</h2>
<p><a target="_blank" href="https://lokesh1729.com/posts/kafka-internals-learn-kafka-in-depth">https://lokesh1729.com/posts/kafka-internals-learn-kafka-in-depth</a></p>
<p><a target="_blank" href="https://lokesh1729.com/posts/kafka-internals-learn-kafka-in-depth-part-2">https://lokesh1729.com/posts/kafka-internals-learn-kafka-in-depth-part-2</a></p>
]]></content:encoded></item><item><title><![CDATA[Best tools to create software architecture diagrams]]></title><description><![CDATA[There are many tools to create architecture diagrams. In this post, I'll discuss free and paid tools. Some examples are excalidraw, draw.io, lucid.app]]></description><link>https://blog.lokesh1729.com/best-tools-to-create-software-architecture-diagrams</link><guid isPermaLink="true">https://blog.lokesh1729.com/best-tools-to-create-software-architecture-diagrams</guid><category><![CDATA[Collaboration]]></category><category><![CDATA[System Architecture]]></category><category><![CDATA[software architecture]]></category><dc:creator><![CDATA[Lokesh Sanapalli]]></dc:creator><pubDate>Thu, 07 Apr 2022 11:23:51 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1649330595651/Y_amSFlAT.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>As software engineers, our day-to-day work involves creating diagrams to explain the thought process. These diagrams include software architecture, database design &amp; UML diagrams. In this post, I'll discuss different tools available to draw these diagrams.</p>
<h1 id="heading-software-architecture-diagram-tools">Software Architecture Diagram Tools</h1>
<h2 id="heading-excalidraw">Excalidraw</h2>
<p><strong><a target="_blank" href="https://excalidraw.com">excalidraw.com</a></strong> is one of the emerging tools that started as an open-source. The best part of it is we can use it to collaborate with other people easily.</p>
<h3 id="heading-pros">Pros</h3>
<ol>
<li>Open-source</li>
<li>Lot of shapes, tools available and highly customizable</li>
<li>Easily import and export drawings</li>
<li>Lot of libraries available</li>
<li>Able to collaborate with others easily</li>
</ol>
<h3 id="heading-cons">Cons</h3>
<ol>
<li>You need excalidraw+ (paid subscription) to save the drawings in the cloud</li>
<li>To save a diagram, you need to export the <code>.excalidraw</code> file and save it by yourself</li>
</ol>
<h3 id="heading-adding-extra-shapes">Adding extra shapes</h3>
<p>Go to <a target="_blank" href="https://libraries.excalidraw.com">Excalidraw Libraries</a> and just click on "Add to Excalidraw" on any libraries you like.</p>
<p>Here are a few must-have libraries I use.</p>
<p><a target="_blank" href="https://libraries.excalidraw.com/?theme=light&amp;version=2&amp;sort=default#rohanp-system-design">System Design Components</a></p>
<p><a target="_blank" href="https://libraries.excalidraw.com/?theme=light&amp;version=2&amp;sort=downloadsTotal#youritjang-software-architecture">Software Architecture</a></p>
<p><a target="_blank" href="https://libraries.excalidraw.com/?theme=light&amp;version=2&amp;sort=downloadsTotal#drwnio-drwnio">Software Logos</a></p>
<p><a target="_blank" href="https://libraries.excalidraw.com/?theme=light&amp;sort=default#oehrlis-db-eng">Database</a></p>
<p><a target="_blank" href="https://libraries.excalidraw.com/?theme=light&amp;sort=default#cloud-cloud">Cloud Icons</a></p>
<p><a target="_blank" href="https://libraries.excalidraw.com/?theme=light&amp;sort=new#narhari-motivaras-aws-architecture-icons">AWS Icons</a></p>
<p>Once you added them, click on the library icon and start using them (illustrated with the image below)</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1649303339604/lrO2Nlkyn.png" alt="SCR-20220407-cwu.png" /></p>
<h3 id="heading-live-collaboration">Live Collaboration</h3>
<p>Step 1</p>
<p>Click on the library icon to browse</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1649303856971/96ND--fr-.png" alt="SCR-20220407-d45.png" /></p>
<p>Step 2</p>
<p>Drag and drop any icon to start using it</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1649303914580/XUPbAt81C.png" alt="SCR-20220407-d59.png" /></p>
<h2 id="heading-diagramsnet">Diagrams.net</h2>
<p><a target="_blank" href="https://diagrams.net">Diagrams.net</a> (formerly known as <a target="_blank" href="https://draw.io">Draw.io</a>) has a lot of features that many people are unaware of. I used to think it has only very basic shapes, but after I spent some time and explored, found that there are so many shapes available.</p>
<h3 id="heading-pros">Pros</h3>
<ol>
<li>Free to use</li>
<li>Lot of shapes available</li>
<li>Easily connect with google drive and any cloud storage to backup</li>
<li>Collaborate with others (requires google drive or one drive account)</li>
</ol>
<h3 id="heading-cons">Cons</h3>
<p>Nothing as of now</p>
<h3 id="heading-adding-extra-shapes">Adding extra shapes</h3>
<p>Step 1</p>
<p>Click on "More Shapes"</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1649322921106/xI2nn0SQl.png" alt="SCR-20220406-mmk.png" /></p>
<p>Step 2</p>
<p>Browse the shapes and drag-and-drop</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1649322954236/Cu3-PpqaB.png" alt="SCR-20220407-kfw.png" /></p>
<h2 id="heading-lucid">Lucid</h2>
<p><a target="_blank" href="https://lucid.app">Lucid.app</a> is an ecosystem of multiple applications such as lucid chart and lucid spark for visual communication. They aimed at enterprises with paid plans, but they also have a freemium model with limited features. You can see their pricing <a target="_blank" href="https://lucid.app/user/165903926#/subscriptionLevel/chart/levelType">here</a></p>
<h3 id="heading-pros">Pros</h3>
<ol>
<li>Lot of shapes and tools available</li>
<li>Ease of diagramming</li>
</ol>
<h3 id="heading-cons">Cons</h3>
<ol>
<li>Not free, most of the features require paid subscription</li>
</ol>
<h3 id="heading-adding-extra-shapes">Adding extra shapes</h3>
<p>Step 1</p>
<p>After logging in, create a new Lucidchart document</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1649323788715/v0yi4kaP-.png" alt="SCR-20220407-ks4.png" /></p>
<p>Step 2</p>
<p>Search for a shape and add it to the diagram</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1649329590413/j2Q9Eoy26.png" alt="SCR-20220407-ku8.png" /></p>
<h2 id="heading-diagrams-as-a-code">Diagrams as a code</h2>
<p>If you like to represent diagrams using code, then there are tools like <a target="_blank" href="https://diagrams.mingrammer.com/">Mingrammer</a>.</p>
<h3 id="heading-pros">Pros</h3>
<ol>
<li>Huge availability of tools including on-premise, AWS etc...</li>
<li>Easily draw diagrams</li>
<li>Open-source</li>
</ol>
<h3 id="heading-cons">Cons</h3>
<ol>
<li>Learing curve</li>
<li>Supports only <code>python3</code></li>
</ol>
<p>There are some examples given here - <a target="_blank" href="https://diagrams.mingrammer.com/docs/getting-started/examples">https://diagrams.mingrammer.com/docs/getting-started/examples</a></p>
]]></content:encoded></item><item><title><![CDATA[A complete introduction to Kafka]]></title><description><![CDATA[As part of the Kafka internals series, in this post, I'll be writing a brief introduction to Kafka fundamentals, common jargon and basic architecture.]]></description><link>https://blog.lokesh1729.com/a-complete-introduction-to-kafka</link><guid isPermaLink="true">https://blog.lokesh1729.com/a-complete-introduction-to-kafka</guid><category><![CDATA[kafka]]></category><category><![CDATA[distributed system]]></category><category><![CDATA[message queue]]></category><dc:creator><![CDATA[Lokesh Sanapalli]]></dc:creator><pubDate>Sun, 20 Feb 2022 06:52:58 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1645339786948/6BI3Wcgbj.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-introduction">Introduction</h2>
<p><a target="_blank" href="https://kafka.apache.org">Kafka</a> had gained huge popularity for the past few years. In a microservices architecture, it plays a pivotal role. It enables data to move from one service to another. I'm starting this series to help beginners understand Kafka in-depth. But, before we go in-depth, it is important to understand some basics. So, in this post, we'll learn the basics and eventually, we'll go in-depth.</p>
<h2 id="heading-basics">Basics</h2>
<p>"Kafka is a highly scalable, durable, fault-tolerant and distributed streaming platform." This is the definition we see from Kafka's official website. These jargons may frighten the newcomers. Let's learn the meaning of these first.</p>
<p><strong>highly scalable</strong>: If the incoming messages of your Kafka are increasing, you can scale your system by adding more brokers to the cluster. You can scale it horizontally by adding more machines or vertically by adding more disk space.</p>
<p><strong>durable</strong>: Durability is the ability to last longer. The messages sent to Kafka topic are persisted in the disk. They will not be deleted unless you configure them to delete.</p>
<p><strong>fault-tolerant</strong>: First of all, fault-tolerant means the ability of the system to operate when one or more nodes are failed. In a Kafka cluster, even if a broker is down, the system still operates because of the replication. We'll learn about this in further posts.</p>
<p><strong>distributed streaming platform</strong>: A stream is a continuous flow. In Kafka, producers will produce messages and consumers will consume. This stream never stops. That's why we call Kafka a streaming platform.</p>
<p>  In a nutshell, Kafka works on the traditional client-server architecture. The server is Kafka, the producer (the one who sends data) and the consumer (the one who receives data) are the clients. The communication between client and server happens via <a target="_blank" href="https://kafka.apache.org/protocol.html">customized high-performance TCP protocol</a> implemented by the Kafka team. There are many <a target="_blank" href="https://cwiki.apache.org/confluence/display/KAFKA/Clients">client libraries</a> available for most programming languages.</p>
<h3 id="heading-events">Events</h3>
<p>An event describes something that happened. For example, in an e-commerce system, examples of events can be "an order is created", "an item is added to cart", "an order is delivered". In Kafka, we read or write data in form of events. An example of <code>ORDER_CREATED</code> event data looks like this. We can send this data in XML, JSON or Avro.</p>
<pre><code class="lang-JSON">{
  <span class="hljs-attr">"order_id"</span>: <span class="hljs-string">"abcd-1234"</span>,
  <span class="hljs-attr">"order_amount"</span>: <span class="hljs-string">"50.00"</span>,
  <span class="hljs-attr">"created_by"</span>: <span class="hljs-string">"lokesh"</span>,
  <span class="hljs-attr">"created_on"</span>: <span class="hljs-string">"2022-02-09T22:02:00Z"</span>
}
</code></pre>
<h3 id="heading-basic-architecture">Basic Architecture</h3>
<p>A producer is an entity that "sends" the data to Kafka. A consumer is an entity that "consumes" the data from Kafka. In Kafka, both these entities are loosely coupled. It means, the producer just produces irrespective of the consumer's existence. Similarly, the consumer's responsibility is to consume data from Kafka without depending on producers.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1645255657787/cI3Q3Yp70.png" alt="kafka flow.png" /></p>
<h3 id="heading-topics-andamp-partitions">Topics &amp; Partitions</h3>
<p>Events are categorized into topics. A topic contains related information. When designing data pipelines, topics are created based on semantics. Every topic has a meaning and purpose. For example, "payments" is a topic where payment-related events are received. Each topic is divided into multiple partitions. The topic is a logical entity in Kafka which means it doesn't exist physically whereas partitions do. When you create a topic with 'n' partitions, here's what happens under the hood.</p>
<ol>
<li>Kafka creates 'n' number of folders with names <code>topic-1</code>, <code>topic-2</code>... <code>topic-n</code>.</li>
<li>In each folder, there will be files where the events are stored.</li>
</ol>
<p>We'll go to the internal in coming posts. Now, coming to partitions, it is the smallest storage unit and an append-only data structure where the events are appended to the end. Partitions allow users to get parallelism. More the number of partitions, the higher the parallelism.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1646473365326/aZq4c1eYF.png" alt="kafka topic partition.png" /></p>
<h3 id="heading-partition-key">Partition Key</h3>
<p>When the producers send messages to the Kafka broker, in which partition they will go? Well, if no partition key was sent, they'll go to a random partition. What is a partition key? it is an optional parameter when sent, Kafka makes sure that the messages with the same partition key are written into the same partition. Let's Illustrate it with the below image. Messages with partition key "lokesh, john &amp; kate" are sent to <code>partition 1</code>. Same with the other keys. Under the hood, Kafka computes the hash of the partition key and applies modulo with the total partitions to get the partition. Partition key solves some use-cases where you need to aggregate messages based on the partition key.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1646473910895/KFJQXXsuQ.png" alt="partition_key.png" /></p>
<h3 id="heading-how-do-consumers-work">How do consumers work?</h3>
<p>When you start a consumer, here's what happens.</p>
<ol>
<li>We specify Kafka bootstrap URL (or zookeeper URL when provided Kafka brokers will be discovered automatically) to the consumer.</li>
<li>The consumer opens a TCP connection with the broker and registers itself.</li>
<li>The consumer asks the broker where it was and the broker returns the offset. The Kafka broker maintains consumer offsets in a separate topic called <code>__consumer_offsets</code>.</li>
<li>The consumer keeps on polling continuously and starts consuming messages from the offset.</li>
<li>The consumer completes the work and commits the offset back to the broker.</li>
<li>The consumer moves to the next message and the process continues.</li>
</ol>
<p>If your consumer takes more time to process each message, then you can change the configuration <a target="_blank" href="https://kafka.apache.org/documentation/#consumerconfigs_max.poll.interval.ms">max.poll.interval.ms</a> to a higher value. By default, it is set to 5 minutes. You can also tune <a target="_blank" href="https://kafka.apache.org/documentation/#consumerconfigs_max.poll.records">max.poll.records</a> which specifies the maximum records the consumer can fetch in a single poll call.</p>
<h4 id="heading-offset">Offset</h4>
<p>In computer science, the definition of offset from Wikipedia is as below. It's the same in the context of Kafka. It tells the message position.</p>
<blockquote>
<p>Offset is an integer indicating the distance (displacement) between the beginning of the object and a given element or point, presumably within the same object.</p>
</blockquote>
<h3 id="heading-consumer-groups">Consumer Groups</h3>
<p>As the name says, a consumer group is nothing but a group of consumers. Each consumer group is given a name. You can have as many consumer groups as you want. When you start a consumer group, it'll be registered with the Kafka broker which means all the consumers in that group will also be registered.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1646499772784/ZP0N4jVFH.png" alt="kafka consumers.png" /></p>
<h3 id="heading-comparision-with-traditional-pub-sub-systems">Comparision with traditional pub-sub systems.</h3>
<p>Also, If you are familiar with traditional pub-sub messaging systems like rabbitmq, you may find a few differences.</p>
<ol>
<li><p>The messages are deleted from rabbitmq once consumed. But, in Kafka, they are not deleted. They are persisted in the disk. This characteristic enables Kafka to act as a streaming platform.</p>
</li>
<li><p>In pub-sub systems, you cannot have multiple services to consume the same data because the messages are deleted after being consumed by one consumer. Whereas in Kafka, you can have multiple services to consume. This opens the door to a lot of opportunities such as <a target="_blank" href="https://kafka.apache.org/documentation/streams/">Kafka streams</a>, <a target="_blank" href="https://kafka.apache.org/documentation/#connect">Kafka connect</a>. We'll discuss these at the end of the series.</p>
</li>
</ol>
<p>You can read more about the differences <a target="_blank" href="https://blog.cloudera.com/scalability-of-kafka-messaging-using-consumer-groups/?utm_source=pocket_mylist">here</a></p>
]]></content:encoded></item><item><title><![CDATA[Learn anything with question-based learning technique]]></title><description><![CDATA[As software engineers, We are knowledge workers. We build software and learn so many things. Learning shouldn't stop for us. There are so many technologies]]></description><link>https://blog.lokesh1729.com/learn-anything-with-question-based-learning-technique</link><guid isPermaLink="true">https://blog.lokesh1729.com/learn-anything-with-question-based-learning-technique</guid><category><![CDATA[learning]]></category><category><![CDATA[software development]]></category><dc:creator><![CDATA[Lokesh Sanapalli]]></dc:creator><pubDate>Mon, 07 Feb 2022 19:39:06 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1644262682188/JT9rf41eo.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-introduction">Introduction</h2>
<p>As software engineers, We are knowledge workers. We build software and learn so many things. Learning shouldn't stop for us. There are so many technologies and solutions that exist today. Sometimes, learning a new "thing" can be overwhelming and stressful. At least, I sometimes feel it. In this post, I will talk about a practical learning method I used and succeeded in.</p>
<h2 id="heading-what-is-question-based-learning">What is question-based learning</h2>
<p>Say, for example, your team wants to use "Kafka" for event streaming. But, you are not familiar with it. The first thing you do is google for some resources. You find a lot of content but don't know where to start and how much content is sufficient. You feel overwhelmed to see the huge resources and procrastinate to start. Sometimes, we blindly read through all the resources and still feel like not learned anything. I used to feel like this. When we think practically, we don't need to learn everything. We need to scope the learning to the extent of what is needed. To figure out a sufficient portion of the topic, we need to come up with some questions. These questions tell you that you don't need to overwhelm or stress yourself, you just need to figure out the answers to those questions. So, it's more like a hunting game. You have questions, now you are searching for answers. It's more fun now!</p>
<p>Let's come back to our example. These are the questions that are needed when getting started with Kafka.</p>
<ol>
<li>What is Kafka?</li>
<li>What problem is it solving?</li>
<li>What are the basic principles, common terms?</li>
<li>What are the use-cases?</li>
<li>How does it fit into our use case?</li>
</ol>
<p>These questions are enough when we are getting started. Let's say, we started implementing the project. Now, we need to go in-depth. Then, we can frame questions like this</p>
<ol>
<li>How partitions are stored in the disk?</li>
<li>What are offsets?</li>
<li>What are consumer groups?</li>
<li>Can a consumer in a consumer group subscribe to multiple partitions?</li>
<li>Can a partition be subscribed to by multiple consumers?</li>
</ol>
<p>In a nutshell, the idea is not to go in-depth at the beginning. Learn only what is required. Believe me! this method had changed my way of learning a lot. It is pragmatic, intuitive and powerful. With this method, I feel confident about what I learned because it's like a hunting game. I hunt for answers to my questions.</p>
<p>If you liked this post, show your appreciation through the emojis and follow me for more content on software engineering.</p>
<p>Thanks for reading :)</p>
]]></content:encoded></item><item><title><![CDATA[Resources for cracking your system design interview]]></title><description><![CDATA[Let's crack your system design interview]]></description><link>https://blog.lokesh1729.com/resources-for-cracking-your-system-design-interview</link><guid isPermaLink="true">https://blog.lokesh1729.com/resources-for-cracking-your-system-design-interview</guid><category><![CDATA[System Architecture]]></category><category><![CDATA[Technical interview]]></category><category><![CDATA[interview]]></category><category><![CDATA[Interviews]]></category><category><![CDATA[distributed system]]></category><dc:creator><![CDATA[Lokesh Sanapalli]]></dc:creator><pubDate>Wed, 05 Jan 2022 07:53:59 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1641369204519/uivyIeCeS.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Hey there,</p>
<p>In this blog post, I'll provide the resources required for cracking system design interviews. Over the past year, I have given many interviews. There were a lot of resources present on the internet. But, not all of them work for everyone. Based on my experience, I am sharing these resources which worked well for me.</p>
<h2 id="heading-free-resources">Free Resources</h2>
<p><a target="_blank" href="https://github.com/donnemartin/system-design-primer">System Design Primer</a> - A bible for system design. A big thanks to <a target="_blank" href="https://donnemartin.com/">Donne Martin</a> for his contributions. I have gone through this to get my basics refreshed and correct some of the concepts. </p>
<p><a target="_blank" href="https://github.com/binhnguyennus/awesome-scalability">Awesome Scalability</a> - An underrated resource. It contains links to all the basics and different use-cases. I read a few articles per week from this list.</p>
<p><a target="_blank" href="https://www.hiredintech.com/courses/system-design">Hiredintech</a> - This course has some good basics.</p>
<p><a target="_blank" href="https://tianpan.co/notes/2016-02-13-crack-the-system-design-interview">Tianpan</a> - This blog has short and concise designs. I had gone through this in the end.</p>
<p><a target="_blank" href="https://github.com/prasadgujar/low-level-design-primer">Low-level design</a> - This has a good collection of low-level designs.</p>
<p>There are youtube channels about system design, but I found none of them gone through much into depth. If you like learning from videos, you can refer below.</p>
<p><a target="_blank" href="https://www.youtube.com/channel/UCn1XnDWhsLS5URXTi5wtFTA">Techdummies</a></p>
<p><a target="_blank" href="https://www.youtube.com/c/codeKarle/videos">Codekarle</a></p>
<h2 id="heading-paid-resources">Paid Resources</h2>
<p><a target="_blank" href="https://www.educative.io/courses/grokking-the-system-design-interview">Grokking System Design Interview</a> - This is a very famous course about system design. I purchased and gone through. But, honestly, I don't find it has much depth. It was all very basic and naive I felt.</p>
<p><a target="_blank" href="https://get.interviewready.io">Interviewready</a> - This course is from Gaurav Sen. He is famous on youtube for system design content. I haven't purchased this. But, I heard good reviews from people.</p>
<p>That's all folks</p>
]]></content:encoded></item></channel></rss>