<?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 Sambhav Mahajan on Medium]]></title>
        <description><![CDATA[Stories by Sambhav Mahajan on Medium]]></description>
        <link>https://medium.com/@sambhavmahajan?source=rss-b93a7af22711------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*DDJiuBaPPMUIXuyUOUiSQw.jpeg</url>
            <title>Stories by Sambhav Mahajan on Medium</title>
            <link>https://medium.com/@sambhavmahajan?source=rss-b93a7af22711------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 20:04:49 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sambhavmahajan/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[Correct way to configure HikariCP]]></title>
            <link>https://sambhavmahajan.medium.com/correct-way-to-configure-hikaricp-75a01fb20aa2?source=rss-b93a7af22711------2</link>
            <guid isPermaLink="false">https://medium.com/p/75a01fb20aa2</guid>
            <category><![CDATA[spring-data-jpa]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[hikaricp-tuning]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[hikaricp]]></category>
            <dc:creator><![CDATA[Sambhav Mahajan]]></dc:creator>
            <pubDate>Mon, 16 Nov 2026 11:28:16 GMT</pubDate>
            <atom:updated>2026-11-16T11:28:16.720Z</atom:updated>
            <content:encoded><![CDATA[<p><em>There are many reasons your Spring Boot application is slow, one such reason is improper pooling. When we run a SQL query using Spring Data JPA or even JDBC, we first have to open a connection if not open yet, this takes time and hence causes your application to be slow, the connection then also needs to be closed(if this can not be idle). In this article we will be exploring how to correctly configure the configurations, although this article is mostly opinionated, i hope that this article may help you find your correct configuration.</em></p><p><strong>Important parameters</strong></p><pre>maximumPoolSize     max allowed connections.<br>minimumIdle         minimum connections that should always be opened.<br>connectionTimeout   max time a new connection attempt can take<br>idleTimeout         time a connection can sit inactive before it is closed</pre><h3>Maximum Pool Size</h3><p>Before we move further, we first have to understand a connection thread is an I/O thread, meaning it is not responsible for computations but rather I/O process such is executing SQL queries. More formally threads that spend significant time waiting for external resources are called I/O threads. Having an optimal number for maximum pool size is very crucial, opening too many your database might not be able to handle, opening too little, there would be too much context switching. Turns out we have a formula for finding the optimal number of I/O heavy threads. The following formula is not usually used for connection pooling, but i think it is worth thinking about it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/431/1*36EX0VOpjGsXOftp2s96og.png" /><figcaption>Optimal I/O threads</figcaption></figure><p>Here, C refers to number of cores of the machine, U cpu utilization ratio, never use U = 1, always use U&lt; .90, idealy 0.8–0.9, W is wait time for IO process, T is the time spent on compute tasks.</p><p>You could calculate median W and median T, and then use those them in the formula. Example: C = 8, U = 0.8, W = 20ms, T = 7 ms.</p><p>8*.8*(1 + 20/7) ≈ 25 connections</p><h4>Documentation Formula</h4><p>PostgreSQL <a href="https://wiki.postgresql.org/wiki/Number_Of_Database_Connections">documentation</a> provides a formula for pool sizing as well and is the recommended way to do so.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cxOXtCxrzMi-eDxq5pBRiQ.png" /><figcaption>Number of connections</figcaption></figure><p>effective spindle count here refers to spindle_count*(1 — cacheHitRatio), and also 1 HDD = 1 Spindle, for SSD its not defined(i don’t know why).</p><h4><strong>Little’s law</strong></h4><blockquote>long-term average number of customers (<em>L</em>) in a stationary system is equal to the long-term average effective arrival rate (<em>λ</em>) multiplied by the average time that a customer spends in the system (<em>W</em>).<br>- Wikipedia</blockquote><p>Basically number of customers(connections) equals effective arrival rate(throughput) multiplied by latency.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/466/1*ant6SWZO9pI2ytJSA2hYgw.png" /></figure><p>For a system with 100 Million daily active users, 100000000/(24*60*60) ≈ 1160 users per second, or 100 Million concurrent on a bad day(not possible in a ideal system). Say mean throughput of each query is 60 ms. Therefor, L = 1160*60/1000 ≈ 70 connections. However, this doesn’t takes into consideration peak loads, for that you have caching and other methods.</p><h3>Minimum IDLE Time</h3><p>HikariCP recommends not setting minimum idle time for maximum performance. By default, minimum idle is equal to maximum pool size, effectively making the pool fixed-size. However if you still want to do so, you can use any of the above formula and use lowest metrics of values in formula, but its not recommended.</p><h3><strong>Connection Timeout and </strong>IDLE Timeout</h3><p>Before this, you should know what kind of data are you trying to query, if the data needs to be highly available, use a higher timeout(10 seconds–10 minutes), else use a lower timeout(1–30 seconds). Furthermore, if your application prefers strong consistency, you might prefer higher timeouts. Ideally, your IDLE Timeout should be greater than Connection Timeout. If your application is write heavy, prefer higher idle timeout and higher connection timeout.</p><h3>Concurrent Limiter</h3><p>Always implement a concurrent limiter, basically it limits number of requests that can take place at single time. We can implement this in Java without any fancy package using Semaphores</p><pre>Semaphore semaphore = new Semaphore(N, true);<br>void work() {<br>  boolean locked = false;<br>  try {<br>    locked = semaphore.tryAquire();<br>    someExpensiveWork();<br>  } finally {<br>    if(locked) semaphore.release();<br>  }<br>}</pre><p>This limits too many requests coming at one time, not everything can be fixed with correct configuration of connections, some problems are not meant to be solved with it.</p><h3>Final Thoughts</h3><p>Whatever you are configuring, be it HikariCP or anything else, always remember to use actual measured data instead of relying on some assumed data for your configurations. There is no fixed formula, but these formulas can actually help to base a foundation for the actual required numbers. Production is messy, think about worst case scenario for your system and remember not to over engineer your solution, keep it stupid and simple.</p><p>Your queries can not become faster just because you are configuring your pool ‘correct’, connection pooling solves a different problem, problem of connection establishment and closing optimally. If your queries are slow, you could introduce caching, maybe use indexes in database. Also, remember, you are allowed to use multiple databases for a single application. Use Cassandra for high write throughput data, or other databases based on your requirement. Always remember, experience is the best teacher, no one in the world can teach you experience, you have to learn it through failures. There is no correct way to configure HikariCP but a poorly thought strategy is always incorrect.</p><h3>Thanks</h3><p>This marks the end of my second article, i hope you enjoyed it. I am still learning, if you spot a mistake, please correct me in the comments. I do hope you learned something new or at least found the article interesting enough for a casual read.</p><p>You can find me on <a href="https://github.com/sambhavmahajan/">GitHub</a> and <a href="https://www.linkedin.com/in/sambhavmahajan/">LinkedIn</a>, i am very active on linkedin these days. I hope you say hi!.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=75a01fb20aa2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Guide to Program]]></title>
            <link>https://sambhavmahajan.medium.com/guide-to-program-14f819da6f77?source=rss-b93a7af22711------2</link>
            <guid isPermaLink="false">https://medium.com/p/14f819da6f77</guid>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Sambhav Mahajan]]></dc:creator>
            <pubDate>Sat, 14 Nov 2026 08:06:51 GMT</pubDate>
            <atom:updated>2026-11-14T08:15:05.009Z</atom:updated>
            <content:encoded><![CDATA[<p>So, a little background. I started programming in 2017, and my first programming language was C#, which I learned from Brackeys’ YouTube channel. Although I don’t use C# much today and, frankly, can’t write functioning C#, it made me who I am as a programmer. I am not a professional software engineer neither i claim to be, i just want to give back. I am currently a student, and this is kind of my first article, so please bear with me. My current tech stack is Java, Spring Boot, and Docker. However, most of the things in the article won’t require mastery over any language. This article(one of many hopefully) represents some of the insights i have gained over the years by consuming content on the internet. I have learned many things online. I believe it’s time I start giving back instead of just consuming knowledge.</p><h3>Defensive Programming</h3><p>One of the most important aspects of programming is being defensive about your code. Defensive means never trusting other developers with your code, and always handling for invalid inputs. I always use something called the validate, collect and act pattern. I took inspiration from the AAA pattern in unit testing.</p><pre>void method(parms) throws Exception {<br>  validateParameters();<br>  var element = collectRequiredStates(parms);<br>  element.performAction();<br>}</pre><h4><strong>Why this pattern</strong></h4><p>If someone forgot to validate parameters, our program might end up inconsistent, or behave incorrectly. Collecting or parsing everything else before we perform any actions ensure nothing is null and everything works smoothly. Using this pattern simplifies debugging to some extent, as we would now where to look when debugging and what are the correct assumptions at that point.</p><h3>Boolean Integer Expressions</h3><p>I learned this pattern from Sara Spalding (Formally Shaun Spalding) from Youtube. Although its not an actual pattern, it helps to write code that is self documenting if written correctly. Usually something like this</p><pre>void func(bool pressUp,<br>       bool pressDown, bool pressLeft, <br>         bool pressRight, int speed, GameObj player) {<br>  <br>   int dx = speed*(int)pressLeft - speed*(int)pressRight;<br>   int dy = speed*(int)pressDown - speed*(int)pressUp;<br>   player.moveBy(dx, dy);<br>}</pre><p>‘press’ here refers to if key pressed on keyboard. In the snippet above you may observe that, opposite directions such as left and right cancel each other out, if neither is being pressed, no movement. Although one might argue we could use two separate if statements, but this achieves the same without compromising for readability much. Just felt like this seemed cool to share.</p><h3>Compatibility Issues</h3><p>Usually when we write software or configure dependencies, we try to fetch the latest versions of everything.</p><h4><strong>Why this is a bad habit</strong></h4><p>Code can be deprecated, if we use modules from external libraries and they get deprecated, our code might break, and we won’t be able to build the same project that built perfectly before. That’s why you should mention versions in your dependencies. We can use the latest dependencies available at the time, but make sure the versions are mentioned. However, if a library has been updated due to security issues, it is worth changing the version, and it is encouraged.</p><h3>Refactoring Hell</h3><p>Three months ago, I was reviewing code for my project, CrowPing, an uptime monitor. Basically, it had a bug: it was calling a @Transactional method from within the same class, if you don’t use Spring Boot or don’t know what a transaction is. Basically, a transaction is a unit of SQL queries grouped into one, following something called the ACID properties. In Spring Boot, you cannot directly call a method annotated with transactional within the same class, as it’s done through a Spring proxy, call it through the Spring-managed bean. If i wanted to fix this, i would have needed to refactor my whole code, as many things were dependent on it. So instead of refactoring my codebase, i did something simple, i copied the method that was causing issues and made it as into another service, now i simply called that method from the object of that service. Instead of refactoring we should always try to find minimal fixes that does the intended task at hand. Simple and stupid is the key.</p><h3>Early Return Pattern</h3><p>Instead of having multiple nested if statements which hinders readability, we should utilize the early return pattern. Early return basically means exiting as soon as a condition is met. Furthermore, instead of nesting the conditions, we can combine them with &amp;&amp; for more readability.</p><pre>// Bad practice<br>if(c1) {<br>  if(c2) {<br>    if(c3) p1();<br>    else p2();<br>  }<br>  else if(c4) p3();<br>}<br><br>// Good practice<br>if(!c1) return;<br>if(c1 &amp;&amp; c2 &amp;&amp; c3) p1();<br>else if(c1 &amp;&amp; c2 &amp;&amp; !c3) p2();<br>else if(c1 &amp;&amp; c4) p3();</pre><p>This makes the condition look explicit and self documenting, for reading the first code we would have to first understand the structure, but for second, everything is already clear, the advantage of this method is that edge cases could be found while reviewing the code before production.</p><h3>Naming</h3><p>One of the most hardest things in programing is what to name things in variables, our code should be self documenting, you shouldn’t need comments on code. Make your methods or variables have meaning.</p><p>For example</p><pre>boolean isOk();<br>//bad name<br><br>boolean isPayloadValid()<br>//good name</pre><p>Furthermore, naming can become messy for things like cache, if we have not correctly defined conventions for it, we might pay dearly for it later in the future.</p><h3>Abstraction is your friend</h3><p>Rewriting the wheel can be a good exercise if you are trying to learn the fundamentals, however you don’t want your software to be buggy because of the modules you wrote, and the bugs could simply have been avoided if we used an already built library, these libraries are already tried and tested, don’t over complicate things, abstraction is your friend. You may only implement your own modules if there is a specific need for it and your requirements call for it. For example, there are already semaphore locks in java, there is already an Atomic Integer in java, don’t try to make one yourself. Not only is it messy and slow, it is not secure, a decade old supported library have far fewer bugs or are identified and fixed periodically.</p><h3>Project Secrets</h3><p>Project secrets refers to sensitive credentials, these could be your database or even API credentials. It’s crucial that these are stored in a manner that does not exposes them publicly. Common ways include, .env files, system environment variables and secrets manager. If we expose our credentials publicly these might become a problem, every API call costs money, if someone malicious gets their hands on those keys, they might cost us money. That is a problem, hence why project secrets must be stored in a secure way. Furthermore, consider adding .env to .gitigore so that you don’t accidentally push your secrets to GitHub.</p><h3>Immutable Strings</h3><p>Usually in programming languages, strings are immutable, meaning their internal value never changes after creation. Hence, it might be a good idea to cache the strings. Strings being immutable has its own issue, consider you are building string like this</p><pre>for(char c : s) {<br>  ret += c; // new string object created<br>  if(condition) {<br>    ret += c; // new string object created<br>  }<br>}</pre><p>This causes huge performance issues, you might think time complexity is O(n) of this string building, but rather it is O(n²) as when we try to concat a character, we don’t modify the string in place, but rather create a new string. First overhead is allocating new memory, then the string to be made is copied in memory. This does not looks incorrect, but it is not, but rather it is inefficient. This is one of the reasons why to use abstraction, you should understand it, not implement it.</p><h4>Solution</h4><p>Use vectors in C++ and then build string or use StringBuilder or StringBuffer in Java. Many languages should have something similar to StringBuilder, if not, just make an array and copy its content to the String object.</p><pre>string f() {<br>  vector&lt;char&gt; v;<br>  string s = &quot;something&quot;;<br>  for(char c : s) {<br>    if(cond) v.push_back(c);<br>    v.push_back(c); // O(1) average, O(n) worst case<br>  }<br>  return string(v.begin(), v.end()); //copy to a new string object<br>}</pre><p>This is O(n). Internally, vector in c++ have a capacity and a current size, when the capacity gets full, new array is allocated capacity of 2*capacity. Insertion is just arr[currentSize] = ele. Although this could have been simply solved by using push_back of string function in c++, i believe it was kinda of necessary to point out this approach.</p><h3>Flatten 2D array to 1D</h3><p>Flattening 2D array to 1D just means, representing 2 dimensional arrays indices, (i, j) as a single 1D index k. Many problems can be solved by flattening 2d to 1d, such as 74. Search a 2D Matrix</p><p>Consider given a 2d array matrix, n number of rows and m number of columns, define flatten index(i, j) = i*m + j, now consider we have flatten index k, what if we mod it by m, (i*m mod m + j mod m) = j, since, i*m is always zero, and j is always less than m, hence j, now what if we divide it by m, (i*m/m + j/m) since j is always &lt; m, j/m is zero, since i*m/m = i, we get flattenIndex/m = i. Hence define</p><pre>int flatten(int i, int j) {<br>  return i*m + j;<br>}<br><br>int row(int index) {<br>  return index/m;<br>}<br><br>int column(int index) {<br>  return index % m;<br>}</pre><h3>Thanks</h3><p>That’s it for this one. I’m still learning, so if you spot a mistake or have a better way to do something, tell me in the comments. I’d love to learn from you too.</p><p>You can find me on <a href="https://github.com/sambhavmahajan/">GitHub</a> and <a href="https://www.linkedin.com/in/sambhavmahajan/">LinkedIn</a>. If this helped you, a clap or a follow means a lot, and more articles are on the way.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=14f819da6f77" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>