<?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 Alok Mishra on Medium]]></title>
        <description><![CDATA[Stories by Alok Mishra on Medium]]></description>
        <link>https://medium.com/@alok-mishra98?source=rss-33668e5959f2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*OC-sy1aYT9ue6VG3FHk9-Q@2x.jpeg</url>
            <title>Stories by Alok Mishra on Medium</title>
            <link>https://medium.com/@alok-mishra98?source=rss-33668e5959f2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 21:16:46 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@alok-mishra98/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[All about Redis]]></title>
            <link>https://medium.com/@alok-mishra98/all-about-redis-5670778155a2?source=rss-33668e5959f2------2</link>
            <guid isPermaLink="false">https://medium.com/p/5670778155a2</guid>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <dc:creator><![CDATA[Alok Mishra]]></dc:creator>
            <pubDate>Sat, 14 Nov 2026 11:11:26 GMT</pubDate>
            <atom:updated>2026-11-14T12:18:25.667Z</atom:updated>
            <content:encoded><![CDATA[<p>A hands-on guide to Redis fundamentals – why it is fast, essential commands, replication and clustering, RDB/AOF persistence, and practical use cases you can run locally.</p><p>Redis(<strong>RE</strong>mote <strong>DI</strong>ctionary <strong>S</strong>erver) is an <strong><em>in-memory data structure store</em></strong><em> </em>.i.e. it supports most fundamental data structures like strings, sets, lists, hashes, sorted sets, geospatial indexes, etc. along with probabilistic structures like like HyperLogLog and Bloom filters.</p><p>It keeps everything in memory thus, it doesn’t guarantees durability. It just absorbs the repeated read load thus, it doesn’t replace your database.</p><p>It executes commands <strong>one at a time on single thread</strong>, which makes it both very fast and easy to reason about.</p><h4>How redis is so fast &amp; works well at scale?</h4><blockquote>Sometimes <strong>how Redis is capable of dealing with millions of requests by executing one task at a time on single thread </strong>might excite you. So lets talk about this.</blockquote><p><strong>Redis uses I/O multiplexing</strong> .i.e. one single thread able to tens of thousands client connection simultaneously, thus Redis only processes the sockets/connections for which data is read, meaning it wastes zero time waiting on idle connections.</p><p><strong>Pure In-memory operations: </strong>Unlike traditional databases/stores Redis doesn’t time in waiting for data travel back and forth from the disk.</p><p>It store everything in RAM which takes nano seconds to execute.</p><p><strong>Zero Lock Contention: </strong>Redis executes commands one at a time on single thread, which needs <strong>No Lock</strong>, which means no thread contention, no race conditions, no deadlocks, no CPU lifecycles waste by thread for free up the resource by another thread.</p><h4>Common Commands in Redis</h4><pre>-- strings: direct key/value, O(1) get/set<br>SET foo bar                 -- {foo: bar}<br>SET zoo park                -- {foo: bar, zoo: park}<br>GET foo                      --&gt; &quot;bar&quot;<br>MGET zoo foo                 --&gt; park, bar<br><br>SET india 1<br>INCR india                   -- atomic increment, {india: 2}</pre><pre>-- lists: ordered, push either end, O(1) push/pop<br>LPUSH myfriendslist &#39;Alok&#39;     --&gt; [&#39;Alok&#39;]<br>LPUSH myfriendslist &#39;Akshay&#39;   --&gt; [&#39;Akshay&#39;,&#39;Alok&#39;]<br>RPUSH myfriendslist &#39;Sajid&#39;   --&gt; [&#39;Akshay&#39;,&#39;Alok&#39;,&#39;Sajid&#39;]<br><br>-- LRANGE listName start stop<br>LRANGE myfriendslist 0 -1  --&gt; &#39;Akshay&#39;,&#39;Alok&#39;,&#39;Sajid&#39;</pre><pre>-- hashes: a key maps to a mini object, great for session/profile data<br>HSET user:100 name &quot;Alok&quot; plan &quot;pro&quot;<br>HGET user:100 plan           --&gt; &quot;pro&quot;<br>HGETALL user:100           --&gt; name Alok plan pro<br>HINCRBY user:100 logins 1</pre><pre>-- TTL management, the backbone of caching<br>EXPIRE foo 30              -- expires in 30s<br>TTL foo                     --&gt; seconds left, or -1 (none)<br>PERSIST foo                 -- remove expiry</pre><p>Above commands can be run on Redis CLI. Most of the time we will be connecting Redis instances from our backend code. Our app code never talks raw RESP protocol directly. A client library (Jedis, ioredis, redis-py) owns a connection pool and speaks Redis&#39;s text protocol over TCP on your behalf.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LUxbADJfGwxN5u83zSxhLw.png" /><figcaption>Connecting with Redis Server using Redis Client Library</figcaption></figure><h4>Architectural Topologies supported by Redis</h4><p>Like any other system Redis supports common topologies listed below:</p><p><strong>Single Node(Running mode: Standalone)</strong></p><ul><li>Single Redis server will be serving all the requests.</li><li>❌ Does not support High Availability, Horizontal Scaling and Data sharding</li></ul><p><strong>Master/Replica(Running mode: Replication)</strong></p><ul><li>Master server with High Availability(HA) replica will be serving request, where replicas will be serving read requests.</li><li>Give support for <strong>horizontal scaling for only read requests</strong>.</li><li>Only manual failover is available.</li></ul><p><strong>Monitored Replication(Running mode: Sentinel)</strong></p><ul><li>It is same as Master/Replica with automatic failover.</li><li>If master goes down, using quorum one replica will be promoted to master.</li><li>Give HA with horizontal scaling for only read requests.</li><li>Suitable for the use-case where data is enough to be stored in single node but have heavy read requests.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B4OpakjU0QZXwa1kQikIUg.png" /><figcaption>topologies of Redis</figcaption></figure><p><strong>Multi Master(Running mode:Cluster)</strong></p><ul><li>The keyspace is divided evenly into <strong>16,384 logical hash slots</strong>. Data is automatically partitioned (sharded) across multiple master nodes, each backed by its own replica node</li><li>Every master node in the cluster is assigned a subset of these hash slots.</li><li>Each master node can also have its own local replicas for redundancy.</li><li>Clients use cluster-aware drivers that route requests directly to the correct master node holding the specific hash slot (using MOVED or ASK redirects if necessary).</li><li>Gives HA, scalability for read &amp; writes along with data sharding.</li><li>You cannot perform a single atomic multi-key operation (transactions, MGET/MSET, Lua scripts, etc.) if the involved keys hash to different slots and therefore different shards. Key design therefore becomes an architectural concern. To guarantee co-location, use hash tags {...} to group logically related keys into the same hash slot, ensuring they live on the same shard and can participate in atomic operations. Be mindful that over-grouping can create hot spots, so tags should reflect your actual atomicity boundaries.</li></ul><pre>-- bad: these two keys can land on different shards<br>users:44:cart<br>users:44:orders   -- different hash slot risk<br><br>-- good: {44} is the hash-tag Redis uses for slot calc<br>users:{44}:cart<br>users:{44}:orders  --&gt; same slot, same shard, atomic ops now valid<br><br>-- CAUTION: over-grouping by one hot id can create hot shards.<br>-- Split into sub-shards if one tag gets too much traffic.</pre><h4>Persistence Modes of Redis</h4><p>To prevent total data loss during a crash, Redis offers two persistence modes, both of which come with compromises:</p><ul><li><strong>RDB (Snapshots):</strong> Redis periodically takes a snapshot of your dataset. If the server crashes unexpectedly, you lose every write that happened <em>since the last snapshot</em>.</li><li><strong>AOF (Append Only File):</strong> Redis logs every write command to a log file, but by default, it flushes to disk (fsync) once per second. A crash can still result in losing up to a second of acknowledged writes.</li></ul><h3>Capabilities of Redis</h3><h4>Redis as a Cache</h4><p>Redis is commonly used as a cache across the industry. At its core, it is a direct mapping from a Redis key to a cached value. To keep data fresh, we can set an expiration time or Time-To-Live TTL using commands like EXPIRE.</p><p>Redis doesn’t run a dedicated background timer for every single key to delete it the exact millisecond its time is up. Instead, Redis handles expiration using two complementary strategies:</p><ul><li><strong>Passive Expiration (Lazy Deletion):</strong> When a client tries to access a key, Redis checks its expiration timestamp. If it has expired, the key is deleted on the spot and a nil is returned. The downside? If an expired key is never accessed again, it will sit in memory forever.</li><li><strong>Active Expiration (Periodic Sweeping):</strong> To catch unaccessed dead keys, Redis runs a background clean-up job <strong>10 times per second</strong>. It samples a batch of keys, deletes any expired ones found, and if more than <strong>25%</strong> of that sample are expired, it immediately runs the loop again.</li></ul><p>If memory fills up before keys can expire, Redis evicts data based on your configured <strong>maxmemory-policy</strong>. The most commonly used options in production are <strong>allkeys-lru</strong> (Least Recently Used) and <strong>allkeys-lfu</strong> (Least Frequently Used).</p><h4>Redis as a Distributed Lock</h4><p>When you are dealing with the data which might be accessed by multiple processes and to maintain consistency should not be changed more than one process at a time, in that case you look towards distributed lock.</p><p>You can use redis as a distributed lock manager, where a process before accessing/writing to a row try to create the key and NX makes this SET succeed only if key doesn’t already exist, which means if it fails someone is holding lock to the row. EX 30 just puts the 30 secs expiry on the key, so crashed processed doesn’t hold lock forever.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sccAS0PILkxspcqkqV84kg.png" /></figure><h4>Redis for Leaderboards</h4><p>Suppose you are designing a scoreboard for a cricket tournament where users frequently scores are updated, check the top X players, a particular player’s rank, or players ranked nearby. One approach is to fetch all player scores from the database, sort them, and then retrieve the required results. However, this can be inefficient, as it involves fetching and processing more data than necessary. To handle this efficiently, we can use <strong>Redis Sorted Sets</strong>, which maintain members in sorted order based on their scores. They allow us to retrieve the top X players, find a player’s rank, and fetch players within a specific rank range without sorting the entire dataset for every request. Many of these operations have logarithmic or near-logarithmic time complexity, making Redis Sorted Sets a suitable choice for leaderboards that require frequent score updates and efficient ranking queries.</p><p>Here are examples of how scores are added and how to check score or rank for a particular player and support of queries like top X.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DLHMdaFqGxGrDJi8LavgMw.png" /><figcaption>commands of sorted-set</figcaption></figure><h4>Redis for Proximity Search</h4><p>Redis provides geospatial indexes for storing coordinates and querying nearby locations. These indexes use sorted sets, with longitude and latitude encoded into a Geohash-based score. In this implementation, restaurant metadata is stored separately in Redis hashes.</p><p>I loaded the <a href="https://www.kaggle.com/datasets/mrmars1010/restaurants-dataset-bengaluru">Bengaluru Restaurant Kaggle Dataset</a> locally and added each restaurant’s location to a geospatial index using:</p><p>GEOADD &lt;key&gt; &lt;longitude&gt; &lt;latitude&gt; &lt;restaurant_id&gt;</p><p>Here, &lt;restaurant_id&gt; identifies the restaurant, while its coordinates determine its position in the index.</p><p>For a food delivery app, this allows you to find restaurants within a specified radius of a location: for example, within 5 km using GEOSEARCH or GEORADIUS. Redis documents the query’s time complexity as O(N + log(M)), where N is the number of elements in the grid-aligned bounding box surrounding the search area and M is the number of items within the requested search shape.</p><p>In below snapshot, i have searched the 5 restaurants near by 77.600 longitude and 13.0016 latitude with 15km radius</p><p>In the snapshot below, I used GEOSEARCH and GEORADIUS command to find the 5 nearest restaurants within a 15 km radius of the location at longitude 77.600 and latitude 13.0016</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZYPeyOiJa7jG9MQZqYOYbw.png" /></figure><p>Here is the animation on how data is store in geohash grid in 52 bits(uses 26 bits per axis) and search happens.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*BTdrp78cHMZR_eWzloW35A.gif" /><figcaption>how geo indexes work in Redis?</figcaption></figure><h4>Redis for Event Sourcing</h4><p>Redis streams are append-only logs. Stream is where producers append the items using commands like XADD and consumers groups processes the items from stream(XREADGROUP/XCLAIM). In below snapshot i have discussed how consumer groups are created, how items are added to the stream, how items are processed and acknowledged by consumer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d614rI-aPs261BMjneLYGw.png" /></figure><p>Now suppose a worker(worker-1) processes the message and fails or stuck before acknowledgement, until any other worker claims (XCLAIM/XAUTOCLAIM) it, it will be parked in PLE(Pending List Entries).</p><h4>Day-to-Day Usecase Cheatsheet</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iKNE3tdX7vM4tHC9nkr9Pg.png" /></figure><h4>Common anti-patterns</h4><ul><li><strong>Running </strong><strong>KEYS * in production:</strong> Because Redis operates on a single-threaded event loop, running an O(N) command that scans every key will freeze the entire server, blocking all other clients for seconds or minutes. Using SCAN with a cursor is the correct, non-blocking way to iterate through keys.</li><li><strong>Setting no TTL on cache keys:</strong> If you treat Redis as a cache but never set an expiration, dead data accumulates silently until you hit your memory ceiling. If your policy is left as noeviction, Redis will immediately start throwing OOM errors on writes.</li><li><strong>Leaving </strong><strong>maxmemory-policy as </strong><strong>noeviction for caches:</strong> This is a classic trap. For a cache, you <em>want</em> old data to drop off automatically when space runs out. Leaving it on noeviction means Redis prioritizes failing writes over evicting stale data.</li><li><strong>Giant keys (millions of fields in a hash/list):</strong> Operations on Redis collections are proportional to their size (e.g., O(N)). Pulling or updating a massive hash blocks the main thread. Sharding large collections into smaller chunks prevents these bottlenecks.</li><li><strong>Hot keys in Cluster mode:</strong> In a Redis Cluster, keys are distributed across different nodes based on hash slots. If a single key gets hammered with traffic, that specific shard bears 100% of the load while other nodes sit idle. Solutions like client-side caching or read replicas help distribute that traffic.</li></ul><h4>References</h4><ul><li>Explore <a href="https://poltora.dev/redis">Redis Cit</a>y to see the full simulation of how redis works internally.</li><li><a href="https://www.hellointerview.com/learn/system-design/deep-dives/redis">https://www.hellointerview.com/learn/system-design/deep-dives/redis</a></li><li><a href="https://www.scribd.com/document/273699992/Redis-Cheat-Sheet?v=0.165">Redis Commands Cheatsheet</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5670778155a2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Essential Linear Algebra for Machine Learning: A Quick Reference]]></title>
            <link>https://medium.com/@alok-mishra98/essential-linear-algebra-for-machine-learning-a-quick-reference-ac4120b3fed5?source=rss-33668e5959f2------2</link>
            <guid isPermaLink="false">https://medium.com/p/ac4120b3fed5</guid>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[mathematics]]></category>
            <dc:creator><![CDATA[Alok Mishra]]></dc:creator>
            <pubDate>Wed, 05 Aug 2026 04:27:29 GMT</pubDate>
            <atom:updated>2026-08-05T04:27:29.275Z</atom:updated>
            <content:encoded><![CDATA[<h4>Concise notes that cover vectors, matrices, eigenvalues, and SVD for ML practitioners</h4><h4>Notions</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qU4Tb8-YwCkqHfTRdBzJ1Q.png" /></figure><h3>System of Equations</h3><ul><li>Sentences are represented in the form of algebraic equations</li></ul><pre>Y = W.X + C<br># W = Weight<br># X = Vector of Features<br># C = Vector of Bias</pre><ul><li>When a group of equations has unique solutions, are <strong>Complete</strong> &amp; <strong>Non-Singular</strong></li><li>When a group of equations has infinite solutions, they are <strong>Redundant</strong> &amp; <strong>Singular</strong></li><li>When a group of equations has no solutions, they are <strong>Contradictory</strong> &amp; <strong>Singular</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C3RTMfPkxQBM0AIAnwD_Ow.png" /><figcaption>System of Linear Equations</figcaption></figure><ul><li>If none of the equations is obtained by performing some operations on the other equations, then those are <strong>linearly independent.</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NGmQjoa3IZq3_evTxzXOWw.png" /><figcaption>Linearly Dependent equations are singular, Linearly Independent equations are non-singular</figcaption></figure><h4>Determinant</h4><p>Determinant helps us to determine the singularity of the matrix.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*xwcKz72IhCLq9fQopnGfHw.png" /></figure><p>If <strong>|A| </strong>of any matrix is zero, then the matrix is singular.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OokaR_R_JO0Yf5IFWD3lUw.png" /></figure><h4>Solving Systems of Linear Equations</h4><ul><li>To solve the system of linear equations, we manipulate the equations so that they remain true in the same form.</li><li>We can manipulate equations:<br>- Multiplying/Dividing by a constant<br>- Adding two equations<br>- Swapping the position of rows (changes the sign of the determinant)</li><li>If it is in the form of a matrix, we solve it using:<br>- Row-Reduction/Guassian Elimination</li></ul><h4>Rank of Matrix</h4><ul><li>It tells how much information a matrix is carrying.</li><li>A matrix is non-singular iff the <strong><em>rank of the matrix = no. of rows of the matrix</em></strong></li><li><strong>Application:</strong> Compression of images</li><li>To calculate the rank of a matrix, need to understand row echelon form.</li></ul><h4>Row Echelon Form</h4><ul><li>These are the possible forms: Number of 1’s followed by zeros in the diagonal</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3AeVPbEJPAnn1gKgI6BpkA.png" /><figcaption>Row echelon forms</figcaption></figure><ul><li>To convert any matrix into row echelon form, we perform operations like multiplication/division of a non-zero constant, addition or subtraction between two or more rows.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_XorCkNpeO5VuKiKTm0hlw.png" /><figcaption>Example to convert a matrix to Row Echelon Form</figcaption></figure><ul><li><strong>No. of 1’s in Row Echelon Form = Rank of a Matrix</strong></li></ul><h4>Reduced Row Echelon Form</h4><p>To transform the matrix to Reduced Row Echelon Form, we need to make sure:</p><ul><li>matrix should be in row echelon form</li><li>each pivot is a 1</li><li>any number above pivot is 0</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VZhdSkSOQoUI56EalKU18g.png" /></figure><p>Till this point, to understand if a matrix is singular or not, we were ignoring the constants present on the right side of the equation. i.e., C in Ax+B=C.</p><p>But to solve the system of equations, we need to consider that.</p><p><strong>An augmented matrix</strong> is primarily used to solve linear systems or find matrix inverses. It is a matrix obtained by combining the coefficient matrix and the constant vector of a system of linear equations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HEzhtgIyUA9z87SpXA0M7A.png" /><figcaption>Representation of Augmented Matrix</figcaption></figure><h4>Gaussian Elimination Algorithm</h4><ul><li>Create an augmented matrix</li><li>Get the matrix into reduced row echelon form</li><li>Complete back substitution</li><li>Stop if you encounter a row of 0’s</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*couulK0wK-eIa0H8sVmflg.png" /><figcaption>If we get the row of 0’s</figcaption></figure><p>So far, we have covered the basics how equations are represented in Matrix, how do we solve these equations, but point to consider is we have done most of the operations for 2 or 3 variables whereas in real world we will have lots of variables. For example: <br>In Neural Network n features are involved and each neuron is represented as a small linear model. Imagine each neuron as a tiny calculator that takes in several input values (<strong>features</strong>), multiplies each by a specific <strong>weight</strong>, adds them all up, and then adds a <strong>bias</strong> (a kind of adjustment number). This process can be written simply as W times X plus b <strong>(W*X + b)</strong>, where <strong>W</strong> is the vector of weights, <strong>X</strong> is the input features, and <strong>b</strong> is the bias. This linear combination is then passed through an activation function, which decides the neuron’s output by adding a bit of nonlinearity, helping the network learn complex patterns.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*-Y4amLo_m-yve0p1w63WRA.png" /><figcaption>Neural Network represented as layers of linear models</figcaption></figure><p>So mainly each layer is represented by vectors, matrices and tensors(multi-dimensional). Now we will discuss <strong>how to apply the linear algebra concepts on vectors and matrices</strong>.</p><h3>Vectors</h3><p>Vector is simple array of numbers, just with one column.</p><p>Two main component of vectors are <strong>magnitude(size)</strong> and <strong>direction</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/313/1*qoUvGL3SNLbVWo5N-Doxkg.png" /><figcaption>Notion for Row &amp; Column vector</figcaption></figure><h4>Magnitude of a vector</h4><p>Norm is used to tell about <strong>the size of the vector</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/966/1*6KNSru856Okki5AogmjdKQ.png" /><figcaption>L1-Norm(taxi-cab distance) and L2-Norm(euclidean distance)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/475/1*7a7PXkEqZPDmIcR8ey4DZA.png" /><figcaption>Generalized formula of n dimensional vector</figcaption></figure><h4>Direction of a Vector</h4><p>To find the direction of a 2D vector, use the trigonometric formula</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/128/1*Zh3JYPcCbyntVhFNZ6hJFw.png" /></figure><p><strong>How do we will calculate the direction in multi-dimensional space?</strong></p><ul><li>In 2D, direction is just one angle, but in higher dimensions, direction involves multiple angles or a more complex description because the vector points somewhere in a multi-dimensional space.</li><li>Lets think about 3D space, you are in office and someone ask you about your position, so you tell about the floor and the zone you are sitting in.</li><li>So, in simple words for 3D space, you need two angles — like how you turn left-right and then up-down — to describe where the arrow points.</li><li>For even more dimensions, you need even more angles or use special mathematical tools like unit vectors (vectors with length 1) to represent direction.</li><li><em>Extra knowledge: For even more dimensions, you need even more angles or use special mathematical tools like unit vectors (vectors with length 1) to represent direction. The key idea is to “normalize” the vector by dividing each component by the vector’s length (magnitude), which gives you a vector pointing in the same direction but with length 1. This normalized vector captures the direction in any number of dimensions.</em></li></ul><h4>Use-Case:</h4><ul><li><strong>Context:</strong> In machine learning, especially in recommendation systems (like those used by Netflix or Amazon), each item (movie, product) and each user can be represented as a vector in a high-dimensional space. Each dimension corresponds to a feature, such as genre, price, or user preferences.</li><li>Imagine a user vector with coordinates representing their interest levels in different movie genres.</li><li>An item vector represents the genre composition of a movie.</li><li>Calculating the L2-norm distance between these vectors helps the system recommend movies closest to the user’s taste.</li><li>The direction (angle) between vectors helps understand if two users have similar preferences regardless of how intense those preferences are.</li></ul><h3>Vector Operations</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/947/1*hOAeFvI11z7mTrsjWxLEJA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/985/1*RJbxN2JjzWIUSzp7tS72Xw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/396/1*iMNRwnAOA27V8mcV_PdmNQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*wLbQgPzUDXofqKYinh5p_g.png" /><figcaption>Notion for dot product</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/887/1*JBfhrhkiokmSRlRVi8-qSw.png" /><figcaption>Properties of dot product</figcaption></figure><h4>Application of the Dot Product: Vector Similarity</h4><p>Geometric definition of a dot product is used in one of the applications — to evaluate <strong>vector similarity</strong>. In Natural Language Processing (NLP) words or phrases from vocabulary are mapped to a corresponding vector of real numbers. Similarity between two vectors can be defined as a cosine of the angle between them. When they point in the same direction, their similarity is 1 and it decreases with the increase of the angle.</p><p>To evaluate cosine of the angle between vectors:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/135/1*M6KC5EB_fd77erUzBFQFfw.png" /></figure><p>Zero value corresponds to the zero similarity between vectors (and words corresponding to those vectors). The largest value is when vectors point in the same direction, lowest value is when vectors point in the opposite directions.</p><h3>Linear Transformations</h3><ul><li>A linear transformation sends each point in a plane to another point using matrix multiplication of coordinate vectors.</li><li>The origin always maps to the origin under any linear transformation.</li></ul><p>Examples of Transformation</p><ul><li>Multiplying the matrix by vectors representing points (like (1,0), (0,1), and (1,1)) shows how these points move to new locations.</li><li>The image of a square formed by these points becomes a parallelogram, illustrating how the transformation changes shapes.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*8ySD08q5rDrbkSaUiT1xvQ.png" /></figure><p>Basis and Coordinate Changes</p><ul><li>The original square and the resulting parallelogram are called bases, which cover the entire plane.</li><li>The linear transformation can be seen as a change of coordinates from one basis to another.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r53WI6vymGOTpMesVpsA6A.png" /><figcaption>Bases (left side is original square and right side is resulting parellelogram)</figcaption></figure><h4>Matrix Multiplication</h4><p>Matrix multiplication helps us find the result of applying multiple linear transformations one after another. When you multiply two matrices, you are combining their corresponding transformations into a single transformation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ssmXXR6FO3QTMZELupk8Tw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/818/1*eE-ABa2kq8lKT_4INQLanA.png" /><figcaption>Example of Matrix Multiplication</figcaption></figure><h4>Identity Matrix</h4><p>The dot product of any matrix with the identity matrix is the matrix itself. i.e., <strong>A.I = A</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*97jVoFzMhvHvch1c.png" /></figure><h4>Matrix Inverse</h4><p>The inverse of a matrix is a special matrix that, when multiplied by the original matrix, results in the identity matrix.</p><ul><li>It is like the “reciprocal” of a number (e.g., the inverse of 2 is 1/2).</li><li>For a matrix ( A ), its inverse is denoted as ( A^{-1} ).</li><li>Multiplying ( A ) by ( A^{-1} ) gives the identity matrix ( I ), which acts like 1 in matrix multiplication.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/332/0*RehWFgMkHq4uG3xE.png" /></figure><ul><li>The inverse matrix “undoes” the effect of the original matrix in linear transformations, returning the space to its original state.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BdofrfknOJdOJmLrNFP3Xg.png" /><figcaption>Steps to find inverse of a matrix</figcaption></figure><h4>Singularity &amp; Rank of Linear Transformation</h4><p>If all the points of the plane can be mapped to the transformed plane, then the transformation is non-singular.</p><p>As you see in the second &amp; third examples, linear transformations on those matrices are not mapping the complete plane, so they tend to be Singular.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NwoZDO5OPIC3f21hGKyN7g.png" /></figure><h4>Bases in Linear Algebra</h4><ul><li>A basis consists of vectors that define a space, such as the plane, by originating at the origin.</li><li>The key property of a basis is that every point in the space can be expressed as a linear combination of the basis vectors.</li><li><strong>Not bases:</strong> Two vectors that lie on the same line do not form a basis because they cannot span the entire plane</li><li><strong>Span: </strong>All the points that you are reaching out with give vectors</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/724/1*tH4N7VGWQNQFFJJ8oILQrA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x-VewiwemqJcChlgFEoUNQ.png" /></figure><h4>Eigenvalues &amp; Eigenvector</h4><p>Suppose we have a transformation matrix <strong>A</strong> and a vector <strong>v</strong></p><p>The transformed vector is</p><blockquote><strong>Av = λv</strong></blockquote><p>Normally, after transformation:</p><ul><li>The vector changes <strong>length</strong>.</li><li>The vector changes <strong>direction</strong>.</li></ul><p>But some vectors are special. <strong>Certain vectors do not change direction</strong>.</p><p>They only:</p><ul><li>Stretch</li><li>Shrink (squish)</li><li>Or flip 180° (if the scaling factor is negative)</li></ul><p>These are called <strong>eigenvectors. </strong>The amount of scaling is called the <strong>eigenvalue.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/426/1*7YaF9b-CQGUajf4XVvczbQ.png" /><figcaption>Formal for calculating eigenvalues</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fwSA81QvoDr2VQI2_ne0ng.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iYboHEixBc7RRlbVR7F4BQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yf53P472fJVeEzJPxvBtVg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iniCcofggJH_MQtQbFKwEw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tnTHm9N6TzDaRUlnLDOswA.png" /></figure><h4>Reference:</h4><p>PCA Implementation: <a href="https://colab.research.google.com/drive/1VSkw3VKLEQolJpxDY7ycR4nFK7fkxqPp?usp=sharing">https://colab.research.google.com/drive/1VSkw3VKLEQolJpxDY7ycR4nFK7fkxqPp?usp=sharing</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ac4120b3fed5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Single Instance to Split-Brain: A Database Scaling Journey]]></title>
            <link>https://medium.com/walmartglobaltech/from-single-instance-to-split-brain-a-database-scaling-journey-8b6a27a65023?source=rss-33668e5959f2------2</link>
            <guid isPermaLink="false">https://medium.com/p/8b6a27a65023</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Alok Mishra]]></dc:creator>
            <pubDate>Tue, 31 Mar 2026 18:40:51 GMT</pubDate>
            <atom:updated>2026-03-31T18:40:51.636Z</atom:updated>
            <content:encoded><![CDATA[<p><em>I used to think adding a ‘Read Replica’ was a magic button for scaling applications. I was wrong. While splitting read and write traffic is a standard system design pattern, implementing it introduces a world of pain – from stale reads to the dreaded Split-Brain problem. Here is how database replication actually works, and how to survive the transition.</em></p><p>When people talk about “scaling databases” or “adding read replicas”, they are almost always thinking about one specific architecture:</p><p>Single-leader (Primary-Replica) architecture with asynchronous replication</p><p>This is the architecture used by:</p><ul><li>MySQL + replicas</li><li>PostgreSQL + streaming replication</li><li>Google Cloud SQL</li><li>PlanetScale, Neon, Supabase, etc.</li></ul><p>There is exactly one node that accepts writes → called the <strong>Primary (or Leader/Master).</strong><br>All other nodes are <strong>Read Replicas</strong> → they apply changes from the primary as fast as they can, but always with some delay (replication lag).</p><p>This is the default and dominant model in 99% of applications today.</p><p>Alternative architectures exist (<strong>multi-primary, leaderless, CRDTs</strong>, etc.), but they are rare and come with their own very different trade-offs.</p><p>The second axis that actually matters in practice is:</p><h3><strong>Who manages the replicas and failover for you?</strong></h3><h4>1. Self-hosted / Self-managed</h4><p>You run MySQL or PostgreSQL yourself (on EC2, Kubernetes, bare metal, etc.).</p><p>You are 100% responsible for:</p><ul><li>Setting up replication</li><li>Promoting a new primary when the old one dies</li><li>Routing traffic correctly</li><li>Handling replication lag</li><li>Monitoring, backups, point-in-time recovery, etc.</li></ul><h4>2. Fully-managed cloud services</h4><p>RDS, Aurora, PlanetScale, Neon, Supabase, CockroachDB, Spanner, YugabyteDB, etc.<br>The provider gives you a single connection string (or two: one for writes, one for reads) and magically keeps it pointing to healthy nodes, handles failover in seconds, and often hides (or eliminates) replication lag headaches.</p><p>This second axis is the one that determines how much pain you will actually feel in production.</p><p>Now, suppose you have a naive application with a small user base, and you decide to spin up a single self-managed instance.</p><p>And on the application end, you have provided the DB configurations, and your queries are running on the provided instance.</p><p>Now that your user base has grown exponentially, you, as an architect, observed your query patterns and saw <strong>a read: write</strong> ratio of <strong>100:1</strong>.</p><p>So you decided to make a pivotal decision for your application. And you decided to split your read and write traffic by adding replicas to your database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6Tn7akDf6x0--WOOcmC4tg.png" /><figcaption>Read-Write Split</figcaption></figure><p>Here, the trouble starts. You have two separate endpoints, suppose</p><pre>primary: db.write.endpoint<br>read replica: db.read.endpoint</pre><p>Now the question arises, how will my application know what kind of DB operation it is, and who will decide which endpoint to call?</p><p>Isn’t it thrilling?</p><p><strong>Identifying the kind of transaction is one of the difficult problems.</strong> There is no automatic detection. Industry wide here are few technique which is being used:</p><ul><li>SQL Parsing: Decide the query type based on the keywords</li><li>Annotation Based: Frameworks like Springboot, supports it using Transactional annotation</li><li>Explict connection: While reading or writing, make use of operation specific connection</li><li>Service Layer Separation: Same database schema, same User model, just two services pointing to different database connections</li></ul><p>To read more about it you can check out my article on <a href="https://medium.com/@alok-mishra98/approaches-to-transaction-routing-77c7f64e7092">transaction routing</a></p><p>Among the available approaches, the explicit connection strategy appears feasible for your team and is therefore implemented. For a period of time, the application operates smoothly.</p><blockquote>However, challenges are inevitable in system design.</blockquote><p>Eventually, one of the replicas becomes unavailable, affecting customers. While the change may appear minimal, you must decide whether to replace the failed replica or tolerate downtime until the server is restored, implying a lower emphasis on availability.</p><p>If you see, here are your issues</p><ul><li>Your team didn’t get any notification about the replica failure.</li><li>If the replica goes down, the team has to manually override db endpoint and may require redeployment or a rolling restart, depending on your architecture.</li></ul><p>But damage is already done, so you started thinking about how to get notified about the failure early, or a way to manage it that doesn’t require manual override.</p><h3>How failover can be managed automatically?</h3><p>You started researching, and you came across terms like DB proxy, orchestrator, consensus, and a lot more. Let&#39;s see what fits where</p><p><strong>DB Proxy</strong> is a smart routing tool that watches all the nodes and keeps pointing to healthy nodes, which means it provides failover support. It also does load balancing, caching, and performance optimisation using connection pooling. Commonly used DB proxies are Amazon RDS Proxy, ProxySQL, and PgBouncer.</p><p>But in the case of failure of the primary node, the proxy is not capable of promoting the replica as master or primary.</p><p>So we need someone who can detect the failure on leader and elect one of the replicas as Primary. That&#39;s the role of an <strong>orchestrator</strong>(like Patroni, Vitess) with a centralised coordination service(like zookeeper, etcd).</p><p>Think of it like air traffic control – the orchestrator monitors all planes (database nodes), decides which runway is active (primary), and updates the control tower (Zookeeper). All pilots (DB proxies) check with the control tower to know where to land.</p><p>In the same way, the orchestrator detects the failure, elects who will new primary, and tells the zookeeper. Now the zookeeper keeps the configuration like primary endpoint, replica endpoints, etc. And DB proxy reads the configurations from zookeeper and route the request.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rl1YPqqVRewqbQ65IBtavg.png" /><figcaption>Failover management</figcaption></figure><p>You might be thinking if orchestrator does everything, then why does it need zookeeper?</p><p>To answer this, you first need to understand <strong>Split-Brain problem</strong>.</p><h3>Split-Brain Problem</h3><p>Imagine you have 3 database nodes: A (current primary), B and C (replicas).</p><p>A network partition happens:</p><ul><li>Node A can still talk to nodes B</li><li>Node C is isolated from A and B, but can still talk to the outside world or some applications</li></ul><p>Without protection, two bad things can happen:</p><ol><li>Node A thinks “I’m still primary” → keeps accepting writes</li><li>Node C (or an orchestrator that only sees C) thinks “I can’t reach A → A must be dead → I promote myself/C as new primary”</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RNh9Snjn7XhpG5q2YMxaqQ.png" /><figcaption>Split Brain</figcaption></figure><p>Now you have <strong>two primaries at the same time</strong> accepting writes → data corruption, lost updates, inventory goes negative, money disappears, etc.</p><p>This is split-brain. It is the single worst failure mode in distributed databases. Once it happens, you usually have to shut down one side manually and pray.</p><blockquote><strong>Zookeeper/etcd solves this problem for us</strong>. It uses the <strong>consensus algorithms</strong> like Raft, Paxos to enforces the <strong>strict majority quorum</strong>.</blockquote><p><strong><em>Wait – Consensus? Quorum?</em></strong> 😭</p><p>If seeing those words makes you want to close the tab, don’t worry. We will deep dive into those topics in a separate article. For now, just understand that consensus algorithms are simply the way distributed nodes agree on a single source of truth.</p><p>Let’s look at how far we’ve come. Our system design has evolved significantly:</p><ul><li>Level 1: We started with a naive, self-managed single instance.</li><li>Level 2: As traffic grew, we split Read and Write concerns.</li><li>Level 3: We realized manual failover is a nightmare, so we introduced a DB Proxy.</li><li>Level 4: To solve the “Who creates the new Primary?” problem, we added an Orchestrator and Zookeeper to prevent Split-Brain.</li></ul><p>However, we have ignored the elephant in the room.</p><p>We know how to route traffic, but we haven’t discussed the physics of data movement:</p><ol><li>How do replicas actually receive updates from the Primary?</li><li>What happens when the replica is 5 seconds behind (Replication Lag)?</li></ol><p><em>In Part 2, we will tackle Replication Lag and why it breaks your application logic.</em></p><p><strong><em>Follow me so you don’t miss the next part!</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8b6a27a65023" width="1" height="1" alt=""><hr><p><a href="https://medium.com/walmartglobaltech/from-single-instance-to-split-brain-a-database-scaling-journey-8b6a27a65023">From Single Instance to Split-Brain: A Database Scaling Journey</a> was originally published in <a href="https://medium.com/walmartglobaltech">Walmart Global Tech Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Approaches to Transaction Routing]]></title>
            <link>https://medium.com/@alok-mishra98/approaches-to-transaction-routing-77c7f64e7092?source=rss-33668e5959f2------2</link>
            <guid isPermaLink="false">https://medium.com/p/77c7f64e7092</guid>
            <category><![CDATA[database]]></category>
            <category><![CDATA[database-design]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Alok Mishra]]></dc:creator>
            <pubDate>Thu, 19 Feb 2026 13:27:21 GMT</pubDate>
            <atom:updated>2026-02-19T13:27:21.518Z</atom:updated>
            <content:encoded><![CDATA[<p><em>When you split your database into a primary (writes) and replicas (reads), your application needs to decide where to send each query. This decision related to transaction routing sounds simple, but getting it wrong can crash production. Here are four approaches, each with increasing control and complexity.</em></p><h3>1. SQL Parsing</h3><p>Decide the query type based on the keywords</p><pre>public Connection routeQuery(String sql) {<br>    if (sql.trim().toUpperCase().startsWith(&quot;SELECT&quot;)) {<br>        return readConnection;<br>    }<br>    return writeConnection;<br>}</pre><h4>Problems</h4><ul><li>SELECT...FOR UPDATE effectively acts as a write lock, so it <em>must</em> go to the primary</li><li>Query starts with select but internally uses function or stored procedure which writes the data.</li></ul><h3>2. Annotation Based</h3><pre>@Transactional(readOnly = true)<br>public Data readOperation() { ... }<br><br>@Transactional(readOnly = false)<br>public void writeOperation() { ... }</pre><h4>Problems:</h4><ul><li>If a method marked @Transactional(readOnly = true) is routed to a replica, any write operation inside it will either silently fail or throw an exception — depending on your database and driver configuration. In the worst case, the replica accepts the write attempt, causing data inconsistency.</li></ul><h3>3. Explict Connection Selection</h3><p>While reading or writing, make use of operation specific connection.</p><pre>public class UserService {<br>    private final JdbcTemplate readTemplate;<br>    private final JdbcTemplate writeTemplate;<br>    <br>    public User getUser(Long id) {<br>        // Explicitly use read connection<br>        return readTemplate.queryForObject(<br>            &quot;SELECT * FROM users WHERE id = ?&quot;, <br>            userRowMapper, <br>            id<br>        );<br>    }<br>    <br>    public void updateUser(User user) {<br>        // Explicitly use write connection<br>        writeTemplate.update(<br>            &quot;UPDATE users SET name = ? WHERE id = ?&quot;,<br>            user.getName(),<br>            user.getId()<br>        );<br>    }<br>}</pre><h3>4. Service Layer Separation</h3><p>Same database schema, same User model, just two services pointing to different database connections.</p><pre>// Two services, that&#39;s it<br>@Service<br>public class UserReadService {<br>    private final ReadOnlyDataSource readDB;<br>    <br>    public User getUser(Long id) {<br>        return readDB.query(&quot;SELECT * FROM users WHERE id = ?&quot;, id);<br>    }<br>    <br>    public List&lt;User&gt; searchUsers(String name) {<br>        return readDB.query(&quot;SELECT * FROM users WHERE name LIKE ?&quot;, name);<br>    }<br>}<br><br>@Service<br>public class UserWriteService {<br>    private final PrimaryDataSource writeDB;<br>    <br>    public void createUser(User user) {<br>        writeDB.execute(&quot;INSERT INTO users ...&quot;, user);<br>    }<br>    <br>    public void updateUser(User user) {<br>        writeDB.execute(&quot;UPDATE users SET ...&quot;, user);<br>    }<br>}</pre><p>There’s a 5th approach — CQRS — that takes this even further. It doesn’t just separate connections; it separates models, schemas, and often entire databases. But that deserves its own article.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=77c7f64e7092" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Review: The Accidental CTO]]></title>
            <link>https://medium.com/@alok-mishra98/review-the-accidental-cto-c8748d7ceb3d?source=rss-33668e5959f2------2</link>
            <guid isPermaLink="false">https://medium.com/p/c8748d7ceb3d</guid>
            <category><![CDATA[database]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Alok Mishra]]></dc:creator>
            <pubDate>Wed, 18 Feb 2026 17:19:15 GMT</pubDate>
            <atom:updated>2026-02-18T17:19:15.636Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oLQi-AGluCpS23wEtTP3Gg.png" /></figure><p>I’ve been reading this book over the past few weeks to make the most of my travel time. Before picking it up, I had no idea about Dukaan or its author, Subhash Choudhary.</p><p>Initially, I thought it was just a publicity stunt, but it gradually captured my full attention. Every chapter comes with a thrill “Ab kya naya fata hoga” (what’s going to break next?) and a question: what could they have done differently to fix it?</p><p>Subhash explains every topic in a way that even a non-CS person can understand. Later, I discovered the reason behind his art. He himself was a non-CS graduate who was entirely self-taught. When you learn from experience, you don’t just write about things; you make them resonate. That was evident throughout the book.</p><p>While reading, there were many moments where I questioned my own fundamentals. As an exercise, I went deeper into those topics and tried to solidify my understanding. The book addressed questions I had long been uncertain about:</p><ul><li>When to use a task/worker queue over a P2P queue</li><li>How to scale reads and writes</li><li>How read-write traffic splitting works</li><li>Anycast and global routing</li><li>How to leverage edge computing to reduce latency</li><li>And much more</li></ul><p>Above all, the book introduces an ideology rarely discussed: cost over tech, making decisions driven by cost-efficiency rather than chasing the shiniest technology.</p><p>I’m thankful to my teammate <a href="https://www.linkedin.com/in/hi-apurba/">Apurba</a> for recommending this. If you’re early in your career and want a practical understanding of system design, I highly recommend it.</p><p>Book link: <a href="https://github.com/subhashchy/The-Accidental-CTO/blob/main/The%20Accidental%20CTO%20Book.pdf">https://github.com/subhashchy/The-Accidental-CTO/blob/main/The%20Accidental%20CTO%20Book.pdf</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c8748d7ceb3d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Part 1: Tokenizer]]></title>
            <link>https://medium.com/@alok-mishra98/part-1-tokenizer-8e384ba9f74f?source=rss-33668e5959f2------2</link>
            <guid isPermaLink="false">https://medium.com/p/8e384ba9f74f</guid>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[agents]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Alok Mishra]]></dc:creator>
            <pubDate>Mon, 25 Aug 2025 16:52:42 GMT</pubDate>
            <atom:updated>2025-08-25T16:52:42.164Z</atom:updated>
            <content:encoded><![CDATA[<p>Welcome to the <em>Agentic Learning Series</em> — a step-by-step journey into how intelligent AI agents are built. In this post, we’ll start with one of the foundational concepts: the tokenizer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7jnfZpUvkr8_1_RWEG-sfQ.png" /></figure><p>If you’re overwhelmed by terms like agents, LLMs, MCP, and GenAI — and don’t know where to start — you’re in the right place</p><p>Consider an <strong>LLM(Large Language Model)</strong> as a 1-year-old child whom you are trying to teach how to speak.</p><p>First, they learn the alphabet, then words, then sentences. Eventually, they can read, write, and make intelligent decisions.</p><p>In the same way, LLM needs a dictionary of tokens.</p><p>In an LLM, any input — whether it’s a sentence, word, code, or special character — is broken down into <strong>tokens</strong>. Each token has a fixed (deterministic) ID from the model’s vocabulary.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gtkK-WDzvCs4NHAZx3JH3Q.png" /></figure><p>In above example, if you notice the 3rd and 8th indices of our token list are <strong>“ I”, </strong>and the token ID is 358, which shows the deterministic nature of the dictionary.</p><p>So, LLM is a type of AI model trained on a massive amount of data to understand and generate human language.</p><p>Since computers <strong>don’t understand raw human language</strong>. So, to process the input LLMs need a tokenizer that <strong>converts input into something it understand: tokens</strong>.</p><pre>import tiktoken<br><br>def explore_tokenization():<br>    &quot;&quot;&quot;Demonstrate how texts are tokenized.&quot;&quot;&quot;<br>    <br>    # Initialize tokenizer for GPT models<br>    encoding = tiktoken.encoding_for_model(&quot;gpt-3.5-turbo&quot;)<br>    <br>    test_texts = [<br>        &quot;Hello, I am Alok. I am gonna to make agentic learning series easy for you.&quot;,<br>        &quot;It will be divided into chucks which can be consumed easily.&quot;,<br>        &quot;Your feedbacks are welcome.&quot;,<br>        &quot;Stay tuned 🔔. Emojis takes more tokens&quot;,<br>    ]<br>    <br>    print(&quot;=== TOKENIZATION EXPLORATION ===\n&quot;)<br>    <br>    for text in test_texts:<br>        tokens = encoding.encode(text)<br>        decoded_tokens = [encoding.decode([token]) for token in tokens]<br>        <br>        print(f&quot;Original text: {text}&quot;)<br>        print(f&quot;Token count: {len(tokens)}&quot;)<br>        print(f&quot;Tokens: {decoded_tokens}&quot;)<br>        print(f&quot;Token IDs: {tokens}&quot;)<br>        print(&quot;-&quot; * 50)</pre><p>Play around with the above code and see how it works.</p><h3>FAQs</h3><ul><li><strong>Do every model uses same tokenizer?</strong><br>No ❌, Each model family has its own tokenizer:<br>GPT-3.5/GPT-4: Use cl100k_base encoding (BPE-based)<br>GPT-3: Uses p50k_base encoding<br>Claude models: Use their own proprietary tokenizer<br>LLaMA: Uses SentencePiece tokenizer<br>BERT: Uses WordPiece tokenizer<br>Worry not, these are currently present LLMs in market.</li><li><strong>Does there are any limitation in amount of tokens which LLM can process?</strong><br>Yes ✅, each model have its own token limit.</li></ul><h3>Summary</h3><p>Tokenizers are the first step in helping LLMs understand language. They break down text into machine-readable chunks (tokens), each mapped to a unique ID. Different models use different tokenizers, and each model has its own limit on how many tokens it can process.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8e384ba9f74f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Database Locks: Ensuring Data Integrity]]></title>
            <link>https://medium.com/@alok-mishra98/mastering-database-locks-ensuring-data-integrity-28b0b944297a?source=rss-33668e5959f2------2</link>
            <guid isPermaLink="false">https://medium.com/p/28b0b944297a</guid>
            <category><![CDATA[transactions]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[concurrency]]></category>
            <dc:creator><![CDATA[Alok Mishra]]></dc:creator>
            <pubDate>Wed, 23 Apr 2025 12:05:15 GMT</pubDate>
            <atom:updated>2025-04-23T12:05:15.876Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>In this article, we explore a crucial aspect of database management: handling concurrency to ensure data integrity. Using a common application scenario, we’ll learn how database-level locking mechanisms — specifically, pessimistic locking — can be a reliable solution to support database inconsistencies that arise when scaling an API to multiple instances.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yBpjGBqOhDa4PkBA-Y89Ww.png" /></figure><p>Imagine you’re building a Flight Booking system which has an API exposed to a UI of users with access to book a seat. You develop the API to parse incoming requests and update the database, as per the example basic schema below.</p><figure><img alt="Basic schema for our Flight Booking API, in reality it is much more complex depending on the system" src="https://cdn-images-1.medium.com/max/1024/1*W_v5FxL3oBXxAeKY8sLmLw.png" /><figcaption>Basic schema for our Flight Booking API, in reality it is much more complex depending on the system</figcaption></figure><h4>Basic Implementation</h4><p>When you started developing your API, you had a single instance of service running in production. As such, your developed API looked like this:</p><pre>// CONTROLLER<br>@Operation(summary = &quot;Booking API&quot;)<br>@PostMapping(&quot;/booking-request&quot;)<br>public ACESResponse upsertBookingRequest(@RequestBody RequestBO requestBO) {<br>    return  flightBookingService.bookingRequest(requestBO);<br>}<br><br>// SERVICE<br>public CustomResponse bookingRequest(RequestBO requestBO) {<br>  // here you need to read the flight details<br>  Flight flight = flightRepository.getFlightById(requestBO.getFlightid());<br>  // then reduce regular seats, consider user allowed to book only one seat<br>  flight.setRegularSeats(flight.getRegularSeats()-1);<br>  flightRepository.save(flight);<br>  <br>  // do other stuff, like insert request details<br>  // return response <br>}</pre><p>So far, everything works smoothly … as long as users aren’t accessing your APIs at the same time. Problems occur <strong>when multiple users try to request your APIs simultaneously</strong>, like when two or more people search for the same flight.</p><h4>Lock Based Implementation for Single Instance</h4><p>As an experienced programmer who studied Operating Systems focused on concurrency and multi-threading, you included <strong>locks/synchronization</strong> in your program. Your service looked like this:</p><pre>// SERVICE<br>public CustomResponse bookingRequest(RequestBO requestBO) {<br><br> synchronized(this){<br>    // here you need to read the flight details<br>    Flight flight = flightRepository.getFlightById(requestBO.getFlightid());<br>    // then reduce regular seats, consider user allowed to book only one seat<br>    flight.setRegularSeats(flight.getRegularSeats()-1);<br>    flightRepository.save(flight);<br>  }<br>  // do other stuff, like insert request details<br>  // return response<br>}</pre><p>Your solution worked for the single instance you had running.</p><p>Shortly after, you received a request for multiple instances to <strong>enhance availability and accommodate sudden spikes in traffic through an auto-scaling strategy</strong>. Eager to implement this change, you <strong>launched an additional instance of your service</strong>. Immediate reads seemed promising.</p><p>However, you soon received an escalation that more tickets were confirmed than seats available.</p><h4>Case Analysis</h4><p>Lets start digging together what happened right now.</p><ul><li><strong>Case 1:</strong> When you have single instance running, <strong>only one request is allowed to execute the critical section at a time.</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r7GfSfe-aGnqQLso6_7H3Q.png" /><figcaption>Single Instance of service</figcaption></figure><ul><li><strong>Case 2:</strong> When you have multiple instances of your service running, <strong>each instance will allow a request to execute the critical section at a time</strong>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I-4bxQFg6fnYrqnBZpaLAg.png" /></figure><p>If both servers receive the same request, both will be allowed to access the critical section and perform the updates in the database, resulting in an inconsistent db state. <strong>The</strong> <strong>Isolation level was compromised in the ACID property.</strong> (<a href="https://medium.com/@salimian/phantom-reads-the-hidden-problem-in-your-db-and-how-to-prevent-it-by-selecting-the-best-isolation-7ec74f966156">Suggested read</a>)</p><h3>How do we handle concurrency?</h3><p>There are many solutions such as <strong>Transactions</strong>, <strong>Locking Mechanisms</strong> (Pessimistic Locking and Optimistic Locking), <strong>Distributed Locks, and Queue-Based Architecture. </strong>We’ll focus on the locking mechanism Pessimistic Locking.</p><h4>Concurrency Control/Locking Mechanisms</h4><p>Locking mechanisms ensure data consistency and prevent deadlocks.</p><ul><li><strong>Pessimistic Locking: </strong>Lock is acquired for exclusive use by a transaction, preventing access to other transactions until the lock is released.</li><li><strong>Optimistic Locking:</strong> Allows multiple instances to read but checks for conflicts before committing an update.</li></ul><h4><strong>Pessimistic Locking</strong></h4><blockquote>Let’s explore the resources you can leverage to acquire a lock, as well as an example for Azure SQL Server.</blockquote><p>Depending on the use case, you’ll need to choose the resource:<strong> Table or Row</strong>.</p><p><strong>Use case for Table-Level Locks: </strong>Bulk insert, updates, or delete operations.</p><p><strong>Use case for Row-Level Locks:</strong> Reading, updating, or deleting a particular condition (specific rows).</p><p>Let’s have a look to flow diagram of locking mechanism.</p><ul><li>When a task/operation needs a lock, it asks for the lock. If the lock is acquired, the operation is performed and once complete, the lock is released.</li><li>If the lock is not acquired, it will retry until it reaches the max limit or timeout, before throwing an error.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*036WLhHEW1YMfXRfEYiwpg.png" /><figcaption>Flow diagram of acquiring and releasing lock</figcaption></figure><p>Azure SQL Server provides the stored procedure to acquire(<a href="https://learn.microsoft.com/en-us/sql/relational-databases/system-stored-procedures/sp-getapplock-transact-sql?view=sql-server-ver16"><strong>sp_getapplock</strong></a>) and release lock(<a href="https://learn.microsoft.com/en-us/sql/relational-databases/system-stored-procedures/sp-releaseapplock-transact-sql?view=sql-server-ver16"><strong>sp_releaseapplock</strong></a>).</p><ol><li>Query to acquire the lock:</li></ol><pre>-- QUERY TO GET LOCK<br>DECLARE @result int<br><br>EXEC @result = sp_getapplock <br>@Resource = &lt;RESOURCE_PLACEHOLDER&gt;, @LockTimeout = &lt;TIMEOUT&gt;,<br>@LockMode = &#39;Exclusive&#39;, <br>@LockOwner = &#39;Session&#39;;<br><br>SELECT @result AS result;</pre><p>In the above query,<em> @result</em> will contain whether the lock was acquired or not.</p><ul><li>0: The lock was acquired successfully.</li><li>1: The lock was granted successfully after waiting for other incompatible locks to be released.</li><li>-1: There was an error in acquiring the lock (e.g., invalid parameters).</li></ul><p>2. Query to release the acquired lock:</p><pre>-- QUERY TO RELEASE LOCK<br>DECLARE @result int;<br><br>EXEC @result = sp_releaseapplock @Resource = &lt;RESOURCE_PLACEHOLDER&gt;, <br>@LockOwner = &#39;Session&#39;;<br><br>SELECT @result AS result;</pre><p>The value of @result will indicate whether the lock was successfully released or if there was an issue:</p><ul><li>0indicates lock<strong><em> </em></strong>was successfully released</li><li>-999indicates a parameter validation or other call error.</li></ul><p>3. <strong>&lt;RESOURCE_PLACEHOLDER&gt;</strong> is crucial as it defines what is being locked—this could be a specific row, a table, or a combination of keys based on your locking strategy.</p><ul><li>Locking row with primary key: <strong><em>&lt;table_name&gt;:&lt;columns_id&gt;</em></strong></li><li>Locking row with composite keys: <strong><em>&lt;table_name&gt;:&lt;columns_1_id&gt;:&lt;columns_2_id&gt;:&lt;columns_3_id&gt;.</em></strong></li></ul><blockquote>Tip: Ensure consistency of column order across your project.</blockquote><p>4. <strong>LockMode </strong>can be Exclusive or Shared</p><ul><li><strong>Exclusive</strong> if both reads and writes are not allowed while lock is acquired,</li><li><strong>Shared </strong>if only reads are allowed while lock is acquired<strong>.</strong></li></ul><h4>Utility<strong> for Locking Mechanism</strong></h4><p>Let’s write a utility for a locking resource. Our goal will be to acquire a lock &gt; run the task &gt; release lock upon task completion.</p><ul><li><strong>executeWithLock: </strong>This method is a main block of code where we run a task when a lock is acquired, and we attempt to release the lock once the task is complete.</li></ul><pre>public void executeWithLock(String resourceName, Runnable task) {<br>    // try-with-resources block is used to Automatically manages connection lifecycle<br>    try (Connection connection = getConnection()) {<br>      if (acquireLock(connection, resourceName, 200L)) {<br>              log.info(&quot;LOCK IS ACQUIRED for resource: {}&quot;, resourceName);<br>              try {<br>                  task.run(); // Run the provided task<br>              } finally {<br>                  // Attempt to release the lock after running the task<br>                  boolean lockReleased = releaseLock(connection, resourceName);<br>                  log.info(&quot;LOCK IS RELEASED, successful: {}&quot;, lockReleased);<br>              }<br>      }<br>    } catch (SQLException e) {<br>        log.error(&quot;Error occurred while acquiring lock or running task&quot;, e);<br>        throw new LockAcquisitionException(&quot;SQL error during lock acquisition for resource: &quot; + resourceName, e);<br>    } catch (Exception e) {<br>        log.error(&quot;Unexpected error occurred&quot;, e);<br>        throw new LockAcquisitionException(&quot;Unexpected error during lock acquisition for resource: &quot; + resourceName, e);<br>    }<br>}<br><br></pre><ul><li><strong>acquireLock:</strong> This returns the boolean value depending on if the lock is successfully acquired or not.</li></ul><pre>public boolean acquireLock(Connection connection, String resourceName, Long timeoutInMs) {<br>    try (PreparedStatement preparedStatement =<br>                 getPreparedStatement(<br>                         connection, LockQueryUtils.ACQUIRE_LOCK, resourceName, timeoutInMs);<br>        ResultSet resultSet = preparedStatement.executeQuery()) {<br>        if (resultSet.next()) {<br>            int result = getResultFromResultSet(resultSet)<br>             // Return true only if the lock is acquired<br>            return result &gt;= 0; // Lock acquired successfully<br>        }<br>    } catch (SQLException e) {<br>        log.error(<br>                &quot;Failed to acquire lock for resource : {}&quot;,<br>                resourceName,<br>                e);<br>    }<br>    return false;<br>}</pre><ul><li><strong>releaseLock:</strong> This returns the boolean value depending on whether the lock is successfully released or not.</li></ul><pre>public boolean releaseLock(Connection connection, String resourceName)  {<br>        try (PreparedStatement preparedStatement =<br>                     getPreparedStatement(connection, LockQueryUtils.RELEASE_LOCK, resourceName);<br>            ResultSet resultSet = preparedStatement.executeQuery()) {<br>            if (resultSet.next()) {<br>                int result = getResultFromResultSet(resultSet)<br>                return result == 0;// Lock released successfully<br>            }<br>        } catch (SQLException e) {<br>            log.error(<br>                    &quot;Failed to release lock for resource : {}&quot;,<br>                    resourceName,<br>                    e);<br>        }<br><br>        return false;<br>    }</pre><ul><li><strong>acquireLock</strong> and <strong>releaseLock</strong> use helper functions. Specifically, <strong>getPreparedStatement </strong>to obtain the PreparedStatement, and getResultFromResultSet, that with the above query, returns the value of @resultfrom resultSet.</li></ul><h4>How to use Utility</h4><pre>public void doSomeOperation(){<br>  Runnable dBtaskToRun = ()-&gt;{<br>    // perform some operation which is related to locked resource ...<br>  };<br>  <br>  String resourceToLock = &quot;flightTable:123&quot;; // 123 is the flight id<br>  lockResourceUtility.executeWithLock(resourceToLock, dBtaskToRun);<br>}</pre><h4><strong><em>Cautions</em></strong></h4><ul><li>If you are writing your own utility, ensure you review and test that your connection is properly established and closed, if you are not using <strong>try-with-resources.</strong></li><li>Choose a locking strategy that best suits your use case.</li><li>Utilities that process a large number of requests require a more advanced architecture design. As such, this solution works best with small-scale designs.</li><li>If a developer <strong>forgets to release the lock</strong> or <strong>close the connection</strong>, it can lead to <strong>serious issues</strong> in a multi-threaded environment. Let’s break it down:</li></ul><h4>Potential Problems</h4><h4>1. Lock Not Released (Deadlock)</h4><ul><li>If a thread acquires a lock but <strong>fails to release it</strong>, other threads waiting for the same lock will be <strong>blocked indefinitely</strong>, leading to a <strong>deadlock</strong>. This can cause:</li><li><strong>System slowdown</strong> (due to blocked threads).</li><li><strong>Resource starvation</strong> (no other threads can proceed).</li><li><strong>Potential service outage</strong> (if the lock is crucial).</li></ul><h4>2. Connection Not Closed (Connection Leak)</h4><ul><li>If a connection is <strong>not closed</strong>, it remains <strong>open</strong> in the <strong>connection pool</strong>. Over time, this can:</li><li><strong>Exhaust available connections</strong>.</li><li>Cause <strong>performance degradation</strong>.</li><li>Lead to <strong>“Too many connections” errors</strong> (DB connections are limited).</li></ul><h4><strong>Conclusion</strong></h4><p>In conclusion, mastering database locks is essential for maintaining data integrity in concurrent applications. This article demonstrated how pessimistic locking can effectively prevent inconsistencies that arise from simultaneous requests. By implementing a locking mechanism, we ensure that only one transaction can access a critical section at a time, thereby upholding the ACID properties of the database. While this approach offers a reliable solution, it’s important to choose the right locking strategy for your specific use case and to rigorously test your implementation to avoid potential pitfalls. With a solid understanding of locking mechanisms, developers can enhance the robustness of their applications and ensure a seamless user experience, even under heavy load.</p><h4>Additional resources</h4><ul><li><a href="https://learn.microsoft.com/en-us/sql/relational-databases/system-stored-procedures/sp-getapplock-transact-sql?view=sql-server-ver16">Azure Stored Producer Documentation</a></li><li><a href="https://medium.com/@salimian/phantom-reads-the-hidden-problem-in-your-db-and-how-to-prevent-it-by-selecting-the-best-isolation-7ec74f966156">To understand isolation levels</a></li><li><a href="https://www.youtube.com/watch?v=I8IlO0hCSgY&amp;t=223s">Optimistic vs Pessimistic Locking by Naseer</a></li><li><a href="https://www.youtube.com/watch?v=K6KyWzZS3Eg&amp;pp=ygUNc3BfZ2V0YXBwbG9jaw%3D%3D">Error Handling during Concurrency Control</a></li><li><a href="https://www.baeldung.com/java-try-with-resources">Java try-with-resources</a></li></ul><p><strong>Sources: </strong>Images drawn with <a href="https://excalidraw.com/">excalidraw</a> and schemas built with <a href="https://dbdiagram.io/">DBDiagram</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=28b0b944297a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Broken Double Check Locking]]></title>
            <link>https://medium.com/@alok-mishra98/load-balancer-part-2-d703f22d0231?source=rss-33668e5959f2------2</link>
            <guid isPermaLink="false">https://medium.com/p/d703f22d0231</guid>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[jvm]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[multithreading]]></category>
            <dc:creator><![CDATA[Alok Mishra]]></dc:creator>
            <pubDate>Sun, 22 Sep 2024 14:51:27 GMT</pubDate>
            <atom:updated>2024-09-22T22:43:54.581Z</atom:updated>
            <content:encoded><![CDATA[<p>In the last <a href="https://medium.com/@alokmishra_24225/load-balancer-feedback-received-part-1-a14199a937d4">article</a>, I had asked what is wrong with below code snippet.</p><pre>// singleton pattern<br>public class Configuration {<br>    private static Configuration instance;<br>    public String[] servers;<br>    public BalancingStrategy balancingStrategy;<br>    public HashSet&lt;String&gt; activeServers;<br><br>    private Configuration(String[] value, BalancingStrategy balancingStrategy) {<br>        this.servers = value;<br>        this.balancingStrategy = balancingStrategy;<br>        this.activeServers = new HashSet&lt;&gt;();<br>    }<br><br>    public static Configuration getInstance(String[] url, BalancingStrategy balancingStrategy) throws IOException {<br>        if(instance==null){<br>            synchronized (Configuration.class){<br>                if(instance==null){<br>                    instance = new Configuration(url, balancingStrategy);<br>                }<br>            }<br>        }<br>        return instance;<br>    }<br>  ..... getter and setter <br>}</pre><p>Before discussing what is wrong with our Double Check Locking and why? I will give you some glance what is Double Check Locking and why is it needed?</p><h4>Double Check Locking</h4><p>While writing a thread safe Singleton class, we can’t simply write this</p><pre>public class Configuration {<br>    ... instance variables and constructor<br><br>    public static Configuration getInstance(String[] url, BalancingStrategy balancingStrategy) throws IOException {<br>        <br>        instance = new Configuration(url, balancingStrategy);<br>        return instance;<br>    }<br>  ..... getter and setter <br>}</pre><p>If you are new to Multi-threaded programing then you might be thinking why it is? Okay, have some patience in next 5 mins it will be clear.</p><p>Now consider 2 Threads .i.e. T1 and T2 are trying to call <strong>getInstance</strong> at the same time, as there is no synchronization defined yet both end up creating their instances. So, <strong>Idea of Singleton is broken 🙄</strong></p><p>So our problems are:</p><ul><li><strong>Don’t want to create another instance if one is already there</strong></li><li><strong>Can’t allow more then two threads in our Object instantiation section</strong>, we can treat this as our <strong>Critical Section</strong></li></ul><p>To solve these problems, we can make use of <strong>Synchronized</strong> keyword (to define our critical section) and <strong>Lazy Initialization </strong>(to make sure object is created only when it is required or not yet created).</p><pre>public class Configuration {<br>    ... instance variables and constructor<br><br>    public static Configuration getInstance(String[] url, BalancingStrategy balancingStrategy) throws IOException {<br>        // our critical section<br>        synchronized (Configuration.class){<br>              // Lazy Initialization<br>              if(instance==null){<br>                  instance = new Configuration(url, balancingStrategy);<br>              }<br>        }<br>        return instance;<br>    }<br>  ..... getter and setter <br>}</pre><p>Now in above snippet we added one more issue, doesn’t matter instance is initialized or not, every time when someone call the <strong>getInstance </strong>method lock has to be acquire, which makes no sense, right?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*McN0eoOoNePObSyD.gif" /></figure><p>So, to solve this issue we check one more time if instance is initialized or not. If not, then only thread is allowed to acquire lock. This is what <strong>Double Check Locking</strong> is.</p><p>Lets, jump back to our main discussion, <strong>Why our Double Check Locking is broken ?</strong></p><h4>Problem 1: Reordering of Instructions by Compiler</h4><p>Java compiler and JIT allowed to reorder the instructions for the better CPU utilizations. Here is how it works</p><ul><li>Object Instantiation underhood consists the serveral instructions like <strong>creation of empty object</strong>, <strong>initializing the fields</strong> and <strong>assigning object to variable</strong> (in our case instance)</li><li>To optimizes the CPU utilization, compiler reorder the instructions.</li></ul><p>Now, consider there are 2 threads T1 and T2 trying to excecute our critical section.</p><ol><li>When T1 trying to instantiate object, it just able to perform the <strong>empty object creation and initializes to the variable. </strong>And it sleeps for sometime.</li><li>Meanwhile T2 got chance to go into critical section, it sees the instance is already created. So, T2 don’t create a new instance.</li><li>T1 preempted before initializing the fields and T2 read the instance (with field initialization), it may lead to the failure of program or invalid states.</li></ol><h4>Problem 2: Not having visibility among other threads</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/407/0*uLGFA-MOgxkZyy1K.png" /><figcaption>JMM(Java Memory Model)</figcaption></figure><p>Consider the scenerio when one Thread create a object and put the changes back to <strong>main memory.</strong> Meanwhile other thread come to our critical section and it reads the instance value from thread memory/cache and will not able to find the instance, which is again a problem.</p><p>To solve these problems, we need to mark <strong>instance </strong>as <strong>Volatile.</strong></p><p>In Java, <strong>Volatile </strong>keyword gurantees that <strong><em>No reordering of instruction will happen </em></strong>and <strong><em>it ensures that changes are visible among all the threads .i.e. </em></strong><em>values for a volatile variable will be read from Main Memory not from Thread Cache</em></p><h4>References:</h4><p><a href="https://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html">https://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html</a><br><a href="https://javarevisited.blogspot.com/2011/06/volatile-keyword-java-example-tutorial.html">https://javarevisited.blogspot.com/2011/06/volatile-keyword-java-example-tutorial.html</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d703f22d0231" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Load Balancer: Feedback Received(Part 1)]]></title>
            <link>https://medium.com/@alok-mishra98/load-balancer-feedback-received-part-1-a14199a937d4?source=rss-33668e5959f2------2</link>
            <guid isPermaLink="false">https://medium.com/p/a14199a937d4</guid>
            <category><![CDATA[load-balancing]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[multithreading]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <dc:creator><![CDATA[Alok Mishra]]></dc:creator>
            <pubDate>Tue, 10 Sep 2024 18:18:33 GMT</pubDate>
            <atom:updated>2024-09-11T06:47:00.372Z</atom:updated>
            <content:encoded><![CDATA[<p>Last week I have implemented a load balancer from scratch. If you are wondering where so please checkout here <a href="https://github.com/i-m-alok/Load_Balancer">https://github.com/i-m-alok/Load_Balancer</a> and I have asked for feedback to many senior engineer and plus roles.</p><p>And I’m amazed that I got so many feedback. Before that I was thinking I write pretty awesome code but no it is pity code. In this article, I will share the feedbacks which I have received so far.</p><p>But before starting this I will give a chance to figure out few issues with this snippet</p><figure><img alt="Find out the bad coding practices or mistakes" src="https://cdn-images-1.medium.com/max/1024/1*M4xiEw3tqmKtA4q9IwoWMg.png" /></figure><p>Lets start,</p><h4>1. Ordering of keywords</h4><p>Silly one, If you are a experienced definitely you will laugh on this.</p><pre>public volatile static int pointer;</pre><p>If are you unable to find out what is wrong with this then worry not. Basically the order of <strong>volatile</strong> and <strong>static</strong> keyword is wrong.</p><p>In Java, the correct order for declaring a variable with multiple modifiers is to place the access modifier first, followed by other modifiers such as static and volatile. This follows the standard convention where modifiers are ordered as follows:</p><ol><li>Access modifier (e.g., public, protected, private)</li><li>Other modifiers (e.g., static, final, volatile)</li><li>Data type</li><li>Variable name</li></ol><p>If want to know more please checkout this <a href="https://checkstyle.sourceforge.io/apidocs/com/puppycrawl/tools/checkstyle/checks/coding/DeclarationOrderCheck.html">documentation</a>.</p><h4>2. Initializing Static Variable in Constructor</h4><p>I’m assuming if you are taking a valuable time to read this then you are a Software Engineer and you are aware of <strong>Static</strong> variables.</p><p>In Java, <strong>Static </strong>variables should be initialized either in <strong><em>static block</em></strong> or in <strong><em>static method.</em></strong></p><h4>3. Use of not using a thread safe data structures</h4><p>As so far you could have guessed this is a Round Robin Algorithm which is used for a load balancing strategy and as load balancer can have concurrent request which leads to looking for the server to divert the request for this our <strong>getNextRoute </strong>can be called by multiple threads.</p><p>So, we need to make sure our code is thread safe. To achieve it, it is suggestable to use <strong>Atomic Classes</strong>(like AtomicInteger) and <strong>Concurrent Collections (</strong><a href="https://sites.cs.ucsb.edu/~cappello/190B/resources/rc061-010d-java_concurrency_0.pdf"><strong>cheatsheet</strong></a><strong>)</strong></p><h4><strong>4. Synchronizing the getNextRoute method</strong></h4><p>It is just due to Domino effect. As I have used normal <strong>int </strong>so to ensure that is thread safe I have considered method as <strong>synchronized </strong>which can lead to performance issue.</p><h4>Task for you, criticize it :P</h4><p>Review the below piece of code and mention the issues which you see. Just a clue I have used <strong>Double Check Locking</strong> here, will share about it in next article.</p><pre>// singleton pattern<br>public class Configuration {<br>    private static Configuration instance;<br>    public String[] servers;<br>    public BalancingStrategy balancingStrategy;<br>    public HashSet&lt;String&gt; activeServers;<br><br>    private Configuration(String[] value, BalancingStrategy balancingStrategy) {<br>        this.servers = value;<br>        this.balancingStrategy = balancingStrategy;<br>        this.activeServers = new HashSet&lt;&gt;();<br>    }<br><br>    public static Configuration getInstance(String[] url, BalancingStrategy balancingStrategy) throws IOException {<br>        if(instance==null){<br>            synchronized (Configuration.class){<br>                if(instance==null){<br>                    instance = new Configuration(url, balancingStrategy);<br>                }<br>            }<br>        }<br>        return instance;<br>    }<br>  ..... getter and setter <br>}</pre><p>Special thanks to <a href="https://www.linkedin.com/in/gaurav-massand/">Gaurav Masand</a> for reviewing it.<br>Kudos to you for reading it :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a14199a937d4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Everything You Need to Know About Manifest Files]]></title>
            <link>https://medium.com/@alok-mishra98/everything-you-need-to-know-about-manifest-files-7bb0a8873d17?source=rss-33668e5959f2------2</link>
            <guid isPermaLink="false">https://medium.com/p/7bb0a8873d17</guid>
            <dc:creator><![CDATA[Alok Mishra]]></dc:creator>
            <pubDate>Sat, 31 Aug 2024 14:24:56 GMT</pubDate>
            <atom:updated>2024-08-31T14:24:56.699Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*PtxWBf5F3xcLN7allgjA0Q.png" /></figure><p>As a developer — whether you’re into front-end, back-end, full-stack, or DevOps — you’ve probably encountered issues such as “No entry point found,” “Version Mismatch,” or “Missing Dependency.”</p><p>If this sounds familiar, you may have spent countless hours on Stack Overflow or scratching your head, trying to figure out what’s going wrong. 🤯 I’ve been there too. However, you’ll be relieved to know that understanding the Manifest file can help pinpoint these issues more effectively. While I can’t guarantee you’ll find the exact line of code causing the problem, you’ll at least be able to identify which file is the culprit. 😜</p><p>Let’s start, majorly these issues are caused by <strong>Manifest file, </strong>either due to absense or corrputed manifest. But how? what the hell this manifest does?</p><h4>What are Manifest files ?</h4><p>Manifest file is the file which contains the metadata or configuration information about a software. You will see it in different technologies with different names like</p><p>In <strong>Java(MANIFEST.MF)</strong></p><ul><li>It is generally placed under “META-INF”</li><li>It contains the informations like your software version, JDK specifications, main-class or entry point for your application</li></ul><pre>Manifest-Version: 1.0<br>Build-Jdk-Spec: 1.8<br>Created-By: Maven JAR Plugin 3.3.0<br>Main-Class: com.wc_cli.Main</pre><p>In <strong>Javascript(Package.json)</strong></p><ul><li>It contains the dependency, scripts to run, software related info, etc.</li></ul><pre>{<br>  &quot;name&quot;: &quot;my-cli&quot;,<br>  &quot;version&quot;: &quot;1.0.0&quot;,<br>  &quot;main&quot;: &quot;index.js&quot;,<br>  &quot;scripts&quot;: {<br>    &quot;start&quot;: &quot;node index.js&quot;<br>  },<br>  &quot;dependencies&quot;: {<br>    &quot;express&quot;: &quot;^4.17.1&quot;<br>  }<br>}</pre><p><strong>Android (AndroidManifest.xml):</strong> For Android apps, the AndroidManifest.xml file contains essential information about the app, including its components and permissions.</p><p><strong>WebApps (manifest.json):</strong> In web applications, the manifest.json file provides metadata about the app, such as its name, icons, and theme color.</p><p><strong>Python (setup.cfg/pyproject.toml):</strong> In Python projects, setup.cfg and pyproject.toml files store configuration details and dependencies.</p><h4>Why does Manifest file required?</h4><p>Manifest files are essential because they contain vital project information, such as:</p><ul><li>Project entry points</li><li>Compiler information</li><li>Dependencies</li><li>Scripts and more (depending on the technology)</li></ul><p>As a software engineer, understanding how to work with Manifest files across different tech stacks is crucial for troubleshooting and project configuration. Familiarity with these files helps ensure that your applications run smoothly and without unexpected issues.</p><p>Stay tuned : )</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7bb0a8873d17" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>