<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Vishal Kumar on Medium]]></title>
        <description><![CDATA[Stories by Vishal Kumar on Medium]]></description>
        <link>https://medium.com/@vishalcjha?source=rss-7ec72335d485------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*6muqxEPWk4a8mCL0.</url>
            <title>Stories by Vishal Kumar on Medium</title>
            <link>https://medium.com/@vishalcjha?source=rss-7ec72335d485------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 02:38:22 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@vishalcjha/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Discover PI — Deep learning]]></title>
            <link>https://vishalcjha.medium.com/discover-pi-deep-learning-da95d7ad6497?source=rss-7ec72335d485------2</link>
            <guid isPermaLink="false">https://medium.com/p/da95d7ad6497</guid>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Vishal Kumar]]></dc:creator>
            <pubDate>Sun, 16 Nov 2025 23:00:27 GMT</pubDate>
            <atom:updated>2025-11-16T23:00:27.577Z</atom:updated>
            <content:encoded><![CDATA[<h3>Discover PI — Deep learning</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_TgZEtW5xJLMN8_m" /><figcaption>Photo by <a href="https://unsplash.com/@morganbea?utm_source=medium&amp;utm_medium=referral">Morgan Bea</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>PI is bedrock of mathematics, but what if we have reached here without PI. In this small blog, I will discover PI using deep learning. My hope is to open mystery around deep learning, while keeping it simple and easy to execute. For anyone who want to try it out, without reading any further, link to <a href="https://colab.research.google.com/drive/1UGpOLQbDSQmSrpxlIm9aZCeO3Kl6QnDv#scrollTo=vOzjWfctrn2V">Google Colab</a>.</p><p>At its core, deep learning is a mathematical function that maps input to output. The reason for its popularity is its ability to solve, or better say approximate, solutions without requiring us to come up with an explanatory model for a given input and output. This makes these models universal, which sacrifices correctness for simplicity.</p><p>Pytorch is one of popular deep learning libraries. Wiht out going in details here are few key concepts to be aware of .</p><ul><li>Tensor — a multidimensional data structure. This can also be thought of as a multidimensional matrix.</li><li>Model — a mathematical function with parameters(also referred as weight and biases).</li><li>Prediction / inference — using a trained model to predict output.</li><li>Parameters — weights and biases that a model learns. During model training these are updated and thus also called learnable parameters.</li><li>Gradient — a vector containing partial derivatives of a function with respect to its parameters.</li><li>Loss function — a function that calculates the distance between prediction and reality. Examples include Root Mean Square Error.</li><li>Epochs — individual iterations in model training that update parameters to minimize the loss function.</li><li>Training loop — running epoch multiple time.</li><li>Hyperparameter — values that control how training is done. They are not part of model itself, but control model execution.</li><li>Learning rate — a critical example of hyper-parameter, which controls rate of change in parameter value with each epoch. A small learning rate makes learning slow, but a high learning rate changes parameters drastically, making it impossible to find the best values.</li><li>Normalization — tensors are usually expressed in floating values. Each epoch involves lots of matrix multiplication, which can cause values to grow very large. To minimize this, tensors are normalized so that they sum to 1.</li></ul><p><strong>Discovering PI</strong></p><p>This example is highly motivated by finding relationship between celcius and fahrenheit example in book <a href="https://www.manning.com/books/deep-learning-with-pytorch">Deeplearning with Pytorch</a>.</p><p>PI appears in many phenomena, but area of circle is most familiar example of it. Suppose we have a set of radii and corresponding areas. PI has not been invented yet — -can we use deep learning to calculate PI? We will start by picking different mathematical functions with different degrees and iterate through our values of radii. In the beginning, we will give PI a value of 1 and then update this by comparing predicted values to actual values. Remember, PI is our learning parameter, which is updated during each epoch. Once we have a loss value under an acceptable range, we can stop.</p><h3>Two phases of learning</h3><ul><li>Forward — during this phase the model moves forward from one layer to another applying different mathematical functions. In our example we have just one layer. Here calculation flows from input toward prediction. In our example this is the t_p = model(ip_radii, *params) part of the training loop. Here getting area using model in forward part of training loop.</li><li>Backward — learning parameters are updated using gradients. Here calculation flows from prediction toward input. This approach allows the use of the chain rule to find derivatives. Pytorch tensors with (requires_grad = True) do this backward propagation. If not present, one will have to manually do derivative. In our example note params = torch.tensor([1., 0.], requires_grad = True). Also, backward calculation is done by loss.backward(). Here update of learning parameter, or value of PI, is backward part of training loop.</li></ul><p>I can not overstate liberties I have taken to explain deep learning. But following are some obvious ones.</p><ul><li>Though we do not have a defined value for PI, we will be using it to make our sample data.</li><li>In actual learning processes, data is divided into 3 parts: training, validation, and test. In our example we will train on the complete dataset.</li></ul><p><strong>Code Snippet </strong>— Better idea would be to go to <a href="https://colab.research.google.com/drive/1UGpOLQbDSQmSrpxlIm9aZCeO3Kl6QnDv#scrollTo=ANT3Lc-CrX0D">Google Colab</a> and skip rest of post. But if for some reason you can not I paste snippets of code from colab.</p><p>Loss function:</p><pre># How far prediction is from actual value. There are many ways to calcualte this, one of simple being square mean difference.<br>def loss_fn(t_p, t_c):<br>    sq_diff = (t_p - t_c) ** 2<br>    return sq_diff.mean()</pre><p>Training Loop</p><pre>## Model trainig is looping though same set of data over and over again,<br>## till we have acceptable loss value.<br><br>## During each iteration, learning parameter, or parameters are updated.<br>## One hopes to see loss going down overtime.<br>def training_loop(n_epochs, model, show_loss, learning_rate, params, ip_radii, unknowns):<br>    for epoch in range(1, n_epochs + 1):<br>        ## Gradient accumulates. So clear them if they are there.<br>        if params.grad is not None:<br>            params.grad.zero_()<br><br>        ## Call the model to get prdicated value. This is the forward pass of training loop.<br>        t_p = model(ip_radii, *params)<br>        ## Calculate loss<br>        loss = loss_fn(t_p, unknowns)<br>        if (epoch % 100 == 0) and show_loss:<br>            print(loss)<br>        ## Find the gradient. This is backward pass of training loop, where calculation goes from final result loss,<br>        ## towards input. This uses chain rule to find derivite of loss over parameters.<br>        loss.backward()<br><br>        ## Update parameters. Here we do not want to accumulate gradient, so no_grad<br>        with torch.no_grad():<br>            params -= learning_rate * params.grad<br><br>    return (params, loss)</pre><p>Hyperparameters</p><pre>## Some parameters for model running. These are referred as hyper parameters.<br><br>## How fast to change parameter. A small value makes model takes long time and a high values makes model jump past optimal solution.<br>learning_rate = 1e-2<br>## How many time to run training loop<br>n_epochs = 1000<br>## Learning parameters. Look at requires_grad True. Otherwise backward traversal will not give any values.<br>params = torch.tensor([1., 0.], requires_grad = True)<br><br>## Input radiia<br>ip_radii = torch.randn(100)<br>## Here we know the anwser or label. This makes is supervised learning.<br>unknowns = torch.pi * (ip_radii ** 2)</pre><p>First try — When we run our training loop for 1000 iterations (completely random choice), we find the loss value is not changing. This indicates our model cannot fit the relationship between input and output. As we are using a linear model, which is simple, it is not able to capture the relationship.</p><pre># A simple function.<br>def linear_model(t_u, w, b):<br>    return w * t_u + b<br>prams, loss = training_loop(n_epochs, linear_model, True, learning_rate, params, ip_radii, unknowns)<br><br>## As function is too simple for this phenomena, it is not able to capture relationship b/w input and output<br>print(f&quot;Parameter : {params}, Loss :{loss}&quot;)<br>print(f&quot;pi is {params[0]}&quot;)<br><br><br>&quot;&quot;&quot;<br>tensor(16.825, grad_fn=&lt;MeanBackward0&gt;)<br>tensor(16.580, grad_fn=&lt;MeanBackward0&gt;)<br>tensor(16.574, grad_fn=&lt;MeanBackward0&gt;)<br>tensor(16.574, grad_fn=&lt;MeanBackward0&gt;)<br>tensor(16.574, grad_fn=&lt;MeanBackward0&gt;)<br>tensor(16.574, grad_fn=&lt;MeanBackward0&gt;)<br>tensor(16.574, grad_fn=&lt;MeanBackward0&gt;)<br>tensor(16.574, grad_fn=&lt;MeanBackward0&gt;)<br>tensor(16.574, grad_fn=&lt;MeanBackward0&gt;)<br>tensor(16.574, grad_fn=&lt;MeanBackward0&gt;)<br>Parameter : tensor([-0.216,  3.140], requires_grad=True), Loss :16.57428550720215<br>pi is -0.21552997827529907<br>&quot;&quot;&quot;<br></pre><p>Second Try — How about making our model a bit more complex and hope it finds the relationship better? Now when we run this learning loop, we discover the loss value drops near zero. Though in this case 1000 was a high number of epochs, our returned parameter is tensor([3.142, 0.000]). The first part of the parameter is 3.141589879989624, which is quite accurate. Practical Deeplearning involves finding balance between model complexity and accuracy. Complex model tend to take long time but simple ones fails to find deep relationship and thus has higher loss value.</p><pre># A bit complex function. Complex function usually capture relationship better, but they also tend to take long time to run.<br># Thought I am calling below complex, it is still very simple. Also these model have sinle layer.<br>def quadratic_model(t_u, w, b):<br>    return w * (t_u ** 2) + b<br>prams, loss =  training_loop(n_epochs, quadratic_model, True, learning_rate, params, ip_radii, unknowns)<br><br># We see loss goes to zero after 400 training loop. We could have terminated early.<br>print(f&quot;Parameter : {params}, Loss :{loss}&quot;)<br><br>## With loss almost zero, we have discovered PI.<br>print(f&quot;pi is {params[0]}&quot;)<br><br>&quot;&quot;&quot;<br>tensor(1.150, grad_fn=&lt;MeanBackward0&gt;)<br>tensor(0.132, grad_fn=&lt;MeanBackward0&gt;)<br>tensor(0.015, grad_fn=&lt;MeanBackward0&gt;)<br>tensor(0.002, grad_fn=&lt;MeanBackward0&gt;)<br>tensor(0.000, grad_fn=&lt;MeanBackward0&gt;)<br>tensor(    0.000, grad_fn=&lt;MeanBackward0&gt;)<br>tensor(    0.000, grad_fn=&lt;MeanBackward0&gt;)<br>tensor(    0.000, grad_fn=&lt;MeanBackward0&gt;)<br>tensor(    0.000, grad_fn=&lt;MeanBackward0&gt;)<br>tensor(    0.000, grad_fn=&lt;MeanBackward0&gt;)<br>Parameter : tensor([    3.142,     0.000], requires_grad=True), Loss :4.177709733710344e-09<br>pi is 3.1415557861328125<br>&quot;&quot;&quot;<br></pre><h3>Conclusion</h3><p>Deeplearning relies on training on a large dataset. One begins with a random estimate of parameters that get updated during each epoch. In the real world, one does not try different methods as we did in our example. There are sets of mathematical learning functions that capture the essence of different phenomena. The hard part is having data and the ability to run training loops. And for sure, I am simplifying this to a very basic level, but my hope is to make it easy to understand for myself and others.</p><p>I highly encourage you to run <a href="https://colab.research.google.com/drive/1UGpOLQbDSQmSrpxlIm9aZCeO3Kl6QnDv#scrollTo=vOzjWfctrn2V">Google Colab</a>. It takes less than a minute of your time.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=da95d7ad6497" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Database in Rust — Part I]]></title>
            <link>https://vishalcjha.medium.com/building-database-in-rust-part-i-1c25945446c2?source=rss-7ec72335d485------2</link>
            <guid isPermaLink="false">https://medium.com/p/1c25945446c2</guid>
            <category><![CDATA[database-internals]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[learning]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[Vishal Kumar]]></dc:creator>
            <pubDate>Thu, 26 Dec 2024 02:42:19 GMT</pubDate>
            <atom:updated>2024-12-26T02:42:19.214Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building Database in Rust — Part I</h3><p>I’ve always been curious about the inner workings of a database. Recently, I stumbled upon the CMU Database course, which uses Bustub — a database system written in C++ — for hands-on learning. Inspired by this, I’ve started to reimplement Bustub in Rust, filling in the gaps by completing the course’s assignments, in Rust. Through this blog series, I hope to share my journey and insights. Post will switch between database internal, Rust code and explanation. <strong>WIP Code can be found at </strong><a href="https://github.com/vishalcjha/abustub-rs"><strong><em>abustus-rs</em></strong></a>.</p><h3>The Anatomy of a Database System</h3><p>A disk based relational database system can be divided into the following layers(bottom up):</p><ol><li><strong>Disk Manger</strong></li><li><strong>Buffer Pool Manager</strong></li><li><strong>Access Method</strong></li><li><strong>Operator Execution</strong></li><li><strong>Query Planning</strong></li></ol><p>We will be building database in bottom up manner. We will outline role of each layer, look at how Rust feature can be used. This post covers the concepts of <strong>Disk Scheduler</strong>, <strong>LRU-K cache eviction</strong> and the <strong>Buffer Pool Manager (BPM)</strong>.</p><h3>Disk Scheduler</h3><p>Modern databases uses diverse storage strategies. Some, like Redis, are entirely in-memory; others use disk storage; and others like ClickHouse uses cloud-based storage. For this series, we’ll stick to a disk baed storage.</p><p>The lowest layer of database is responsible for reading and writing data from persistent storage. Access to this layer is page aware (more on page later). It is not aware of what is stored in these pages.</p><p>We can start with following definition for read and write</p><pre>type PageId = usize;<br>trait PageAccessor {<br>   // Wite data_buf to storage loaction of page_id<br>   fn write_page(&amp;mut self, page_id: PageId, data_buf: Box&lt;[u8; PAGE_SIZE]) -&gt; io::Result&lt;()&gt;;<br>   // Readfrom storage location of page_id to data buffer.<br>   fn read_page(&amp;mut self, page_id: PageId, data_buf: Box&lt;[u8; PAGE_SIZE]) -&gt; io::Result&lt;()&gt;;<br>}</pre><p>Functionality of these methods are given in their names. However, let’s talk about Rust side of this. We use <em>trait </em>which is akin to interface in other language. This provides opportunity to have multiple implementation for set of functionality, say a db where things are in memory, or in disk or cloud storage.</p><p>We also see <em>Result</em>, which represent given method can succeed or fail. Rust uses algebraic types aka <em>enum </em>to represent different possible state for a value. <em>Result</em> has two state, <em>Ok</em> and <em>Err</em>. Result will be <em>Ok</em> if operation is successful and <em>Err</em> if failure occurs.</p><p>There is usually a think layer on top, called <strong>DiskScheduler</strong>. This is responsible to call above calls for read and write. This layer is what BufferPool Manager interacts with. In Bustub this has been implemented as a background thread which use <a href="https://docs.rs/tokio/latest/tokio/sync/oneshot/fn.channel.html"><em>channel</em></a> to communicate task completion. One can use them in blocking or non blocking manner.</p><h3>The Role of the Operating System and Database Memory Management</h3><p>A database system runs on top of a general-purpose operating system (OS). However, generality of OS often clashes with the specific needs of databases, especially in performance-critical areas. For example, operating systems provide abstractions like virtual memory, which create the illusion of unlimited memory.</p><p>While useful, relying on OS-level virtual memory management would mean relinquishing control over critical aspects like eviction policies, prioritizing pages, and minimizing cache misses. To address these challenges, databases implement their own memory management through a component called the <strong>Buffer Pool Manager (BPM)</strong>.</p><p>The BPM handles the task of managing memory within the database system, ensuring data from disk is efficiently cached in memory. As with any limited resource, caching introduces the need for eviction. Among various cache eviction policies, the CMU course emphasizes <strong>LRU-K</strong>. This post will delve into how this policy is implemented within a database system.</p><h3>Frames and Pages: Understanding Eviction</h3><p>Before diving into eviction policies, let’s clarify two key terms: <strong>Frames</strong> and <strong>Pages</strong>.</p><p>A <strong>Page</strong> is a fixed-size region of disk storage where the database stores its data, for long term persistence. Choosing the right page size is part science, part art; for this project, we’ll pick size of <strong>4 KB</strong>. The <strong>Buffer Pool Manager (BPM)</strong>, which handles data in memory, also divides memory into fixed-size regions called <strong>Frames</strong>. When a page is loaded into memory, the BPM assigns it to an available frame.</p><p>If there are no free frames available in the free pool, the BPM needs to evict a page which is mapped to a frame to make room for a new one. This is where <strong>eviction algorithms</strong> come into play. Common algorithms include:</p><ul><li><strong>First-In-First-Out (FIFO):</strong> Evicts the oldest frame first.</li><li><strong>Most-Recently-Used (MRU):</strong> Evicts the most recently accessed frame.</li><li><strong>Least-Recently-Used (LRU):</strong> Evicts the least recently accessed frame.</li></ul><p>While LRU is generally a good choice, it has a notable drawback: it focuses solely on recent access patterns without considering the broader history. For instance, during a sequential scan, the database might touch many pages that it won’t revisit anytime soon. In contrast, an <strong>index page</strong>, which hasn’t been accessed recently, is much more likely to be reused.</p><p>To address this limitation, <strong>LRU-K</strong> improves upon LRU by keeping track of the last <strong>K accesses</strong> for each entry. If an entry doesn’t yet have <strong>K recorded accesses</strong>, the missing entries are treated as infinitely old. This makes such entries more likely to be evicted, ensuring that more critical pages remain in memory.</p><p>Main operations can be defined by</p><pre>pub type FrameId = usize;<br>///records frame is accessed.<br>pub fn record_access(&amp;self, frame_id: FrameId);<br>///If holds frame, change the evictable flag as requested.<br>pub fn set_evictable(&amp;self, frame_id: FrameId, is_evictable: bool);<br>///Returns a frame that is evicted from cache.<br>///If none exists, None is returned.<br>pub fn evict(&amp;self) -&gt; Option&lt;FrameId&gt;;</pre><h4>How not be do billion dollar blunder</h4><p>Let’s look a evict()method in the <strong>LRU-K</strong> cache which returns an Option type. Option is Rust’s way of indicating that a method might or might not return a value. In this case, it signifies that the method might not succeed to find a frame_id to evict, returning None in such scenarios. In many languages Null value is returned, which results in runtime error and reffered as billion dollar blunder.</p><h4>Internal Mutability in Rust</h4><p>All the methods in the LRU-K cache operate on a shared reference (&amp;self), yet they modify the internal state of the cache. This behavior is a hallmark of <strong>internal mutability</strong>, a design pattern in Rust that allows changes to be made through a shared reference.</p><p>Internal mutability is typically achieved in concurrent Rust using types like Arc (Atomic Reference Counting) combined with synchronization primitives such as Mutex. This ensures that the shared state remains thread-safe while allowing modifications.</p><p>In the context of the LRU-K cache, the underlying data structure might look something like this</p><pre>type History = Vec&lt;Timestamp&gt;; <br>// for my implementation i used elapsed time since cache initialization.<br>cache: Arc&lt;Mutex&lt;HashMap&lt;FrameId, History&gt;&gt;&gt;</pre><h3>Buffer Pool Manager</h3><p>The task of the Buffer Pool Manager (BPM) is straightforward: maintain a pool of memory frames ready to store pages from disk as frame. When a database operation (eg a query or transaction) brings in page as frame, it either reads and/or writes the frame. For read operations, since they don’t modify the data, multiple operations can safely access the frame concurrently. However, for write operations, the BPM must ensure exclusivity to avoid conflicts or data inconsistencies.</p><p>There are many ways to achieve shared vs exclusive access in Rust. I though of many but tried following 4.</p><p>Try 1</p><p>Return a ref type aka &amp; — issue is once you have this, lifetime comes into play. Which leads to some tough battle when concurrency is involved.</p><p>Battle become more challenging for mutable ref type ask &amp;mut.</p><pre>const PAGE_SIZE : usize = 4096;<br>struct FrameData {<br>   buffer: Box&lt;[u8; PAGE_SIZE]&gt;<br>}<br>frame_holder : Arc&lt;Mutex&lt;Vec&lt;FrameData&gt;&gt;&gt;;<br>fn read_page(&amp;self, page_id: PageId) -&gt; &amp;[u8; PAGE_SIZE];<br>fn write_page(&amp;self, page_id: PageId) -&gt; &amp;mut[u8; PAGE_SIZE];<br>// for both methods, what is lifetime of returned buffer.<br>// In concurrent env, value need to corss thread boundary and thus must have<br>// &#39;static lifetime. &#39;static is Rust way of saying, a memory must exits till<br>// Rust needs it to. This way Rust overcomes issue of referring to dropped<br>// memory region.</pre><p>Try 2</p><p>In original CMU db, with C++, shared_mutex is used. Following best practices of resource allocation, RAII guard is used, which relinquishes the lock once the variable goes out of scope.</p><p>In Rust it is not quite possible for concurrent scenario. For a value to move around a thread, it must be of <em>Send</em> type. But the guard returned by read() and write() method of <em>RwLock</em> are marked <em>!Send</em> aka not send. The reason being thread locking a RwLock must be thread relinquishing the lock.</p><pre>frame_holder: Arc&lt;Mutex&lt;Vec&lt;RwLock&lt;FrameData&gt;&gt;&gt;&gt;;<br>fn read_page(&amp;self, page_id: PageId) -&gt; RwLockReadGurad&lt;&#39;_, FrameData&gt;;<br>fn write_page(&amp;self, page_id: PageId) -&gt; RwLockWriteGuard&lt;&#39;_, FrameData&gt;;<br>// This would have worked but both RwLockReadGurad and RwLockWriteGuard<br>// as !Send and thus can not be passed around thread. <br>// &#39;_ is anonymous lifetime in Rust.</pre><p>Try 3</p><p>Why not return <em>RwLock</em> it self. This would work, but for me it is semantically wrong. When I get response from write_page, I expect to have exclusive access till the time I want. Return of RwLock will need caller to invoke read() and write(), which will lock the frame. This may or may not be terribly bad, but let’s try something different, which does not requires caller to lock for access.</p><p>Try 4</p><p>Would’t it be nice if a <em>frame_holder</em> looses it content once a db activity has acquired a exclusive access. For a frame to be exclusive, even <em>frame_holder</em> should not hold it. It suggest a index in <em>frame_holder</em> may or may not have FrameData. This presence(Some) and absence(None) of value is represented by <em>Option</em> in Rust. So we can think to store frame in <em>frame_holder</em> like</p><pre>frame_holder: Arc&lt;Mutex&lt;Vec&lt;Option&lt;Arc&lt;FrameData&gt;&gt;&gt;&gt;&gt;<br>/*<br>Let&#39;s break down the layers in the type.<br>Arc - so that frame_holder can be passed around thread, and shared if needed.<br>It makes frame_holder Send. But it need to be Sync to be truly shared.<br>Mutex - Adds synchronization, enabling safe concurrent access.<br>Vec - Stores a contiguous block of memory for managing frames.<br>Option - Indicates that a frame can be either Some(FrameData) or None,<br>useful for exclusive access scenarios.<br>Arc - Again for multiple reading DB activity, we need type to be Send. <br>As shared data are non mutating, Mutex is not needed.<br>FrameData - Actual data holding Frame buffer and other helper values.<br>Some useful ones are <br>frame_id: FrameId - what frame it represents. <br>page_id: PageId - what page it is assigned to. Helps during eviction.<br>pin_count: AtomicU32 - how many db activity are looking at this frame.<br>To be evicted, this count must be zero.<br>is_dirty: AtomicBool - if frame has be updated. If so it must be persisted <br>to DB.<br>*/</pre><p>After a successful return of write operation, <em>frame_holder</em> at selected <em>frame_id</em>, will have <em>None</em> value. Thus marking exclusive access.</p><p>And then we can define our read/write operation as below. Note we still use <em>RAII </em>patten and return Guard. This allows us to restore <em>frame_holder with Some(</em>Arc&lt;FrameData&gt;) in <em>drop</em> of <em>WriteGuard, </em>relinquishing exclusive access. Similarly during drop of ReadGuard, we can decrement page reference counter. Though in our case, Arc::strong_count can be used for the same.</p><pre>struct ReadGurad(Arc&lt;Box&lt;[u8; PAGE_SIZE]&gt;&gt;);<br>fn read_page(&amp;self, page_id: PageId) -&gt; Option&lt;ReadGurad&gt;;<br>// return with Arc type suggest, multiple activity in db for same page_id<br>// can have hold to shred copy to data.<br>// Box - is rust way to of representing data on heap.<br>struct WriteGuard(Box&lt;[u8; PAGE_SIZE]&gt;&gt;);<br>fn write_page(&amp;self, page_id: PageId) -&gt; Option&lt;WriteGuard&gt;;<br>// return with simple Box&lt;[u8; PAGE_SIZE]&gt; signifies write has exclusive access.<br><br>// Option in both represents possiblity of non freeded up frame.<br>// Time to increase size of memory - I guess. Or just wait it out.<br><br>//Both ReadGurad and WriteGuard will implement Drop trait for RAII.<br>//Drop trait method drop(&amp;mut self) is executed when a value goes out of scope.<br>//This can be thought as Destructor in C++.</pre><p>I have mentioned quite a few types in this post. Let me talk about two more type.</p><h3>Conditional Variables</h3><p>When a thread holds a mutex, waiting for some condition to become true, it can either block CPU or ask OS to inform it when waiting condition is met and thus relinquishes CPU.</p><p>In the context of the Buffer Pool Manager (BPM), conditional variables are useful in scenarios such as:</p><ul><li>A writer thread waiting for all active reader threads to finish before obtaining exclusive access to a frame.</li><li>A reader thread waiting for a frame being updated by a writer thread to become available again.</li></ul><pre> <br>while frame_lock.as_ref().is_none()<br> || (is_write &amp;&amp; Arc::strong_count(frame_lock.as_ref().unwrap()) != 1)<br> {<br>    frame_lock = cond<br>        .wait_timeout(frame_lock, Duration::from_micros(100))<br>        .unwrap()<br>        .0;<br>    // no cpu is held, and above line wait for notification for same condvar.<br>    // In this example, a drop() of WriteGuard thread can notify that<br>    // FrameData is returned back to frame_holder.<br>}<br>//Taken directly from implementation. You can see I have used wait with timeout.<br>//This helped me to break out of situation when thread missed out notification<br>//from condvar at some other place.</pre><h3>Deref: Simplifying Access to Nested Types in Rust</h3><p>In many programming languages, accessing deeply nested types often involves a chain of access operators (.). For example, if you want to reach the innermost [i8; PAGE_SIZE] value wrapped in multiple layers (e.g., ReadGuard), you might write something like:</p><pre>readGuard.as_ref().as_ptr(); //dummy code. Does not work.</pre><p>This approach works, but as the nesting increases, the chain becomes unwieldy. Rust solves this problem elegantly using the <strong>Deref</strong> trait.</p><h4>The Deref Trait</h4><p>The Deref trait allows a type to define how it should be dereferenced. When implemented, it simplifies access by automatically &quot;unwrapping&quot; nested layers. With Deref, you can access the innermost value seamlessly, as if the layers in between don’t exist.</p><pre>impl Deref for ReadGuard {<br>    type Target = [u8; PAGE_SIZE];<br><br>    fn deref(&amp;self) -&gt; &amp;Self::Target {<br>        self.frame.get_readable()<br>    }<br>}<br>/*<br>let guard: ReadGuard = ...;<br>guard. -&gt; here . will directly refer to [u8;PAGE_SIZE]<br>*/<br><br>//Most wrapper type Box, Arc, Mutex implement this trait along with its <br>//mutable counter part DerefMut (when it makes sense). Thus accessing nested<br>//type in Rust is not that taxing, if done right.</pre><p>And that is all for Post 1. We’ve explored the foundational concepts of frames, pages, and the inner workings of the Buffer Pool Manager, including the LRU-K cache eviction policy. These building blocks form the backbone of a database’s memory management system. In the next post, I’ll dive into <strong>Indexes</strong> with a focus on the <strong>B+ Tree</strong> data structure — an essential component for efficiently querying data in relational databases.</p><p>I’d love to hear your thoughts, suggestions, or feedback — feel free to share them publicly or privately. As always, keep learning and stay curious!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1c25945446c2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Rust Nom tag with graceful whitespace]]></title>
            <link>https://vishalcjha.medium.com/rust-nom-tag-with-graceful-whitespace-fd674df066d9?source=rss-7ec72335d485------2</link>
            <guid isPermaLink="false">https://medium.com/p/fd674df066d9</guid>
            <category><![CDATA[learning]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[closure]]></category>
            <dc:creator><![CDATA[Vishal Kumar]]></dc:creator>
            <pubDate>Mon, 04 Dec 2023 03:33:55 GMT</pubDate>
            <atom:updated>2023-12-04T03:33:55.727Z</atom:updated>
            <content:encoded><![CDATA[<p>This article assumes you have familiarity with Rust and heard about <a href="https://docs.rs/nom/latest/nom/"><em>nom</em></a>. To jog memory in one line, nom is a popular parser combinator library in Rust. It provides “parser functions” that take input and give back output and “combinator functions” that combine parsers.</p><p>The nom guide is a great resource to learn more about nom. <a href="https://tfpk.github.io/nominomicon/chapter_4.html">Chapter 4</a>, which details custom parsers to return Custom data types as output, ends with an open question — how can we gracefully allow whitespaces while parsing? We can rephrase the problem for simplicity — how can we gracefully avoid whitespaces when matching a <em>tag</em>? Let’s say we have to identify the tag “hello”. We can write the following :</p><pre>tuple((many0(tag(&quot; &quot;)), tag(&quot;hello&quot;), many0(tag(&quot; &quot;))))(input)?</pre><p>The above is fine but what will happen if we want the same relaxation for other tags say “world”? Are we going to duplicate the code? I hope you are thinking No to answer. To do so, let’s capture the above action using closures —</p><pre>/// clone is necessary inside closure. As we are passing reference<br>/// and return Closure,<br>/// we need to make sure captured value lives as long as closure.<br>/// Owning the value be clone and moving it the way to do so.<br>/// ```<br>/// let value = spaced_tag(&quot;hello&quot;)(&quot;   hello  world&quot;);<br>/// assert_eq!(value, Ok((&quot;world&quot;, &quot;hello&quot;)));<br>/// ```<br>use nom::{bytes::complete::tag, IResult};<br>fn spaced_tag&lt;&#39;a&gt;(tagged_str: &amp;&#39;a str) -&gt; impl FnMut(&amp;&#39;a str) -&gt; IResult&lt;&amp;&#39;a str, &amp;&#39;a str&gt; {<br>    let moved = tagged_str.clone();<br>    move |input: &amp;str| {<br>        let res = tuple((many0(tag(&quot; &quot;)), tag(moved), many0(tag(&quot; &quot;))))(input)?;<br>        Ok((res.0, res.1 .1))<br>    }<br>}</pre><p>Note as we are accepting tagged_str as reference, we need to make an owned copy by using the clone and then moving this in closure capture. This makes sure, captures values lives as long as closure. Note we can make this function accept either <em>&amp;str or String</em> by making the parameter <em>tagged_str: impl Into&lt;String&gt; </em>but<em> </em>I wanted to keep this simple for any level Rust developers.</p><p>And now we can use this parser to match any tag with whitespaces around it. For example</p><pre>// nom parser return (remaining, parsed) value when success.<br>// That is why first assert has world - not parsed, and hello - which is parsed.<br>let value = spaced_tag(&quot;hello&quot;)(&quot;   hello  world&quot;);<br>assert_eq!(value, Ok((&quot;world&quot;, &quot;hello&quot;)));<br>let value = spaced_tag(&quot;hello&quot;)(&quot;hello  world&quot;);<br>assert_eq!(value, Ok((&quot;world&quot;, &quot;hello&quot;)));<br>let value = spaced_tag(&quot;nom&quot;)(&quot;nomhello  world&quot;);<br>assert_eq!(value, Ok((&quot;hello  world&quot;, &quot;nom&quot;)));</pre><p>I hope this article excites you to explore more capabilities of nom. I also hope this explains how features in Rust, closure to be specific in this use case help to remove code duplication. Happy coding !!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fd674df066d9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Rust in Distributed System Environment]]></title>
            <link>https://vishalcjha.medium.com/rust-in-distributed-system-environment-8b164b6a5bed?source=rss-7ec72335d485------2</link>
            <guid isPermaLink="false">https://medium.com/p/8b164b6a5bed</guid>
            <category><![CDATA[learning]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <dc:creator><![CDATA[Vishal Kumar]]></dc:creator>
            <pubDate>Tue, 25 Jul 2023 10:46:15 GMT</pubDate>
            <atom:updated>2023-07-25T10:46:15.294Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sO3HFZpPxGE34Pwq" /><figcaption>Photo by <a href="https://unsplash.com/@fridaae29?utm_source=medium&amp;utm_medium=referral">Frida Aguilar Estrada</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>What makes Rust a good choice for the distributed system? Well, to validate this, let’s write some code involving distributed systems. Distributed locks, Queues, Unique Id Generators, Decentralized file share, and Databases are a few examples of distributed system components. There are many vendors that provide competing products. But how to verify if these products live up to their promises? Without complete verification, software using these products can have unintended consequences. Enter <a href="https://jepsen.io/">Jespen</a>, an open-source library for testing and encouraging vendors to meet their claims. I will not be explaining distributed systems concepts in detail, but showcasing Rust code snippet to demonstrate its effectiveness in such an environment.</p><p><a href="https://fly.io/dist-sys/">What challenges are we solving? </a>We will be looking at 4 challenges out of 6. This challenge set is provided by Fly.io, in partnership with <a href="https://aphyr.com/about">Kyle Kingsbury</a>, author of Jespen. Fly.io is a cloud provider with nodes across the globe. I came across this via a vlog from <a href="https://youtu.be/gboGyccRVXI">Jon Gjengset</a>, author of “Rust for Rustaceans”. Post is focused on Rust features that make language enjoyable. <strong>It will explore SerDe, blanket implementation, channel, and RAII concepts in Rust, </strong>using code snippets from my solution (<a href="https://github.com/vishalcjha/fly_dis"><strong><em>Git Link</em></strong></a>).</p><p><strong>Let’s start with SerDe -</strong> When I think of the distributed system, I think of N nodes communicating with each other by passing messages. When data is sent from one node to another, we need serialization (Ser) of data from the object to wire format. This data reaches other nodes where it converts wire format back to object format, which is called deserialization (de). Rust has <a href="https://serde.rs/">serde</a> crate, which provides the mapping of Rust data types to a standard specification. Such specification can then be converted to specific wire formats i.e. JSON, TOML, or Protobuf. <a href="https://docs.rs/serde_json/latest/serde_json/#">serde_json</a> is a widely used crate in the Rust echo system for JSON wire format.</p><p>Rust type system, specifically traits (akin to Interface or abstract class in other languages) makes serde highly efficient. It uses no reflection and in some scenario zero memory allocation for deserialization. Below is a snippet showing serde in action.</p><pre>// Git link https://github.com/vishalcjha/fly_dis/blob/main/src/message.rs<br>#[derive(Debug, Serialize, Deserialize, Clone)]<br>pub struct Message&lt;T&gt; {<br>    pub src: String,<br>    #[serde(rename = &quot;dest&quot;)] // renames dst to dest for wire format<br>    pub dst: String,<br>    pub body: Payload&lt;T&gt;,<br>}<br><br>#[derive(Debug, Serialize, Deserialize, Clone)]<br>pub struct Payload&lt;T&gt; {<br>    #[serde(flatten)]<br>    pub data: T,<br>    pub msg_id: Option&lt;usize&gt;,<br>}<br><br>#[derive(Debug, Serialize, Deserialize, Clone)]<br>#[serde(tag = &quot;type&quot;, rename_all = &quot;snake_case&quot;)]<br>pub enum Init {<br>    Init {<br>        node_id: String,<br>        node_ids: Vec&lt;String&gt;,<br>    },<br>    InitOk {<br>        in_reply_to: usize,<br>    },<br>}</pre><p>Few interesting serde macro attributes</p><ol><li>Serialize — make an object Serializable.</li><li>Deserialize — allows the construction of objects from wire format.</li><li>Tag — Enum in Rust represents union type. They are also called polymorphic types, meaning a single type can have multiple variants. When we serialize, it is helpful to provide extra information to allow quick identification of specific variants. The tag attribute allows that. It will add an extra field in the above example type in a serialized format which will have variant name. Though Rust does not forces this extra info.</li><li>flatten — This one is interesting. It unpacks an object in serialized wire format. In the above example, when Payload is serialized we will not have data an attribute rather T will be unpacked in place of the payload object.</li><li>Debug and Clone are standard Rust macro attributes that help to autogenerate object representation for debug format and to create a clone of object respectively. It is recommended to tag data structures with these, when possible.</li></ol><p><strong>Blanket Implementation in action </strong>— In this challenge, input comes from stdin and output goes out to stdout. Input is read one line at a time, and can be captured as String or byte array. The question is how we convert this String to the desired object. Being a trait first language, one can try to parse objects from String, using FromStrtrait. But how can we implement FromStr for every type that can be Deserialized? What we need is a generic implementation for types that can be Deserialized. In Rust, such generic implementation is referred to as blanket implementation.</p><pre>//https://github.com/vishalcjha/fly_dis/blob/main/src/message.rs#L71<br>// We are providing a generic implementation of FromStr trait for any type T <br>// that also implements DeserializeOwned trait<br>impl&lt;T&gt; FromStr for Message&lt;T&gt;<br>where<br>    T: DeserializeOwned,<br>{<br>    type Err = anyhow::Error;<br><br>    fn from_str(s: &amp;str) -&gt; std::result::Result&lt;Self, Self::Err&gt; {<br>        Ok(serde_json::from_str::&lt;Message&lt;T&gt;&gt;(s)?)<br>    }<br>}</pre><p>An important part of the snippet is T: DeserializedOwned which constraints this implementation to be available to any type that can prove at compile time for its capability of Deserialization. But wait, should it not be named Deserialize{able} ? Why extra Owned in the name? As I briefly mentioned Rust serde can be allocation free. For it to happen, any deserialized object can not live beyond the thing or String we are deserializing from. But we are not storing strings we read, as it can take up infinite memory. To force Deserializer not to opt for Zero allocation, we tell it, to <em>own</em> rather than <em>loan memory, </em>hence DeserializedOwned. Details can be found <a href="https://serde.rs/lifetimes.html">here</a>.</p><p>Once we have this blanket implementation, we can use it as follows</p><pre>// Note both Message, and Init are marked with #[derive(Deserialize, ...)<br>// this makes our blanket FromStr implementaion for below line.<br>serde_json::from_str::&lt;Message&lt;Init&gt;&gt;(&amp;init_message)</pre><p><strong>Now turn for channel change </strong>— <a href="https://fly.io/dist-sys/3a/">Challenge 3</a>, involves knowledge sharing among nodes, thus making all nodes aware of complete knowledge. This is a classic example of Gossip protocol used by many peer-to-peer file-sharing applications. For the solution, I used a background thread, that will trigger periodic sync of messages from one node to other nodes in its topology. In this problem, we are given topology for each node. In the real world, nodes can construct their topology by themselves. Topology is a subset of nodes, which a given node shares its data with. This makes the protocol efficient, otherwise, all N nodes sharing data with all (N — 1) nodes will cause a N/W bottleneck, with no gain. Now the question is, how to communicate b/w periodic thread and the thread which holds knowledge? One way could be sharing memory space but that will need Mutexes. Or we can use high-level construct task to achieve the same. The idea here is to communicate b/w threads by sharing messages just like we do among nodes, rather than sharing memory. Like many other languages, Rust provides channel to achieve the same. A channel can be buffered, unbuffered, finite, or infinite. It has two ends, sender and receiver. In basic form, we have multiple senders (producers) and single receiver (consumer), thus named mpsc .</p><pre>// Creaing a unbounded channel.<br>// For creating bounded channel mpsc::sync_channel(capacity) <br>// Bounded channel can block caller, an effective way of back pressure.<br>use std::sync::mpsc::{channel, Receiver, Sender}<br>let (tx, rx) = channel();</pre><p>The single line above creates both ends of the channel. Internally, channels use atomic constructs (not mutex though), but keeping this detail hidden from application programs, makes the program less error-prone. tx is the sender end, and rx is the receiver end. For a code to compile Rust needs to prove ownership, but as there could be multiple senders, who is the owner? This problem is solved by the concept of shared ownership. In a single-thread program Rc types represent shared ownership but the same is represented by Arc like containers in a multithreaded environment. Cloning of an object is a costly operation, but cloning of container types like Rc or Arc (and tx ) is a mutation of owner count, which is a fast operation. A in Arc stands for atomic reference count, which is slower because of the use of atomic variables than their single-threaded counterpart Rc . Let’s see how we share ownership of tx with other threads.</p><pre>let (tx, rx) = channel()<br>let tx_cloned = tx.clone();<br>// we need to clone tx to tx_cloned. Otherwise line using tx outside spawn<br>// block would not compile as tx owership is passed to thread. By cloning, <br>// we increment owner count and thus sharing ownership.<br>let join_handler = thread::spawn(move || {<br> // use tx_cloned.send to send message to channel<br>tx_cloned.send(...)?; // cloned and moved tx.<br> .....<br>});<br>tx.send(...)?; // second use of tx<br>.<br>.<br>.<br>join_handler.join()?;</pre><p>Block inside thread::spawn represents a closure || . As spawned thread can live beyond the parent thread, we need to move any captured variables, making its lifetime independent of the original thread. <a href="https://doc.rust-lang.org/book/ch13-01-closures.html">Rust book explains this in detail.</a></p><p>A channel is open, till it has either a single sender or single receiver. Its receiver side closes itself when there is no sender, otherwise, it will be an infinite wait. For a graceful shutdown, we will have to pass a termination signal to background threads, just like our Gossip trigger thread. For challenge 3, I did the same, but that is not reusable. When I faced a similar question in challenge 4, I used RAII.</p><p><strong>Let’s fee/drop the resources correctly aka RAII —</strong> A brief detour. When Herb Sutter of C++ frame was asked what is the best feature in C++, he said } . One can ask, what&#39;s the fuss about }, well it is RAII enabler. RAII stands for <a href="https://en.cppreference.com/w/cpp/language/raii"><em>Resource Acquisition is Initialization</em></a>, a concept that ties an object&#39;s lifetime to the lifetime of its resources. Once an object goes out of scope, most likely at the end of some} object can define code, usually referred as destructors, which is executed for resource cleanup. For this challenge, the background thread triggers periodic events to initiate broadcast, holding a txresource, which in turn hold rx. We do not want such threads to be running forever. We can easily create lifetime guards of resources by defining destructors. In Rust, this is achieved by Drop trait, which is called when an object owner count reaches to zero. Below is a snippet of Drop the implantation of PeriodicThread the struct.</p><pre>// https://github.com/vishalcjha/fly_dis/blob/main/src/periodic_thread.rs<br>// A data structure, with thread handler and terminate signal.<br>// Both are private member to struct (see lack of pub) and thus implementation <br>// detail for its client.<br>pub struct PeriodicThread {<br>    handler: Option&lt;JoinHandle&lt;()&gt;&gt;, // thread handler<br>    terminate: Arc&lt;AtomicBool&gt;,<br>}<br><br>impl Drop for PeriodicThread {<br>    fn drop(&amp;mut self) {<br>        // we show our intent to terminate this thread.<br>        // Infinite loop below reads this and ends the loop and thus finishing thread.<br>        self.terminate<br>            .store(true, std::sync::atomic::Ordering::Release);<br>        if let Some(handler) = self.handler.take() {<br>            // if there is handler, we first wake it and then wait for it to finish.<br>            handler.thread().unpark();<br>            if let Err(_) = handler.join() {<br>                println!(&quot;Periodic thread join ended with error&quot;);<br>            }<br>        }<br>    }<br>}<br><br>// and its usage for challange 4<br>// https://github.com/vishalcjha/fly_dis/blob/main/src/counter.rs#L52<br>let gossip_trigger_task = PeriodicThread::new(<br>      // periodic task<br>      move || {<br>          tx.send(ExternalInternal::Internal(Internal::TriggerDispatch {}))?;<br>          Ok(())<br>      },<br>      // gap b/w each execution <br>      Duration::from_secs(1),<br>  )</pre><p>The moment gossip_trigger_task is dropped explicitly or by the runtime, its loop terminates, dropping any captured resource. In this case, it is shared ownership of tx and thus allowing rx to be dropped automatically, which shuts down the application node.</p><p>With 2 more challenges left, I am sure to learn a few other tricks and traits. Excited to see what’s your take on this challenge. If you have come across some fun challenges, share the link with me. Happy learning !!!</p><p>Challenge home <a href="https://fly.io/dist-sys/">https://fly.io/dist-sys/</a></p><p>Jon Gjengset’s challenge vlog <a href="https://youtu.be/gboGyccRVXI">https://youtu.be/gboGyccRVXI</a></p><p>Git link to my challenge solutions <a href="https://github.com/vishalcjha/fly_dis">https://github.com/vishalcjha/fly_dis</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8b164b6a5bed" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Rust learning with Advent of code]]></title>
            <link>https://vishalcjha.medium.com/rust-learning-with-advent-of-code-922adf5331db?source=rss-7ec72335d485------2</link>
            <guid isPermaLink="false">https://medium.com/p/922adf5331db</guid>
            <category><![CDATA[collaboration]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[learning]]></category>
            <category><![CDATA[advent-of-code]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Vishal Kumar]]></dc:creator>
            <pubDate>Tue, 18 Jul 2023 10:21:48 GMT</pubDate>
            <atom:updated>2023-07-18T10:21:48.677Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gsk6joEJcJGxv5c2" /><figcaption>Photo by <a href="https://unsplash.com/@dbaumgartner?utm_source=medium&amp;utm_medium=referral">Derek Baumgartner</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Being a polyglot and biased towards building low latency distributed systems, Rust has always been on my list. I have deployed Rust code for projects involving realtime ad bid price evaluation and real time video media processing for anomaly detection. Both times it was learning on job and I enjoyed it. This time, I wanted to see how Rust system have evolved and choose to do while solving <a href="https://adventofcode.com/2022">Advent of Code</a>. Idea came after coming though Luciano Mammino’s talk on <a href="https://youtu.be/udHjmno-tfA">You Tube</a>. BTW his<a href="https://www.amazon.com/Node-js-Design-Patterns-production-grade-applications/dp/1839214112"> Node book is amazing</a>. <strong>One would ask but why : Rust is considered safe and performant language but it is tagged a difficult and non productive language. With small snippets I would like bring a different prospective. </strong>Explanation is kept minimal as intent is to showcase ergonomics of language.</p><p>This article and future article in this series list small code snippets I used to bring my skill to use and save Christmas 2022. I hope July 2023 is not late for that.</p><p>All problem in Advent of code requires reading input from files. Following are two possible way. First way is inefficient in terms of memory as it tries to read file in one go. In my solutions I have always used second way.</p><pre><br>use std::{<br>    fs::{read_to_string, File},<br>    io::{BufRead, BufReader, Read}<br>};<br>// Read file in one go - less efficient in terms of memory<br>for line in  read_to_string(file_name)?.lines() {<br>  process_line(&amp;line);<br>}<br><br>// A better approach is to use Buffered reader and consume one line at a time<br>for line in BufReader::new(File::open(file_name)?).lines() {<br>  process_line(&amp;line);<br>}</pre><p>One might notice use of ? . Rust uses functional approach and to make fallible functions complete, returns <a href="https://doc.rust-lang.org/book/ch09-02-recoverable-errors-with-result.html">Result</a>. Result is a Union type represented as enum, with Ok and Err variant. Unlike many language where handling error is forced at each call site, Rust provides an operator ? which simplifies error handling. In case error occurs, function returns with same error response. And it is matter of train implementation if we want to change this behavior.</p><p>Now we have successfully read file. All coding challenge needs operation on file. That brings us to iterators. Before we can talk about iterators though, we have to talk about <a href="https://doc.rust-lang.org/book/ch10-02-traits.html">traits</a>. Traits are like interface in other programming language. And they describe behavior or capability that any type may or may not support. In above code lines() return an object of <a href="https://doc.rust-lang.org/std/io/struct.Lines.html#impl-IntoIterator-for-Lines%3CB%3E">Lines </a>structure. And these do have iteration capability. Forloop in rust depends on support of <a href="https://doc.rust-lang.org/std/iter/trait.IntoIterator.html">IntoIterator</a> trait. Once we have iterators, we get access of many adapters. List below is minute sub set of adapters I reached out when solving code challenge.</p><ol><li><a href="https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.map">map</a>/ <a href="https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.flat_map">flat_map</a> — are used for adapting iterator item from type A to type B.</li><li><a href="https://doc.rust-lang.org/stable/std/iter/trait.Iterator.html#method.enumerate">enumerate</a> — allows to get access to iteration count along with iteration item.</li><li><a href="https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.filter">filter</a> &amp; <a href="https://doc.rust-lang.org/std/iter/struct.FilterMap.html">filterMap</a> — first one allows to process selected items and later combines filter and map in one.</li><li><a href="https://doc.rust-lang.org/std/iter/trait.Sum.html#tymethod.sum">sum</a>, count, min, max — simple accumulators that reduce iterators in single value.</li><li><a href="https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.fold">fold</a> — allows to accumulate/reduce iterators into any data structure. For example want count of each character in a string, we can easily create a HashMap with fold. I find it very useful in many scenarios.</li></ol><pre>use std::collections::HashMap;<br>let word_count = &quot;repeated&quot;<br>    .chars() // return iterator over String one char at a time.<br>    .fold(HashMap::new(), |mut word_count, current_char| {<br>        word_count<br>            .entry(current_char)<br>            .and_modify(|count| *count += 1)<br>            .or_insert(1);<br>        word_count<br>    });<br>assert_eq!(<br>    word_count,<br>    HashMap::from([(&#39;a&#39;, 1), (&#39;e&#39;, 3), (&#39;t&#39;, 1), (&#39;d&#39;, 1), (&#39;r&#39;, 1), (&#39;p&#39;, 1)])<br>);</pre><p>Note HashMap in Rust comes with <a href="https://doc.rust-lang.org/stable/std/collections/struct.HashMap.html#method.entry">EntryApi</a> which return Union Type Entry. It has two variant Occupied, and Vacant. This allows find and mutate i.e. either update or insert value associated with given key in single lookup.</p><p>There are plethora of adapters and it is easy to create create custom adapter.</p><p><a href="https://adventofcode.com/2022/day/3">In day 3 of challenge</a>, we are required to work 3 lines at a time. Let’s create an struct which provides chunked iterator to do this.</p><pre>struct Chunked&lt;I, const N: usize&gt; {<br>    iter: I,<br>}<br><br>impl&lt;I, const N: usize&gt; Chunked&lt;I, N&gt; {<br>    fn new(iter: I) -&gt; Self {<br>        Chunked { iter }<br>    }<br>}<br><br>/* We are implementing Iterator Trait for Chunked struct.<br>* It will allow us to write<br>* Chunked::new(input.lines())<br>        .into_iter()<br>         // we are passing 3 as chunk size.<br>        .map(|item: [&amp;str; 3]| ... )...<br>* <br>*<br>*/<br>impl&lt;I, const N: usize, T&gt; Iterator for Chunked&lt;I, N&gt;<br>where<br>    I: Iterator&lt;Item = T&gt;,<br>    I: Debug,<br>{<br>    // This is where we tell what kind of Item this iterator will produce.<br>    type Item = [T; N];<br><br>    fn next(&amp;mut self) -&gt; Option&lt;Self::Item&gt; {<br>        let mut result = Vec::new();<br>        while let Some(next) = self.iter.next() {<br>            result.push(next);<br>            if result.len() == N {<br>                break;<br>            }<br>        }<br> <br>         // If we are left with less than 3 elements stop processing.<br>        if result.len() != N {<br>            return None;<br>        }<br><br>        Some(result.try_into().unwrap())<br>    }<br>}</pre><p>Now we have capability to work on individual lines. Many problem involves changing String to custom data structure. In Rust we can define custom data structure with with <a href="https://doc.rust-lang.org/book/ch05-01-defining-structs.html">struct</a> keyword. There are few traits that allows conversion of one type to another.</p><ol><li><a href="https://doc.rust-lang.org/std/str/trait.FromStr.html">FromStr</a> — allows transformation of a type from String. For example i32 has FromStr capability. This allows <em>“1234”.parse::&lt;i32&gt;().unwrap(). </em>As any parsing can fail, result on parse is Result. We have already seen usage of ? operator to retrieve Ok variant. unwrap , expect are other options where we want to panic if result is of Err type.</li><li><a href="https://doc.rust-lang.org/std/convert/trait.From.html">From</a> / TryFrom — transform one type to another.</li><li><a href="https://doc.rust-lang.org/std/convert/trait.Into.html">Into</a>/ TryInfo — This is reciprocal to From trait. And Rust can generate definition of From or Into give other. One uses From to convert one type to another type in regular program flow. But Into are specifically used to make function more flexible by allowing type which they expect.</li></ol><pre>/* In Rust there are three way to define struct.<br>* a. Empty - struct Electron; - these do not take any memory.<br>* b. Tuple based - as done here. Member are accesed with index value like .0.<br>* c. Regular struct. We could have written Number like below <br>*    struct Number { num: i32 }<br>*.Rust struct does not define method in same block as struct. But they are defined<br>* outside using impl block. This helps to break struct capability in smaller chunks           <br>* and provides redability.<br>*/<br>struct Number(i32);<br>impl Number {<br>    fn say_number(&amp;self) {<br>        println!(&quot;I am {}&quot;, self.0);<br>    }<br>}<br><br>impl Into&lt;Number&gt; for &amp;str {<br>    fn into(self) -&gt; Number {<br>        Number(self.parse::&lt;i32&gt;().unwrap())<br>    }<br>}<br><br>/* Here we are using generic with bounds based on Traits. `flexible` type is not <br>* known at compile time but is guaranteed to be a type that can be converted to Number type. <br>*/<br>fn work_with_number&lt;A&gt;(flexible: A)<br>where<br>    A: Into&lt;Number&gt;, // this allows flexible to be of any type that can be converted in Number.<br>{<br>    flexible.into().say_number();<br>}<br><br>/*<br>Now we can call work_with_number with Number as well as &amp;str as parameter. <br>*/<br>fn call_work_with_number() {<br>    work_with_number(Number(1234));<br>    work_with_number(&quot;1234&quot;);<br>}</pre><p>So far we have seen how to process data using what Rust standard library provides. For a language to succeed it must have a vibrant community. Being most loved language on StackOverFlow for many years, Rust does has a big community. They share code using <a href="https://crates.io/">Cargo</a> package manager. Let’s review <a href="https://docs.rs/nom/latest/nom/">nom</a> which is a parse combinator library.</p><p>Though Rust provides <a href="https://docs.rs/regex/latest/regex/">regex</a>, nom provide efficiency and way to build and reusable parsing components. Let’s parse first 9 lines of input from <a href="https://adventofcode.com/2022/day/5/input">5th coding challenge</a>.</p><pre>use nom::{<br>    bytes::complete::tag,<br>    character::complete::alpha1,<br>    multi::separated_list0,<br>    sequence::{delimited, tuple},<br>    IResult,<br>};<br>fn parse_line(input: &amp;str) -&gt; IResult&lt;&amp;str, Vec&lt;Option&lt;&amp;str&gt;&gt;&gt; {<br>    Ok(separated_list0(tag(&quot; &quot;), parse_crate)(input).unwrap())<br>}<br><br>fn parse_crate(input: &amp;str) -&gt; IResult&lt;&amp;str, Option&lt;&amp;str&gt;&gt; {<br>    let (rem, matched) = alt((tag(&quot;   &quot;), delimited(tag(&quot;[&quot;), alpha1, tag(&quot;]&quot;))))(input)?;<br>    let result = match matched {<br>        &quot;   &quot; =&gt; None,<br>        alpha =&gt; Some(alpha),<br>    };<br>    Ok((rem, result))<br>}<br><br>#[cfg(test)]<br>mod tests {<br>    use std::collections::HashMap;<br><br>    use super::*;<br><br>    #[test]<br>    fn test_parse_crate() {<br>        let input = r#&quot;<br>                    [Q]     [P] [P]<br>                [G] [V] [S] [Z] [F]<br>            [W] [V] [F] [Z] [W] [Q]<br>        [V] [T] [N] [J] [W] [B] [W]<br>    [Z] [L] [V] [B] [C] [R] [N] [M]<br>[C] [W] [R] [H] [H] [P] [T] [M] [B]<br>[Q] [Q] [M] [Z] [Z] [N] [G] [G] [J]<br>[B] [R] [B] [C] [D] [H] [D] [C] [N]<br>&quot;#;<br>        let crates: Vec&lt;Vec&lt;String&gt;&gt; = input<br>            .split(&quot;\n&quot;)<br>            .filter_map(|line| parse_line(line).ok())<br>            .fold(vec![Vec::new(); 9], |mut acc, current| {<br>                current<br>                    .1<br>                    .into_iter()<br>                    .enumerate()<br>                    .for_each(|(index, value)| match value {<br>                        Some(value) =&gt; acc[index].push(value.to_string()),<br>                        None =&gt; {}<br>                    });<br>                acc<br>            });<br>        assert_eq!(<br>            crates,<br>            vec![<br>                vec![&quot;C&quot;, &quot;Q&quot;, &quot;B&quot;,],<br>                vec![&quot;Z&quot;, &quot;W&quot;, &quot;Q&quot;, &quot;R&quot;],<br>                vec![&quot;V&quot;, &quot;L&quot;, &quot;R&quot;, &quot;M&quot;, &quot;B&quot;],<br>                vec![&quot;W&quot;, &quot;T&quot;, &quot;V&quot;, &quot;H&quot;, &quot;Z&quot;, &quot;C&quot;],<br>                vec![&quot;G&quot;, &quot;V&quot;, &quot;N&quot;, &quot;B&quot;, &quot;H&quot;, &quot;Z&quot;, &quot;D&quot;],<br>                vec![&quot;Q&quot;, &quot;V&quot;, &quot;F&quot;, &quot;J&quot;, &quot;C&quot;, &quot;P&quot;, &quot;N&quot;, &quot;H&quot;],<br>                vec![&quot;S&quot;, &quot;Z&quot;, &quot;W&quot;, &quot;R&quot;, &quot;T&quot;, &quot;G&quot;, &quot;D&quot;],<br>                vec![&quot;P&quot;, &quot;Z&quot;, &quot;W&quot;, &quot;B&quot;, &quot;N&quot;, &quot;M&quot;, &quot;G&quot;, &quot;C&quot;],<br>                vec![&quot;P&quot;, &quot;F&quot;, &quot;Q&quot;, &quot;W&quot;, &quot;M&quot;, &quot;B&quot;, &quot;J&quot;, &quot;N&quot;]<br>            ]<br>        );<br>    }<br>}</pre><p>Here we are combining quite a few nom parser (see use nom:: at top of code snippet), with one defined above parse_crate and combining them to create a new combined parser parse_line. Rust also encourages to write unit test in same file as source code. As same file means same module, unit test has access to private function (lack of pub modifier in function definition makes it private).</p><p>In conclusion, when we work with something new, it does take time, especially if it bit unconventional. I have skipped over many nuances notable reference and borrow from discussion. As these concepts are usually not present in many language, or invisible mostly, having it explicit, Rust does make adoption challenging. But once we understand the purpose of these construct in language, working with Rust is like working with any other modern language. My experience in Rust is almost pleasantly equal to coding in Kotlin. Both (along with other modern language like Scala, Dart, Typescript) have lots in common namely</p><ol><li>Functional construct / flowing api</li><li>Null aware operators</li><li>Better error handling</li><li>Extension functions</li><li>Immutability</li><li>Composition above inheritance</li><li>Union types</li><li>async support</li><li>pattern matching</li></ol><p>I hope I am able to encourage you to give new thing which is bit awkward to use at first a try. It will unburden you from long JVM tweaks for CPU spike when our customer needs us the most, or make software reliable by clearly defining ownership and provides all construct which we look in modern languages. Give it (or any new thing) a try and comment how you made a better product.</p><p>PS: I am hoping to build a toy DB using Rust. Reach out if want to collaborate.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=922adf5331db" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cheatsheet from Designing data-intensive applications — Part I]]></title>
            <link>https://vishalcjha.medium.com/cheatsheet-from-designing-data-intensive-applications-part-i-def48a43e5a?source=rss-7ec72335d485------2</link>
            <guid isPermaLink="false">https://medium.com/p/def48a43e5a</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[learning]]></category>
            <category><![CDATA[design]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[big-data]]></category>
            <dc:creator><![CDATA[Vishal Kumar]]></dc:creator>
            <pubDate>Mon, 06 Feb 2023 14:30:45 GMT</pubDate>
            <atom:updated>2023-02-06T14:30:45.785Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Suitcase stacked picture from some where in Doylestown" src="https://cdn-images-1.medium.com/max/1024/1*1iGF0o5I3bWDS0h4jriGKg.jpeg" /><figcaption>Replicated and Partitioned storage - somewhere in Doylestown (PA)</figcaption></figure><h3>Cheatsheet from Designing data-intensive applications — Part I</h3><p>The book “Designing data-intensive applications” (DDIA) by Martin Kleppmann, is a must-read book for Software professionals. Many of us do not get much time or have not come across this book. In a 2 or 3-part series blog, I hope to make you aware of the nomenclature and design principles behind data-intensive applications. I will follow book chapter sequencing and present their takeaways in each section. In Part-I, we will discuss Database choices, their physical layout, access patterns, schema evolution, and things to watch when using replication and partitioning. The next posts will cover time, transactions, batch, event processing, and ways to maintain heterogeneous systems in sync.</p><p><strong>Database(DB) choices</strong></p><p>Data stored in DB’s and its usage in code usually have different structures. NO SQL DB re-gained popularity in the early 2000s by making this gap smaller, aided by the explosion of data volume that required support for partition and replication. There are three popular database choices :</p><p>a. <strong>Relational</strong> — Good for storing data where most have one-to-one relationships. Joins are optimized, but making too many joins for a single query can make things slower. It is usually called DB with schema but we can also think about it as DB with write time schema.</p><p>b. <strong>Document-based</strong> — Good for one-to-many relationships. In such a scenario, relational joins may start becoming a bottleneck. Data is kept denormalized to avoid joins. Many can call it schema-less, but in reality, it is more appropriate to think about it as schema at read.</p><p>c. <strong>Graph-based</strong> — For many-to-many relationships. When denormalization for document based becomes hard to maintain. Imagine, a single update, that can have cascading effect and force updates in multiple documents. In reality, most database designs can benefit from adopting graphs, where a single record can be reached via multiple records following different relationships. It just feels natural. Recently I had a chance to prototype with Neo4J and use cypher. It was fun and helped me to realize how graphs can be very effective designs.</p><p><strong>Storage and Retrieval</strong></p><p>A note on how data is stored inside DB — the physical layout. This will help to use the right storage for a given context.</p><p>a. Log-based — Append only sequence of records. Writes are fast, wicked fast. But to read need to do a full scan, unless there is a secondary data structure to support the search. Systems, do employ compaction to make things faster by de-dupling multiple records with samekey and getting rid of <em>Tombstone(used in deletes)</em> records.</p><p>b. Indexed — Things are faster for retrieval but slower for writing. Need to keep metadata in sync with actual data.</p><p>c. Hash-based<strong> </strong>— When there is a high volume of writes, but a small number of keys.</p><p>d. In memory AVL Tree + Log-based, which allows range queries.</p><p>e. If in memory AVL trees are not desired, on disk BTrees provide crash protection, with range query benefit.</p><p>f. When queries are multidimensional, data structures like RTrees are well suited.</p><p><strong>Access patterns</strong></p><p>a. Online transactional processing(OLTP) — Usually a single user is involved in the transaction. Usually needs a small set of data, and can result in random writes.</p><p>b. Online analytic processing(OLAP) — Businesses making sense of their data or third-party (3P) data about their customers. One can use materialized view, and keep it away from OLTP flow. Usually, such materialized views have 100s of columns, so using column-based DB like Snowflake is suggested.</p><p><strong>Encoding and Evolution</strong></p><p>a. <strong>Forward compatibility</strong> — old code reading new data. One thing to keep in mind, if old code reads new data and then writes back, new fields can be nullified.</p><p>b. <strong>Backward compatibility</strong> — new code reading old data.</p><p>c. JSON is king here. Use swagger / openapi to generate schema for client interaction.</p><p>d. Binary Encoding like Thrift or Protobuf uses tag #, thus changing the field&#39;s name has no concerns. But while changing tag # or type, one should keep compatibility in mind.</p><p>e. Avro does not store type making it most compact. It is good for dynamic schema generation.</p><p><strong>Replication</strong></p><p>To keep DB running in case one fails and to have the reliability of storage, the dataset is replicated to more than one node, sometimes across countries and continents. These duplicated data needs to get in sync and can produce undesired result if not well planned.</p><p>a. Single Leader — If the write volume is not high, but the read volume is very high. Also providing serializability is easy. One should consider, a read from clients about their data should go to the leader.</p><p>b. Multi Leader — When write volume is also high. Also, one should consider sticky routing in such a scenario.</p><p>c. Leader Less — These usually use quorum-based read and write.</p><p><strong>Synchronous vs Asynchronous replication</strong> — when to get back to the client about write has been done. Having all followers synchronous does not makes sense, and partial (some quorum) is good.</p><p><strong>Adding new followers</strong> — Take a snapshot from Lader and then the follower can sync with the leader for changes after the snapshot.</p><p><strong>Handling failover</strong> — How to detect a leader is gone and how to choose a new leader. In most systems timeout is used for detecting the loss of a leader. One should be careful about<em> Split Brain </em>scenario when two nodes consider themselves as the leader.</p><p><strong>Some choices on how to replicate</strong></p><p>a. Statement based — very concise but problematic to implement. Function like now() can cause different values on a different row.</p><p>b. Write ahead log — It makes replication highly coupled with storage.</p><p>c. Logical or Row-based replication — This is most desired and most databases are supporting <em>Change data capture (CDC)</em> now.</p><p><strong>Replication challenges</strong></p><p>These are issues we should be aware of when multiple replicas are involved and different queries can interact with different replicas.</p><p>a. Read your own write — logical timestamp can help to fix this. Writing to the leader and reading from followers can cause this.</p><p>b. Monotonic read — Reading from two different replicas can result in inconsistency. The use of sticky routing can help.</p><p>c. Consistent prefix reads — This one is challenging. The Issue is, records may have different keys, and thus seems unrelated, but are connected via causality.</p><p><strong>How to handle write conflicts</strong></p><p>a. By not having it — Single leader replication</p><p>b. Converging towards a consistent state — 1. The last write wins. 2. Give higher replica preference 3. Merge conflict (like GIT) 4. Or let the client know and ask them to resolve the conflict.</p><p>c. Using CRDTs — Confict-free replicated datatypes.</p><p><strong>Partitioning</strong></p><p>When one replica can not store the whole dataset. Or can not support read or write volume, data can be broken down or partitioned and different nodes can work as sources for each subset. Partitioning can be done by either :</p><p>a. Random — write to any random partition. Reading will become a nightmare as the read queries will have to go to all partitions.</p><p>b. By range — Different partitions are responsible for a different set of range values. Range need not be of equal size and different ranges can have a different amount of data.</p><p>c. Hash-based — Take a key, and hash it to partition/node id. Rather than using modulo based, one should always use consistent hashing.</p><p>d. Consistent hashing — All nodes are positioned on an abstract ring or hash ring based on their node hash value. The same hash function is used with the data key and the node right on the virtual circle is used for storage. I<em>t is advised to assign more than one label to a node</em>, which causes a node to appear multiple times on the hash ring. This allows better distribution and minimal shuffling on node failure. Also, machines with higher computing can be given assigned a higher number of node labels.</p><p>e. Sometimes no single key is perfect — Here one can use the composite key. In such a scenario, the first key is for finding the partition node, and the rest is for sorting data on the partition node.</p><p><strong>How to route requests to partitions</strong></p><p>There is a need to map the key to the partition node. One can use Zookeeper to store this metadata.</p><p>Alternatively one can use <em>gossip protocol</em>, where any partition can accept the request and forward it to owning partition. This avoids any external mapping.</p><p>That is a wrap for this part. Hopefully, you will give it a try to DDIA book if not already.</p><p>Happy reading !!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=def48a43e5a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[WeakReferece — why I strongly recommend it]]></title>
            <link>https://vishalcjha.medium.com/weakreferece-why-i-strongly-recommend-it-985fc5974905?source=rss-7ec72335d485------2</link>
            <guid isPermaLink="false">https://medium.com/p/985fc5974905</guid>
            <category><![CDATA[ownership]]></category>
            <category><![CDATA[weakreference]]></category>
            <category><![CDATA[garbage-collection]]></category>
            <category><![CDATA[websocket]]></category>
            <category><![CDATA[observer-pattern]]></category>
            <dc:creator><![CDATA[Vishal Kumar]]></dc:creator>
            <pubDate>Thu, 26 Jan 2023 12:25:34 GMT</pubDate>
            <atom:updated>2023-01-26T12:25:34.442Z</atom:updated>
            <content:encoded><![CDATA[<h3>WeakReferece — why I strongly recommend it</h3><figure><img alt="Sunny days Ooty India" src="https://cdn-images-1.medium.com/max/1024/1*H3yHNiRHpKZvJRZihdUwOw.jpeg" /></figure><p>When we design cache or apply observer patterns, we tend to hold a reference to resources aka objects. Holding reference implies sole ownership or shared ownership of resources. In other words, once a code path holds a reference, it gets intertwined in the lifecycle of the referent. Sometimes we just want to use an object via reference if it exits.</p><p>Say for example we have a Kafka message processor. A message has a count of post likes and other details, a tuple of <em>{PostId, LikeCount, …}</em>. A client, can establish a web socket connection to the server and then subscribe itself to the count of likes, for a set of PostIds.</p><p>Without being concerned about concurrency, we can achieve this by having a subscription map between PostId and web socket clients interested in it. WebSocket reference can be passed via web socket handlers provided by web servers.</p><pre>// Not taking concurrency in account<br>// This can be part of some message processor which is listening to kafka.<br><br>val subscriptionMap: Map&lt;PostId, MutableList&lt;WebSocket&gt;&gt;<br>fun subscribe(postId: PostId, socket: WebSocket)<br>// unsubscribe is needed because a websocket can subscribe to multiple of topics<br>fun unsubscribe(postId: PostId, socket: WebSocket)<br><br>onMessage {<br>  message -&gt; val postId = message.postId<br>  for (ws in subscriptionMap[postId] ?: listOf()) {<br>     ws.sendUpdate(message)<br>  }<br>}<br></pre><blockquote>One question that above code keeps open is how to evict subscribers in case web-socket is closed. Web-socket client can be buggy or it got terminated rather than graceful close, resulting in missing unsubscribe call.</blockquote><p>To solve this issue one may employ a heartbeat mechanism, where a daemon task can remove web-socket from which the processor has not received a heartbeat message in the configured window.</p><pre>// Not taking concurrency in account<br>val heartBeatMap: Map&lt;WebSocket, TimeStampMillis&gt;<br><br>// launch a daemon coroutine, one can think as daemon task, in context of this post<br>GlobalScope.launch {<br>   // never ending daemon loop<br>   while(true) {<br>     // this will cause this coroutine to run periodically after duration<br>     delay(duration)<br>     val now = getTimeMillis()<br>     // remove if have not received heartbeat for last heartBeatGapMillis duration<br>     heartBeatMap.removeIf {entry -&gt; entry.value + heartBeatGapMillis &lt; now }<br>  }<br>}</pre><p>This can be a sufficient solution. But it forces us to do extra, nontrivial tasks. A few of them are:</p><ol><li>We have to maintain a separate map between web-socket and the last time of heartbeat. The above code is not thread-safe, so we have to keep thread safety in mind too. When choosing thread safety we have to think about critical section, phantom sharing, desire to make things faster, and then breaking it, extra burden.</li><li>To update time, now the server has to process extra heartbeat messages.</li><li>Similar to the above point, and more concerning, all clients would also need to send a heartbeat message, to message processors, an extra logic.</li></ol><p>Though these points are not that hard to code, <em>erhrm</em>, they do add unnecessary complexity. Also, as we know “<em>Only bug-free code is code that is not written</em>”, this path does open doors to bugs, some interesting talk about performance, thread safety, and debugging time, and all fun discussion (pun intended) which we could and should avoid.</p><p>How can we remove this extra code? The answer is, <strong>WeakReference</strong>. The issue here is a classic example of wrong ownership. By holding a reference, we imply shared ownership, but if we have <strong>WeakReference</strong>, the burden of Web socket reference lifetime is outside the message processor&#39;s purview. To do this in code, all we need to do is change from</p><pre>val subscriptionMap: Map&lt;Topic, MutableList&lt;WebSocket&gt;&gt;</pre><p>to</p><pre>val subscriptionMap: Map&lt;Topic, MutableList&lt;WekReference&lt;WebSocket&gt;&gt;&gt;</pre><p>Once we do that, we shake off our hands from the lifetime concerns of the WebSocket object. Now, the web server (making a connection with the web socket client, most likely a third-party library), is the only code that is truly owning the WebSocket object (hopefully another part of the code is not holding reference), which will close the web socket, and reclaim the resource. This frees up, the message consumer, from thinking about the lifecycle of the web-socket object. And thus there is no need for <em>val heartBeatMap: Map&lt;WebSocket, TimeStamp&gt;</em>.</p><p>We should still use the daemon task, which should go through <em>subscriptionMap</em> and remove released references, otherwise, its size would keep on growing. Now our daemon coroutine could be</p><pre>// Not taking concurrency in account<br>GlobalScope.launch {<br>  while(true) {<br>     // this will cause this coroutine to run periodically after duration<br>     delay(duration)<br>     val now = getTimeMillis()<br>     // remove if referant is gone<br>     subscriptionMap.forEach {<br>         entry -&gt; entry.value.removeIf{ it.value == null }<br>     }<br>     subscriptionMap.removeIf { entry.value.isEmpty() }<br>  }<br>}</pre><p>It would be better and highly emphasized, to use an actor pattern, for the subscription management, which would alleviate thread safety concerns raised in the sample code.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=985fc5974905" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spliterator: Concurrency in Java Parallel Stream]]></title>
            <link>https://vishalcjha.medium.com/spliterator-concurrency-in-java-parallel-stream-3c782f5c9ae5?source=rss-7ec72335d485------2</link>
            <guid isPermaLink="false">https://medium.com/p/3c782f5c9ae5</guid>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[stream]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[opinion]]></category>
            <dc:creator><![CDATA[Vishal Kumar]]></dc:creator>
            <pubDate>Sun, 21 Mar 2021 19:11:26 GMT</pubDate>
            <atom:updated>2021-03-21T19:11:26.315Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Parallel Lines" src="https://cdn-images-1.medium.com/max/998/1*IJnAqm6XuaXX85pcVcoBhA.png" /><figcaption>Image By <a href="https://unsplash.com/@gurdain">Gurdain Bharj</a> via <a href="https://unsplash.com/">Unsplash</a></figcaption></figure><p>Java 1.8 came with streams API which supports parallel execution on Collection. It is simple, elegant but when and how to use them is not well looked at by the developer community. In this post, I will explore Spliterator, which helps to use parallel stream effectively.</p><p>Q. How would you create a new list of uppercased words given a list of words.</p><p>A. Using Stream this can be done in a single line.</p><pre>return Arrays.<em>asList</em>(&quot;hello&quot;, &quot;world&quot;)<br>        .stream()<br>        .map(String::toUpperCase)<br>        .collect(Collectors.<em>toList</em>());</pre><p>But shall we use parallelStream() in place of stream() ? The answer is, it depends. If the list size is small, it is not suggested to use ParallelStream. The next question could be what is “not small” for ParallelStream? As a rule of thumb, for non-trivial CPU bound operation, if the size of the Collection is more than 1000, it can be considered “not small” and Parallel Streams can become useful. Doug Lea has guidance here <a href="http://gee.cs.oswego.edu/dl/html/StreamParallelGuidance.html">http://gee.cs.oswego.edu/dl/html/StreamParallelGuidance.html</a> . Going by guidance, it is not recommended to use parallelStream() in the above code snippet.</p><p>Q. What if operations on Stream are blocking I/O?</p><p>For blocking I/O bound traditionally, there would a thread pool which gets one job at a time or all jobs together and the application program hopes it does the right thing. With ParallelStream work is much simple, just adding parallelStream() in stream execution pipeline makes execution concurrent. <strong>Caution</strong>: As all streams by default share common java run time environment Fork Join Pool, it is strongly recommended to have a custom pool for blocking I/O bound execution. Many executors, along with Fork Join Pool works fine for this, though testing for different scenario is recommended.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d267307def499fe19bc600a9719cab36/href">https://medium.com/media/d267307def499fe19bc600a9719cab36/href</a></iframe><p>In the above example, all words, Hello, World, With, Parallel, Stream would be printed after 5 seconds. This may or may not be desirable. Say if these words are links of action that came as part of the request, and sleep is actually blocking rest calls on the links. Few requests with a high number of links can make the application unresponsive to almost all other requests. This is the classical starvation problem.</p><p>Q. How to control the number of concurrent operations in ParallelStream.</p><p>A. For this we have to use a new Iterator which is specifically introduced in 1.8 for ParallelStream called Spliterator. Spliterator is a portmanteau of split and iterator. At a high level, this is used to split the stream into chunks of streams which can be executed concurrently, with each chunk iterated sequentially. trySplit() takes care of the first part, i.e. split. It either returns a smaller chunk if the stream is large enough or reruns null signifying stream should not be divided further for parallel execution. tryAdvance() takes care of the second part, i.e. iteration. Iteration for a given chunk of the stream should be continued till tryAdvance() returns true. Let’s see how can we override these two methods and control the number of splits.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/53743d72f5790977a1e757e519dcf552/href">https://medium.com/media/53743d72f5790977a1e757e519dcf552/href</a></iframe><p>Above is an implementation of Spliterator for List . It divides the input List into N splits passed in as the second argument of the static factory method. <strong>Disclaimer: </strong>Code has no validation and is not production-ready.</p><p>Let’s re-write our steam with I/O using the above implementation.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/29281af1fc22203f6aaa3ae60750a590/href">https://medium.com/media/29281af1fc22203f6aaa3ae60750a590/href</a></iframe><p>It is almost the same as the last try. The difference is the usage of custom Spliterator . With this change in the above solution for a given request, we will have a maximum of 2 splits. Thus, it ensures all work submitted via CappedListSpliterator would get a maximum of 2 threads, eliminating starvation.</p><p>In the above example, elements would be divided into two splits, Hello, World,With, Parallel, Stream. We should see Hello, With followed by World, Parallel and at end Stream printed with a 5-second interval. Below is my try to represent splits using pictures. The same color represents the same passage of time from the original submission to ForkJoinPool. Note this assumes the system had enough thread and no other requests are executing on the pool.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V_mXt3ANLOfDeVTNeJ0XkA.png" /><figcaption>Original List in two splits, with each down arrow representing thread during the 5-sec interval</figcaption></figure><p>Hopefully, this will encourage you to look at Spliterator and get to know them more. Happy Learning !!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3c782f5c9ae5" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>