<?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 Mohan T on Medium]]></title>
        <description><![CDATA[Stories by Mohan T on Medium]]></description>
        <link>https://medium.com/@tmohan064?source=rss-417845e57142------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*JLi4oTrwBoeiQe8w</url>
            <title>Stories by Mohan T on Medium</title>
            <link>https://medium.com/@tmohan064?source=rss-417845e57142------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 14:59:27 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tmohan064/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[Ruby Threads & ThreadPool]]></title>
            <link>https://medium.com/@tmohan064/ruby-threads-threadpool-2653ca451d8d?source=rss-417845e57142------2</link>
            <guid isPermaLink="false">https://medium.com/p/2653ca451d8d</guid>
            <dc:creator><![CDATA[Mohan T]]></dc:creator>
            <pubDate>Mon, 03 Apr 2023 07:14:05 GMT</pubDate>
            <atom:updated>2023-04-03T07:14:05.554Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello Ruby community !! In this blog , we are going to look into the Thread Pool feature provided by the concurrent-ruby gem. Before jumping into the ThreadPool , let’s first understand why it is needed.</p><p>Ruby program usually gets executed in a single thread. Statements in your ruby code gets executed sequentially. For example</p><pre>api_call_1 # Takes 10 seconds<br>api_call_2 # Takes 10 seconds<br>puts &quot;Hello world!!&quot;  # Printed after 20 seconds</pre><p>In the above code, api_call_2 waits until api_call_1 gets finished. Lets assume that api_call_1 and api_call_2 are independant. We can save 10s of our execution time if we make the call to happen in concurrently.</p><p><strong>Threads in Ruby</strong></p><p>Ruby threads are a lightweight and efficient way to achieve parallelism in your code. When you have multiple unit of work that can happen independently or waiting for external events(I/O bounds) to complete , Ruby thread comes in handy.</p><p>We can spin up multiple Threads and assign an unit of work to each thread which can happen in parallel. If we modify our code to run api calls in multiple threads , we can save 10s of execution time.</p><pre><br>thread_1 = Thread.new do<br>  api_call_1  # Takes 10 seconds<br>end<br><br>thread_2 = Thread.new do<br>  api_call_2 # Takes 10 seconds<br>end<br><br><br># Blocks the main Thread to wait till 2 thread  finishes<br>thread_1.join<br>thread_2.join<br><br>puts &quot;Hello world!!&quot;</pre><p>Wohoo , we reduced the time. Important thing to note here is, both threads didn’t execute in parallel . Both thread started, ran, and completed in overlapping time periods which is called as “<strong>Concurrency</strong>” .</p><p><strong>Advantages of using Threads</strong></p><ol><li>Thread shares the same memory and address space.</li><li>Faster execution .</li></ol><p><strong>Disadvantages</strong></p><ol><li>Control can be switched between threads anytime and it can create a chaos and thus leading to race condition.</li><li>Things will go worse if same resource is shared by the multiple Threads. Implementation of locking mechanism (Mutex, Monitor ) is required.</li></ol><p><strong>ThreadPool</strong></p><p>We can’t keep on creating Threads in our application as it leads to <strong>“can<em>’t create Thread: Resource temporarily unavailable” error. </em></strong>We need to limit the number of active threads that can be created by our application and properly manage threads. We can build our own ThreadPool but there are several gems out there which can be used.</p><p><strong>Concurrent Ruby</strong></p><p>Concurrent Ruby’s ThreadPool is a simple and easy to use framework which manages the threads and avoids deadlock and race condition problems. We can modify the above example to use concurrent-ruby gem.</p><pre><br>require &#39;benchmark&#39;<br>require &#39;concurrent-ruby&#39;<br><br>executor = Concurrent::ThreadPoolExecutor.new<br><br>executor.post{ api_call_1 }<br>executor.post{ api_call_2 }</pre><p><strong>Limiting Active Threads using concurrent Ruby</strong></p><p>Based on your requirement and system capacity , identify how many active threads needed for you in any given point of time and configure the options. Behind the scenes, concurrent-ruby does all the hard work for you .</p><pre>pool = Concurrent::ThreadPoolExecutor.new(<br>  min_threads: 5,<br>  max_threads: 10,<br>  max_queue: 10,<br>  fallback_policy: caller_run<br>)</pre><p>Lets see what these each config options is capable of doing</p><p><strong>min_threads</strong></p><p>Setting <strong>min_threads </strong>to 5 will keep on creating threads until it reaches 5. Afterwards if any background job comes, it looks for any active thread which doesn’t have job. If so, it will allocate that job to that thread. Else it create new threads.</p><p><strong>max_threads</strong></p><p>Setting <strong>max_threads </strong>to 10 won’t create a new Thread beyond that 10. A new requested task has to wait in the queue until any threads becomes available.</p><p><strong>max_queue</strong></p><p>Setting <strong>max_queue </strong>to 100 states that only 100 background jobs can wait in the queue. Any more background job request will be handled based on the fallback_policy settings.</p><p><strong>fallback_policy</strong></p><p>fallback_policy has 3 options. It is basically what should happen when a new task request comes when queue is full</p><p>abort : Silently fail the task .</p><p>discard: Raise an exception.</p><p>caller_run: Execute in the caller context.</p><p><strong>Conclusion</strong></p><p>Instead of creating raw threads and managing it, its better to rely on some proven ruby gems which provides ThreadPool feature such as celluloid, workers. Alright! Its cool , isn’t it ? No need to make your application sit idle for I/O Bound. Start a thread in background and execute work while waiting for I/O Bound and improve your application response time.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2653ca451d8d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating Proxy server for postgres using Toxiproxy]]></title>
            <link>https://medium.com/@tmohan064/creating-proxy-server-for-postgres-using-toxiproxy-fdeb7dd8b204?source=rss-417845e57142------2</link>
            <guid isPermaLink="false">https://medium.com/p/fdeb7dd8b204</guid>
            <dc:creator><![CDATA[Mohan T]]></dc:creator>
            <pubDate>Tue, 22 Nov 2022 07:59:44 GMT</pubDate>
            <atom:updated>2022-11-22T07:59:44.224Z</atom:updated>
            <content:encoded><![CDATA[<p>Imagine your application has a lot of Single points of failure . So, if anything fails, your entire application will stop working.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Ftenor.com%2Fembed%2F26506450&amp;display_name=Tenor&amp;url=https%3A%2F%2Ftenor.com%2Fview%2Fthe-website-is-down-gif-26506450&amp;image=https%3A%2F%2Fmedia.tenor.com%2FHGNWwf_qZpUAAAAd%2Fthe-website-is-down.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=tenor" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/444a0dafd6531b7c41e9786debbba94c/href">https://medium.com/media/444a0dafd6531b7c41e9786debbba94c/href</a></iframe><p>How to be confident that your application doesn’t have single points of failure ? 🤔</p><p>Probably writing tests is one way where you tamper services (eg: postgres, redis, mysql server) and see how your application behaves.</p><p>Okay, “how to tamper services?” might be the next question. Well there comes Toxiproxy.</p><p>Before proceeding to the Toxiproxy introduction, lets take a look into the below scenario.</p><h4><strong>Scenario</strong></h4><p>Imagine you have an application communicating with the database. In local environment, you have database server and application hosted on the same machine. Your application will quickly communicate with database server and provide you the results. But when it comes to production environment, for some reason( eg: your database and application might be in different region) you may notice the network latency/ delay.</p><p>In this blog post, will see how to make use of Toxiproxy to introduce latency to our postgres database server.</p><h4><strong>Introduction to Toxiproxy</strong></h4><p>Toxiproxy is failure testing tool which is used to improve the resiliency of our application. Using Toxiproxy , we can simulate the network condition as it is in production for our development environments.</p><p>Please read here for getting more information on <a href="https://github.com/Shopify/toxiproxy#toxiproxy">Toxiproxy</a></p><h4>Installing Toxiproxy</h4><p>Here is how to setup Toxiproxy service in your Mac system,</p><p>With <a href="https://brew.sh/">Homebrew</a>:</p><pre><br>$ brew tap shopify/shopify<br>$ brew install toxiproxy</pre><p>For installing toxiproxy in other operating systems, Please refer <a href="https://github.com/Shopify/toxiproxy#1-installing-toxiproxy">here</a>.</p><h4><strong>Pre-requiste</strong></h4><ol><li>Before proceeding, make sure to install postgres on your machine and run the database server on port 5432.</li><li>Make sure to start the Toxiproxy service. You can do it in Mac terminal by running the below command</li></ol><pre> brew services start toxiproxy</pre><p>You will see the following output in the terminal</p><pre>==&gt; Successfully started `toxiproxy` (label: homebrew.mxcl.toxiproxy)</pre><h4>Creating Toxiproxy client</h4><p>Let’s create a proxy server which will run on port 22220 for the postgres database server running on port 5432.</p><p><strong>Note: Make sure that your system doesn’t run anything on port 22220 .</strong></p><p>Toxiproxy client can be created in the command line using the below command</p><pre>toxiproxy-cli create -l localhost:22220 -u localhost:5432 postgres_proxy</pre><p>Once created, run</p><pre>toxiproxy-cli ls</pre><p>and you should see the following.</p><pre>toxiproxy-cli ls                                                        <br>Name             Listen            Upstream     Enabled  Toxics<br>======================================================================================<br>postgres_proxy  127.0.0.1:22220 localhost:5432  enabled  None</pre><p>Thats it. We created our first proxy server.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Ftenor.com%2Fembed%2F14367253&amp;display_name=Tenor&amp;url=https%3A%2F%2Ftenor.com%2Fview%2Felmo-shrug-i-dont-know-whats-next-gif-14367253&amp;image=https%3A%2F%2Fmedia.tenor.com%2Fnj8BSzkK6dIAAAAC%2Felmo-shrug.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=tenor" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/bbc4b1eef7a0373fe6279aea69182256/href">https://medium.com/media/bbc4b1eef7a0373fe6279aea69182256/href</a></iframe><h4>Adding Toxic to proxy server</h4><p>So far, we have created a proxy server running on port 22220. Now lets introduce latency to the proxy server using the following command</p><pre>toxiproxy-cli toxic add -t latency -a latency=6000 postgres_proxy</pre><p>Above command adds 6000 milliseconds latency to our proxy server.</p><h4>Creating database, table and inserting record.</h4><p>Alright its time to verify . Firstly, we will create sample records in the database. Execute the following commands.</p><pre>psql postgres -p 5432 <br>CREATE DATABASE &quot;toxiproxy&quot;;<br>\c toxiproxy<br>CREATE TABLE users(name text, email text); <br>INSERT INTO users values(&#39;John Maxi&#39;, &#39;john@maxi.com&#39;); </pre><p>All set. We have the records in our database.</p><h4>Seeing it in action</h4><p>Execute user’s query in both postgres database server and proxy server and notice the behaviour.</p><p>First, run it on postgres database server.</p><pre>psql toxiproxy -p 5432<br>SELECT * from users;</pre><p>Next run it on proxy server running on 22220</p><pre>psql toxiproxy -p 22220 -h 127.0.0.1<br>SELECT * from users;</pre><p>You would have observed delay for 6 seconds before getting the results when connected to the proxy server.</p><p>Hurray ! we have sucessfully simulated the latency using the postgres proxy server.</p><h4>What’s next</h4><p>That’s pretty much it for this post. In my upcoming post, will cover how to use this proxy server in rails application with few example test cases.</p><p>Thanks for reading 🙂</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fdeb7dd8b204" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>