<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">

  <title><![CDATA[Venkatesh CM]]></title>
  <link href="http://venkateshcm.com/atom.xml" rel="self"/>
  <link href="http://venkateshcm.com/"/>
  <updated>2014-06-08T20:10:38+05:30</updated>
  <id>http://venkateshcm.com/</id>
  <author>
    <name><![CDATA[Venkatesh CM]]></name>
    
  </author>
  <generator uri="http://octopress.org/">Octopress</generator>

  
  <entry>
    <title type="html"><![CDATA[Web Applications Caching]]></title>
    <link href="http://venkateshcm.com/2014/06/Web-Application-Cache/"/>
    <updated>2014-06-08T00:00:00+05:30</updated>
    <id>http://venkateshcm.com/2014/06/Web-Application-Cache</id>
    <content type="html"><![CDATA[<p>In <a href="http://venkateshcm.com/2014/05/Caching-To-Scale-Web-Applications/">Caching To Scale Web Applications</a>, we looked at ways to cache page response to url request by setting http cache headers to enable upstream systems to cache, mostly treating web application as black box. In this post we will look at</p>

<ul>
<li>Cache scopes</li>
<li>Caches Policies</li>
<li>Caching storage strategies and implications on performance</li>
</ul>


<p><b><i>Web Application Caching</i></b></p>

<p>Caching within web application can be done at different scope and granularity.</p>

<p>Some well know (common) ways of caching in web application is based on scope of cached values</p>

<ol>
<li>Session Cache :&ndash; Cached value is stored per key per user and cached values are used for a single user. For example :&ndash; User home country.</li>
<li>Application Cache :&ndash; Cached value is stored per key and cached values are used for multiple users. For example :&ndash; List of countries.</li>
</ol>


<p>Session cache&rsquo;s Time To Live (TTL) is usually in minutes while Application cache&rsquo;s TTL varies widely and usually cached forever until changed with application events or business triggers.</p>

<p>Application cache is memory efficient compared to Session cache, as same cached values is used by multiple users in application cache. But if the cached value is personalized data for a specific user, it should stay in Session Cache.</p>

<p>While Session Cache has been used a lot (sometime abused), Application cache is not widely used.</p>

<p><b><i>Cache Policies</i></b></p>

<ul>
<li><p>Write-through : Cache is updated along with backing datastore synchronously. Since both datastore and cache is always kept in sync, Write-through provides high data integrity and consistency at the cost of performance. Write-through caching makes sense with read heavy applications with very few writes.</p></li>
<li><p>Write-back : Cache is updated synchronously and backing datastore is updated asynchronously. Since only cache is updated synchronously Write-back provides better performance but at the cost of inconsistency or data loss in an event of crash. Write-back caching policy makes sense when there is large number of writes and lossing latest data does not effect application.</p></li>
</ul>


<p>As you can see detecting and handling cached value modification is very important. In fact, it is good practice to make all cached values immutable.</p>

<p><b><i>Cache strategies</i></b></p>

<p>Below are different cache storage options available</p>

<ul>
<li>In-memory cache : cached values are stored in RAM memory.

<ul>
<li>(a) in-process : caching with-in application process</li>
<li>(b) out-of-process : caching in another process</li>
</ul>
</li>
<li>Persistent cache : caching in persistent systems like files or database.</li>
</ul>


<p>To choose caching option, we have to understand performance characteristics of different storage option. Lets start with time taken to perform typical operations on computer. Below numbers are from <a href="http://static.googleusercontent.com/media/research.google.com/en//people/jeff/stanford-295-talk.pdf">Jeff Dean presentation at Google</a>.</p>

<table border="1"><tbody><tr><th colspan='2'><b>Numbers Everyone Should Know:</b></th><tr>
<tr><td> Execute typical instruction :       </td><td style="text-align:right">   1/1,000,000,000 sec = 1 nanosec      </td></tr>
<tr><td> Fetch from L1 cache memory  :        </td><td style="text-align:right">                   &nbsp;0.5 nanosec    </td></tr>
<tr><td> Branch mis-prediction       :        </td><td style="text-align:right">                         5 nanosec      </td></tr>
<tr><td> Fetch from L2 cache memory  :        </td><td style="text-align:right">                         7 nanosec      </td></tr>
<tr><td> Mutex lock/unlock           :        </td><td style="text-align:right">                       100  nanosec      </td></tr>
<tr><td> Fetch from main memory      :        </td><td style="text-align:right">                       100 nanosec      </td></tr>
<tr><td> Compress 1K bytes with Zippy :        </td><td style="text-align:right">                       10,000 nanosec      </td></tr>
<tr><td> Send 2K bytes over 1Gbps network :  </td><td style="text-align:right">                    20,000 nanosec      </td></tr>
<tr><td> Read 1MB sequentially from memory :     </td><td style="text-align:right">                   250,000 nanosec      </td></tr>
<tr><td> Round trip within same datacenter :     </td><td style="text-align:right">                   500,000 nanosec      </td></tr>
<tr><td> Fetch from new disk location (seek) : </td><td style="text-align:right">                 10,000,000 nanosec      </td></tr>
<tr><td> Read 1 MB sequentially from network : </td><td style="text-align:right">                 10,000,000 nanosec      </td></tr>
<tr><td> Read 1MB sequentially from disk : </td><td style="text-align:right">                30,000,000 nanosec      </td></tr>
<tr><td> Send packet CA->Netherlands->CA : </td><td style="text-align:right"> &nbsp;&nbsp;&nbsp;150 millisec = 150,000,000 nanosec      </td></tr>
</tbody>
</table>


<br/>


<p>First thing to notice from above numbers is, L1 and L2 cache. Caching is not only used in applications, network software, database systems, operating systems but also in Computer design.</p>

<br/>


<ul>
<li><p>Back of the Envelope Calculations to determine performance of different caching strategies</p>

<ul>
<li><p>In-memory and in-process caching :&ndash; Cache reads are fetched directly from current process memory.</p>

<p>In-memory and in-process cache fetch time = Fetch from main memory = 100 nanosec</p></li>
<li><p>In-memory and out-of-process caching :&ndash; Cache reads are fetched from another process usually over network. Cached values are stored in another processes memory.</p>

<p>In-memory and out-of-process cache fetch time = Round trip within same datacenter + Fetch from main memory = 500,000 nanosec + 100 nanosec</p></li>
<li><p>Persistent caching :&ndash; Cache reads are read from disk usually over network.</p>

<p>In-memory and out-of-process cache fetch time = Fetch from new disk location (seek) + Round trip within same datacenter = 10,000,000 nanosec + 500,000 nanosec</p>

<p>Persistent caching does not always mean reading from disk, databases usually cache working set data ( often used data ) in its main memory so when there is <b>cache hit</b> it performs similar to In-memory and out-of-process.</p></li>
</ul>
</li>
</ul>


<h6>Summary</h6>


<ul>
<li>In-memory and in-process caching is 500 times faster than In-memory and out-of-process cache fetch time</li>
<li>In-memory and out-of-process cache fetch time is 20 times faster than Persistent caching</li>
</ul>


<p>Clearly in-memory in-process caching is big winner and is widely used in web applications. Does that mean we should always use in-memory in-process caching ? To answer this question we have to understand characteristics of large scale web application.</p>

<p><b><i>Caching in Web Applications Cluster</i></b></p>

<p>As discussed in <a href="http://venkateshcm.com/2014/05/Architecture-Issues-Scaling-Web-Applications/">Architecture Issues Scaling Web Applications</a>, large scale web application should be able to</p>

<ul>
<li><p>Horizontal scale out
  We should be able to add identical nodes in each layer to scale web applications.</p></li>
<li><p>No single point of failure
  Is large cluster of nodes, failure of single node can happen and it should not bring down application.</p></li>
</ul>


<p>Due to above two characteristics we end-up with cluster of nodes in any large scale applications.</p>

<p>Getting back to caching, if we go with in-memory in-process caching, each node will have to cache required data. Below are few issues with in-process caching</p>

<ul>
<li>Redundant caching consumes lot of memory. In cluster with N web application processes same cached value has to be stored N times.</li>
<li>Each node will have to face cache miss and perform resource intensive operation before caching. i.e. In N Node cluster resource intensive operation is performed N times. This problem become noticeable if TTL of cached value is low. For Example :&ndash; A web application cluster with 100 nodes, and TTL of 1 min will perform 100 resource intensive operations every minute.</li>
<li>Cache Refresh is another major problem with in-memory in process in cluster of web application process. Refreshing cache across the cluster is not easy and if cache is refreshed based on time. Due to machine time synchronization issue stale cached value will be used in some nodes, depending on application it could cause application in-consistent results based on which node handles request.</li>
</ul>


<p>Out-of-process caching gets around the above issues by storing cached values in distributed caching systems like memcache. Due to central cache handling in out-of-process caching</p>

<ul>
<li>If one of the web application node caches a value, it is available to all other nodes reducing cache misses.</li>
<li>Cache can be refreshed or invalided easily by updating central cache system.</li>
</ul>


<p>Persistent caches is used when it is important to recover from crash with cached values intact. It is achieved by re-loading cached data from disk.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Caching To Scale Web Applications]]></title>
    <link href="http://venkateshcm.com/2014/05/Caching-To-Scale-Web-Applications/"/>
    <updated>2014-05-17T00:00:00+05:30</updated>
    <id>http://venkateshcm.com/2014/05/Caching-To-Scale-Web-Applications</id>
    <content type="html"><![CDATA[<p>In <a href="http://venkateshcm.com/2014/05/Architecture-Issues-Scaling-Web-Applications/">Architectural Issues While Scaling Web Applications</a>, I pointed to caching as solution to some of the scaling issues, in this post I will cover different ways of caching and how caching can reduce load on web application and hence improve performance and scalability of web applications. I will cover Web application &amp; database caching in next post.</p>

<p>Caching is the most common way to improve performance or scalability of an web application. In fact, effectiveness of caching is arguably main reason for developer confidence to ignore premature optimisation or to postpone fixing probable performance issue until detecting an issue. The underlying assumption for this confidence is (a) the performance optimisation is may not be required (b) if required, performance issue could be fixed by caching.</p>

<p>Effectiveness of caching in improving performance is due to the fact that most applications are read heavy and perform lot of repetitive operations. So application&rsquo;s performance can be greatly improved by avoiding repeatedly performing resource intensive operation several times. An operation could be resource intensive due to IO activity such as accessing database/service or due to computation/calculations which are CPU intensive.</p>

<p><b><i>What is caching?</i></b></p>

<p>Caching is storing result of an operation which can be used later instead of repeating the operation again.</p>

<p><b><i>Cache hit ratio</i></b></p>

<p>Before executing an operation, a check is performed to determine if the operation result (requested data) is already available in cache. If requested data is available, it is called <b>cache hit</b> and if requested data is not available in cache, it is called <b>cache miss</b>. When cache miss occurs, the requested operation is executed and result is cached for future use (lazy cache population).</p>

<p><b>Cache hit ratio</b> is the number of cache hits divided by total number of requests for an operation. For efficient utilisation of memory, cache hit ration should be high.</p>

<p>Cache hit ratio closer to 0 means most of the requests miss cache and the requested operation is executed every time. Low cache hit ratio could also lead to large cache memory usage as every cache miss could mean new addition to cache storage. Cache hit ratio closer to 1 means most of the requests have cache hits and requested operation is almost never executed.</p>

<p><b><i>Cache population</i></b></p>

<p>Cache could be populated lazily after the executing the operation very first time or by pre-populating cache at the start of application or by another process/background job. Lazy cache population is most common usage pattern but cache population by another background job can be effective when possible.</p>

<p><b><i>Caching Layers in Web Architecture</i></b></p>

<p>There are several layers in typical web application architecture where caching can be performed.</p>

<p><img class="article-img" border="0" src="http://venkateshcm.com/img/blog/CacheArchitecture.png" class="" style="display: inline-block;"></p>

<p>As shown in the above diagram, caching can be done right from browser to database layer of architecture. Let us walk through each layer of caching touching how and what could be cached at that layer and understand pros and cons of caching at each layer.</p>

<p>Few general points to note in the above diagram</p>

<ul>
<li>Caching at left most layer is better for latency.</li>
<li>Caching at right most layers gives better control over granularity of caching and ways to clear or refreshing cache.</li>
</ul>


<p><b><i>Browser Cache</i></b></p>

<p>Browser loads a web page by makes several requests to server for both dynamic resource and static resources like images, style sheets, java scripts etc. Since web application is used by user several times, most of the resources are repeatedly requested from server. Browser can store some of the resources in browser cache and subsequent requests load locally cached resource instead of making server request, reducing the load on web server.</p>

<h6>Cache granularity</h6>


<ul>
<li>Static file caching like images , style sheets, java scripts etc</li>
<li>Browsers also provide local storage (HTML5) and cookies which can be used for caching dynamic data.</li>
</ul>


<h6>How to populate cache</h6>


<ul>
<li>Browser caching works by setting HTTP header parameters like cache control headers of resource to be cached with time to live (TTL).</li>
</ul>


<h6>Regular Cache Refresh</h6>


<ul>
<li>Browser makes server requests after TTL time period and refreshes browser cache.</li>
</ul>


<h6>Forced Cache Refresh</h6>


<ul>
<li>Cache refresh can be forced by changing cache invalidation parameter in the URL of the resource. Cache invalidation can be</li>
<li>a query parameter Eg. <a href="http://server.com/js/library.js?timestamp">http://server.com/js/library.js?timestamp</a></li>
<li>a version number in resource path URL Eg. <a href="http://server.com/v2/js/library.js">http://server.com/v2/js/library.js</a></li>
</ul>


<p>In <a href="http://en.wikipedia.org/wiki/Single-page_application">Single Page Applications (SPA)</a>, the initial page is always loaded from server but all other dependents like images, stylesheets, java scripts etc. are loaded based on  (query parameter or version number in URL). When a new resource or application is deployed to production, cache invalidation parameter is changed to refresh cache.</p>

<h6>Pros</h6>


<ul>
<li>User will experience best response time with no latency.</li>
<li>Can cache both static files and dynamic data.</li>
</ul>


<h6>Cons</h6>


<ul>
<li>Load on server is marginally reduced since repeated requests for the same resource from other machine still hit the server.</li>
<li>Dynamic data stored in HTML5 local storage could be security risk depending on application even through the html6 local storage is accessible to application domain only.</li>
</ul>


<p><b><i>Content Delivery Network(CDN)</i></b></p>

<p><i>Content Delivery Network is a large distributed system of servers deployed in multiple data centres across the Internet. The goal of a CDN is to serve content to end-users with high availability and high performance. CDNs serve a large fraction of the Internet content today, including web objects (text, graphics and scripts), downloadable objects (media files, software, documents), applications (e-commerce, portals), live streaming media, on-demand streaming media, and social networks. </i> &mdash;from <a href="http://en.wikipedia.org/wiki/Content_delivery_network">Wikipedia</a></p>

<p>Content Delivery Network (CDN) providers usually work with Internet Service Providers (ISP) and Telecom companies to add data centres at the last mile of internet connection. Browser request latency is reduced since servers handling requests to cached resource are close to browser client. Browsers usually hold limited number of connection to each host, if the number of requests to a host is more than browser connection limit, requests are queued. CDN caching provides another benefit of distributing resources over several named domains, hence handling more browser requests parallely provides better performance or response time to user. Only static resources are cached in CDN since TTL of resources is usually in the order of days and not seconds.</p>

<h6>Cache granularity</h6>


<ul>
<li>Static File caching like images , style sheets, java scripts etc</li>
</ul>


<h6>How to populate cache</h6>


<ul>
<li>Static resources such as images, stylesheets, java scripts can be stored in CDN using CDN provided tool or API. CDN provides an url for each resource which can be used in web application.</li>
</ul>


<h6>Regular Cache Refresh</h6>


<ul>
<li>CDN tool or API can be used to configure time to live and when to replace static resource on CDN network servers, but replication of CDN resource over distributed network takes time, hence can not be used for very short TTL dynamic resource.</li>
</ul>


<h6>Forced Cache Refresh</h6>


<ul>
<li>Similar to browser cache refresh above, forced cache refresh can be achieved by introducing versioning in url to invalidate cache.</li>
</ul>


<h6>Pros</h6>


<ul>
<li>User will experience good response time with very little latency since resource is returned from nearest server.</li>
<li>Load on server is greatly reduced since all requests for the resource will be handle by CDN.</li>
</ul>


<h6>Cons</h6>


<ul>
<li>Cost of using CDN.</li>
<li>Cache refresh time takes time as it has to refresh on highly distributed network of servers all over the world.</li>
<li>Cache static resources only, since cache refresh is not easy.</li>
</ul>


<p><b><i>Reverse Proxy Cache</i></b></p>

<p>A reverse proxy server is similar to normal proxy server, both act as intermediary between browser client and web server. The main difference is normal proxy server is placed closer to client and reverse proxy server is placed closer to web server. Since requests and responses go through reverse proxy, reverse proxy can cache response to a url and use it to respond to subsequent requests without hitting the web application server. Dynamic resource caching is significant benefit of caching at reverse proxy level with very low TTLs (few seconds). Reverse proxy can cache data in memory or in external cache management tool like memcache, will discuss more on it later.</p>

<p>There are several reverse proxy servers to choose from. Varnish, Squid and Ngnix are some of the options.</p>

<h6>Cache granularity</h6>


<ul>
<li>Static file caching like images, style sheets, java scripts etc</li>
<li>Dynamic page response of http requests.</li>
</ul>


<h6>How to populate cache</h6>


<ul>
<li>Other then reverse proxy server configurations to cache certain resources, proxy servers caching works using HTTP header parameters like cache control, expires headers of resource to be cached with time to leave (TTL).</li>
</ul>


<h6>Regular Cache Refresh</h6>


<ul>
<li>Reverse proxy servers provide ways to invalidate and refresh cache and they make server requests after TTL time period and to refresh cache.</li>
</ul>


<h6>Forced Cache Refresh</h6>


<ul>
<li>Reverse proxy servers can invalidate existing cache on demand.</li>
</ul>


<h6>Pros</h6>


<ul>
<li>Web server load is reduced significantly as multi machine requests can use cache compared to browser cache where only requests for single machine are cached</li>
<li>Reverse proxy servers can cache both static and dynamic resources. Eg. Home page of a site which is same for all clients can be cached for few seconds at reverse proxy.</li>
<li>Most reverse proxy servers act as static file servers as-well, so web application never gets request for static resources.</li>
</ul>


<h6>Cons</h6>


<ul>
<li>User will experience latency since request has to hit distant reverse proxy to get response.</li>
<li>Reverse proxy processing and caching is required, which means added hardware costs compared to CDN costs. But most reverse proxies can be used for multiple purposes -as load balancer, as static file servers as-well as caching layer, added cost of additional box should not be a problem.</li>
</ul>


<p>Next part of this post will cover different ways of <a href="http://venkateshcm.com/2014/06/Web-Application-Cache/">caching within web application</a>.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[How To Determine Web Application Thread Pool Size]]></title>
    <link href="http://venkateshcm.com/2014/05/How-To-Determine-Web-Applications-Thread-Poll-Size/"/>
    <updated>2014-05-10T00:00:00+05:30</updated>
    <id>http://venkateshcm.com/2014/05/How-To-Determine-Web-Applications-Thread-Poll-Size</id>
    <content type="html"><![CDATA[<p>Continuing on <a href="http://venkateshcm.com/2014/05/Architecture-Issues-Scaling-Web-Applications/">Architectural Issues faced while scaling web applications</a>, in this blog I will cover a common issue, how to determine web application thread pool size?, that shows up while deploying web applications to production or while performance testing web applications.</p>

<p><b><i>Thread Pool</i></b></p>

<p>In web applications thread pool size determines the number of concurrent requests that can be handled at any given time. If a web application gets more requests than thread pool size, excess requests are either queued or rejected.</p>

<p>Please note concurrent is not same as parallel. Concurrent requests are number of requests being processed while only few of them could be running on CPUs at any point of time. Parallel requests are number of requests being processed while all of them are running on CPUs at any point of time.</p>

<p>In Non-blocking IO applications such as NodeJS, a single thread (process) can handles multiple requests concurrently. In multi-core CPUs boxes, parallel requests can be handled by increasing number of threads or processes.</p>

<p>In blocking IO applications such as Java SpringMVC, a single thread can handle only one request concurrently. To handle more than one request concurrently we have to increase the number of threads.</p>

<p><b><i>CPU Bound Applications</i></b></p>

<p> In CPU bound applications thread Pool size should be equal number of cpus on the box. Adding more threads would interrupt request processing due to thread context switching and also increases response time.</p>

<p> Non-blocking IO applications will be CPU bound as there are no thread wait time while requests get processed.</p>

<p><b><i>IO Bound Applications</i></b></p>

<p>Determining thread pool size of IO bound application is lot more complicated and depends on response time of down stream systems, since a thread is blocked until other system responds. We would have to increase the number of threads to better utilise CPU as discussed in <a href="http://venkateshcm.com/2014/04/Reactor-Pattern-Part-1-Non-blocking-I-O/">Reactor Pattern Part 1 : Applications with Blocking I/O</a>.</p>

<p><b><i>Little&rsquo;s law</i></b></p>

<p>Little&rsquo;s law was used in non technology fields like banks to figure out number of bank teller counters required to handle incoming bank customers.</p>

<p><b><a href="http://en.wikipedia.org/wiki/Little's_law">Little&rsquo;s law</a></b></p>

<pre><code>The long-term average number of customers in a stable system L is equal to the long-term 
average effective arrival rate, λ, multiplied by the average time a customer spends 
in the system, W; or expressed algebraically: 
L = λW.
</code></pre>

<p><b>Little&rsquo;s law applied to web applications</b></p>

<pre><code>The average number of threads in a system (Threads) is equal average web request 
arrival rate (WebRequests per sec), multiplied by the average response time (ResponseTime)
</code></pre>

<p>Threads = Number of Threads <br/>
WebRequests per sec = Number of Web Requests that can be processed in one second <br/>
ResponseTime = Time taken to process one web request <br/></p>

<pre><code>Threads = (WebRequests/sec) X ResponseTime
</code></pre>

<p>While the above equation provides the number of threads required to handle incoming requests, it does not provide information on the threads to cpu ratio i.e. how many threads should be allocated on a given box with x CPUs.</p>

<p><b><i>Testing to determining Thread Pool size</i></b></p>

<p>To find right thread pool size is to balance between throughput and response time. Starting with minimum a thread per cpu (Threads Pool Size = No of CPUs) , application thread pool size is directly proportional to the average response time of down stream systems until CPU usage is maxed out or response time is not degraded.</p>

<p>Below diagrams illustrate how number of requests, CPU and Response Time metrics are connected.</p>

<p>CPU Vs Number of Requests graph shows how CPU usage while increasing load on the web applications.</p>

<p>Response Time Vs Number of Requests graph shows response time impact due to increasing load on the web applications.</p>

<p>Green dot indicates point of optimal throughput and response time.</p>

<p><b>Thread pool size = Number of CPUs</b></p>

<p><img class="article-img" border="0" height="325" width="480" src="http://venkateshcm.com/img/blog/MinimumThreads.png" class="" style="display: inline-block;"></p>

<p>Above diagram depicts blocking IO bound applications when number of threads is equal to number cpus.
Application threads get blocked waiting for down stream systems to respond. Response time increases as requests get queued since threads are blocked. Application starts rejecting requests as all threads are blocked even though CPU usage is very low.</p>

<p><b>Large Thread pool size</b></p>

<p><img class="article-img" border="0" height="325" width="480" src="http://venkateshcm.com/img/blog/MaximumThreads.png" class="" style="display: inline-block;"></p>

<p>Above diagram depicts blocking IO bound applications when large number of threads are created in web application. Due to large number of threads, thread context switching will be very frequent. Application CPU usage gets maxed out even though throughput has not increased due to unnecessary thread context switching. Response Time degrades since requests are interrupted with context switching.</p>

<p><b>Optimal Thread pool size</b></p>

<p><img class="article-img" border="0" height="325" width="480" src="http://venkateshcm.com/img/blog/OptimalThreads.png" class="" style="display: inline-block;"></p>

<p>Above diagram depicts blocking IO bound applications when optimal number of threads are created in web application. CPU gets efficiently used with good throughput and fewer thread context switching. We notice good response time due to efficient request processing with fewer interrupts (context switching).</p>

<p><b><i>Thread Pool isolation</i></b></p>

<p>In most web applications, few types of web request take much longer to process than other web request types.The slower web requests might hog all threads and bring down entire application.</p>

<p>Couple of ways to handle this issue is</p>

<ul>
<li>to have separate box to handle slow web requests.</li>
<li>to allocate a separate thread pool for slow web requests within the same application.</li>
</ul>


<p>Determining optimal thread pool size of a blocking IO web application is difficult task. Usually done by performing several performance runs. Having several thread pools in a web application further complicates the process of determining optimal thread pool size.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Architecture Issues Scaling Web Applications]]></title>
    <link href="http://venkateshcm.com/2014/05/Architecture-Issues-Scaling-Web-Applications/"/>
    <updated>2014-05-05T00:00:00+05:30</updated>
    <id>http://venkateshcm.com/2014/05/Architecture-Issues-Scaling-Web-Applications</id>
    <content type="html"><![CDATA[<p>I will cover architecture issues that show up while scaling and performance tuning large scale web application in this blog.</p>

<p>Lets start by defining few terms to create common understanding and vocabulary. Later on I will go through different issues that pop-up while scaling web application like</p>

<ul>
<li>Architecture bottlenecks</li>
<li>Scaling Database</li>
<li>CPU Bound Application</li>
<li>IO Bound Application</li>
</ul>


<p><a href="http://venkateshcm.com/2014/05/How-To-Determine-Web-Applications-Thread-Poll-Size/">Determining optimal thread pool size of an web application</a> will be covered in next blog.</p>

<p><b><i>Performance</i></b></p>

<p>Term performance of web application is used to mean several things. Most developers are primarily concerned with response time and scalability.</p>

<ul>
<li><p><h5>Response Time</h5></p>

<p>Is the time taken by web application to process request and return response. Applications should respond to requests (response time) within acceptable duration. If application is taking beyond the acceptable time, it is said to be non-performing or degraded.</p></li>
<li><p><h5>Scalability</h5></p>

<p>Web application is said to be scalable if by adding more hardware, application can linearly take more requests than before. Two ways of adding more hardware are</p>

<ul>
<li><b>Scaling Up (vertical scaling)</b> :&ndash;
increasing the number CPUs or adding faster CPUs on a single box.</li>
<li><b>Scaling Out (horizontal scaling)</b> :&ndash;
increasing the number of boxes.</li>
</ul>
</li>
</ul>


<p><b><i>Scaling Up Vs Scaling Out</i></b></p>

<p>Scaling out is considered more important as commodity hardware is cheaper compared to cost of special configuration hardware (super computer). But increasing the number of requests that an application can handle on a single commodity hardware box is also important. An application is said to be performing well if it can handle more requests with-out degrading response time by just adding more resources.</p>

<p><b><i>Response time Vs Scalability</i></b></p>

<p>Response time and Scalability don&rsquo;t always go together i.e. application might have acceptable response times but may not handle more than certain number of requests or application can handle increasing number of requests but has poor or long response times. We have to strike a balance between scalability and response time to get good performance of the application.</p>

<p><b><i>Capacity Planning</i></b></p>

<p>Capacity planning is an exercise of figuring out the required hardware to handle expected load in production. Usually it involves figuring out performance of application with fewer boxes and based on performance per box projecting it. Finally verifying it with load/performance tests.</p>

<p><b><i>Scalable Architecture</i></b></p>

<p>Application architecture is scalable if each layer in multi layered architecture is scalable (scale out). For example :&ndash; As shown in diagram below we should be able linearly scale by add additional box in Application Layer or Database Layer.</p>

<p><img class="article-img" border="0" height="325" width="480" src="http://venkateshcm.com/img/blog/scaling.png" class="" style="display: inline-block;"></p>

<p><b><i>Scaling Load Balancer</i></b></p>

<p>Load balancers can be scaled out by point DNS to multiple IP addresses and using DNS Round Robin for IP address lookup. Other option is to front another load balancer which distributes load to next level load balancers.</p>

<p>Adding multiple Load balancers is rare as a single box running nginx or HAProxy can handle more than 20K concurrent connections per box compared to web application boxes which can handle few thousand concurrent requests. So a single load balancer box can handle several web application boxes.</p>

<p><b><i>Scaling Database</i></b></p>

<p>Scaling database is one of the most common issues faced. Adding business logic (stored procedure, functions) in database layer brings in additional overhead and complexity.</p>

<p><b>RDBMS</b></p>

<p>RDBMS database can be scaled by having master-slave mode with read/writes on master database and only reads on slave databases. Master-Slave provides limited scaling of reads beyond which developers has to split the database into multiple databases.</p>

<p><b>NoSQL</b></p>

<p><a href="http://en.wikipedia.org/wiki/CAP_theorem">CAP theorem</a> has shown that is not possible to get Consistency, Availability and Partition tolerance simultaneously. NoSql databases usually compromise on consistency to get high availability and partition.</p>

<p><b>Splitting database</b></p>

<p>Database can be split vertically (Partitioning) or horizontally (Sharding).</p>

<ul>
<li><p>Vertically splitting (Partitioning) :&ndash; Database can be split into multiple loosely coupled sub-databases based of domain concepts. Eg:&ndash; Customer database, Product Database etc. Another way to split database is by moving few columns of an entity to one database and few other columns to another database. Eg:&ndash; Customer database , Customer contact Info database, Customer Orders database etc.</p></li>
<li><p>Horizontally splitting (Sharding) :&ndash; Database can be horizontally split into multiple database based on some discrete attribute. Eg:&ndash;  American Customers database, European Customers database.</p></li>
</ul>


<p>Transiting from single database to multiple database using partitioning or sharding is a challenging task.</p>

<p><b><i>Architecture bottlenecks</i></b></p>

<p>Scaling bottlenecks are formed due to two issues</p>

<ul>
<li><p><b>Centralised component</b>
A component in application architecture which can not be scaled out adds an upper limit on number of requests that entire architecture or request pipeline can handle.</p></li>
<li><p><b>High latency component</b>
A slow component in request pipeline puts lower limit on the response time of the application. Usual solution to fix this issue is to make high latency components into background jobs or executing them asynchronously with queuing.</p></li>
</ul>


<p><b><i>CPU Bound Application</i></b></p>

<p>An application is said to be CPU bound if application throughput is limited by its CPU. By increasing CPU speed application response time can be reduced.</p>

<p>Few scenarios where applications could be CPU Bound</p>

<ul>
<li>Applications which are computing or processing data with out performing IO operations. (Finance or Trading Applications)</li>
<li>Applications which use cache heavily and don&rsquo;t perform any IO operations</li>
<li>Applications which are asynchronous (i.e. Non Blocking), don&rsquo;t wait on external resources. (Reactive Pattern Applications, NodeJS application)</li>
</ul>


<p>In the above scenarios application is already working in efficiently but in few instances applications with badly written or inefficient code which perform unnecessary heavy calculations or looping on every request tend to show high CPU usage. By profiling application it is easy to figure out the inefficiencies and fix them.</p>

<p>These issues can be fixed by</p>

<ul>
<li>Caching precomputed values</li>
<li>Performing the computation in separate background job.</li>
</ul>


<p>Different ways of caching, how caching can reduce load and improve performance and scalability of web applications is covered in post <a href="http://venkateshcm.com/2014/05/Caching-To-Scale-Web-Applications/">Caching To Scale Web Applications</a></p>

<p><b><i>IO Bound Application</i></b></p>

<p>An application is said to be IO bound if application throughput is limited by its IO or network operations and increasing CPU speed does not bring down application response times. Most applications are IO bound due to the CRUD operation in most applications
Performance tuning or scaling IO bound applications is a difficult job due to its dependency on other systems downstream.</p>

<p>Few scenarios where applications could be IO Bound</p>

<ul>
<li>Applications which are depended on database and perform CRUD operations</li>
<li>Applications which consume drown stream web services for performing its operations</li>
</ul>


<p>Next blog will cover <a href="http://venkateshcm.com/2014/05/How-To-Determine-Web-Applications-Thread-Poll-Size/">how to determining optimal thread pool size of an web application</a>.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Zen Of Software Design - Part 2]]></title>
    <link href="http://venkateshcm.com/2014/04/zen-of-software-design-part-2/"/>
    <updated>2014-04-28T00:00:00+05:30</updated>
    <id>http://venkateshcm.com/2014/04/zen-of-software-design-part-2</id>
    <content type="html"><![CDATA[<p>This blog is part 2 of <a href="http://venkateshcm.com/2014/04/Zen-Of-Software-Design-Part-1/">Zen of Software Design : Part 1</a> which covers lines 1 to 9 of <a href="http://legacy.python.org/dev/peps/pep-0020/">Zen of Python</a>, if you have not read it please read it before reading this post. In this blog I will cover lines 10 to 19 of <a href="http://legacy.python.org/dev/peps/pep-0020/">Zen of Python</a></p>

<p><b><i>Errors should never pass silently.</i></b><br/>
<b><i>Unless explicitly silenced.</i></b></p>

<p>Silencing an error is hiding a symptom. Catching an exception and ignoring it is hiding error from being discovered and providing false feedback to user. Application should make errors transparent and visible. i.e. End user should know that the current task has failed and he had to take appropriate action and not proceed with assumption that the task has succeeded.</p>

<p>That said, in few occasions when a low priority task is performed along with high priority task, it is better not to fail the entire request if low priority task fails.</p>

<p>For Example:&ndash; User registration might have two steps</p>

<ul>
<li>Update user information in datastore</li>
<li>Send out an confirmation email</li>
</ul>


<p>If user information is updated in datastore and sending confirmation email failed it is ok to ignore send email error by queuing it to be processed later. But this also means taking appropriate steps to intimate support person and to make sure developer has enough information to figure out the reason for failure.</p>

<p><b><i>In the face of ambiguity, refuse the temptation to guess.</i></b><br/>
<b><i>Although that way may not be obvious at first unless you&rsquo;re Dutch.</i></b></p>

<p>In large systems it is difficult to figure what went wrong, without testing and inspecting several scenarios. I have seen developers jump into code to fix an issue without understanding the root caused for error and later to realise they were barking on wrong tree. It is better to simulate the error and than find a solution to fix the error, instead of working on a solution directly. After simulating error we could test out different hypothesis to confirm the assumptions.</p>

<p><b><i>Now is better than never.</i></b><br/>
<b><i>Although never is often better than <em>right</em> now.</i></b></p>

<p>When faced with a need for large scale code refactoring, we tend to procrastinate and postpone the refactoring. Even thought we know the urgency or necessity for refactoring and how to fix the problem, we keep broken windows in codebase causing more issues.</p>

<p>There are cases where we don&rsquo;t have a solution for the problem or we don&rsquo;t have enough time to make the change right now. It is better to hold off changes, instead of doing half baked (partial) solution right now. In many cases it is better to hold off doing the changes until the right opportune moment, instead of jumping into action right away. (Eg :&ndash; Premature optimisation)</p>

<p><b><i>If the implementation is hard to explain, it&rsquo;s a bad idea.</i></b><br/>
<b><i>If the implementation is easy to explain, it may be a good idea.</i></b></p>

<p>If the business problem is not modelled correctly or there are several exceptions each core application flows. Software design tends to be hard to explain. In such cases, hard to explain, should be treated as a design-smell.</p>

<p>Difficulty to explain means bad design but easy to explain does not imply good design. Simple design might not have taken all different scenarios into consideration or could have made plain wrong assumption.</p>

<p>Design should be as-complex or as-simple as the requirement need, not more and not less. Over designing is adding unnecessary complexity to the system and under designing is not handling all scenarios.</p>

<p><b><i>Namespaces are one honking great idea &mdash; let&rsquo;s do more of those!</i></b></p>

<p>There are several tools and conventions which make life easier, we should just follow them instead of reinventing new solutions. Following conventions and standards is very important means of managing code quality.</p>

<pre><code>$ python

&gt;&gt;&gt; import this

The Zen of Python, by Tim Peters
1 Beautiful is better than ugly.
2 Explicit is better than implicit.
3 Simple is better than complex.
4 Complex is better than complicated.
5 Flat is better than nested.
6 Sparse is better than dense.
7 Readability counts.
8 Special cases aren't special enough to break the rules.
9 Although practicality beats purity.
10 Errors should never pass silently.
11 Unless explicitly silenced.
12 In the face of ambiguity, refuse the temptation to guess.
13 There should be one-- and preferably only one --obvious way to do it.
14 Although that way may not be obvious at first unless you're Dutch.
15 Now is better than never.
16 Although never is often better than *right* now.
17 If the implementation is hard to explain, it's a bad idea.
18 If the implementation is easy to explain, it may be a good idea.
19 Namespaces are one honking great idea -- let's do more of those! 
</code></pre>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Reactor Pattern Part 4 - Write Sequential Non-Blocking IO Code With Fibers in NodeJS]]></title>
    <link href="http://venkateshcm.com/2014/04/Reactor-Pattern-Part-4-Write-Sequential-Non-Blocking-IO-Code-With-Fibers-In-NodeJS/"/>
    <updated>2014-04-26T00:00:00+05:30</updated>
    <id>http://venkateshcm.com/2014/04/Reactor-Pattern-Part-4-Write-Sequential-Non-Blocking-IO-Code-With-Fibers-In-NodeJS</id>
    <content type="html"><![CDATA[<p>This is the final part of 4 part Reactor Pattern series. In <a href="http://venkateshcm.com/2014/04/Reactor-Pattern-Part-1-Non-blocking-I-O/">Reactor Pattern Part 1 : Applications with Blocking I/O</a>, I went through issues faced by a single threaded application to scale to handle more requests pre box. In <a href="http://venkateshcm.com/2014/04/Reactor-Pattern-Part-2-Non-blocking-I-O/">Reactor Pattern Part 2 : Applications with Non-Blocking I/O</a> I went through what Reactor Pattern is and how it solved the Blocking IO issues and mentioned call back issue due to async code. <a href="http://venkateshcm.com/2014/04/Reactor-Pattern-Part-3-Promises-to-solve-callback-hell/">Reactor Pattern Part 3 &ndash; Promises to solve callback hell</a> talked about callback code issues in detail and how promise library can solve some of the issues.</p>

<p><b><i>Recap &ndash; Part 3 Conclusion</i></b></p>

<p>Async or Non-blocking IO introduces new challenges on how applications should to be structured and how async call backs can be abstracted away using promises like library. We need Non-blocking IO application since, sequential blocking IO applications are not scalable. So Non-Blocking IO or Asynchronous code is not a desired feature but a necessary evil to achieve scalability.</p>

<p>Finally, we should question assumption that Non-blocking IO and Asynchronous code are clubbed together and one comes with other. Is it possible to get the best of both the worlds, i.e. Sequential code and Non-Blocking IO scalability. In fact, I think there is an option based on Fibers which can provide best of both the worlds.</p>

<p>An interesting article on <a href="http://static.usenix.org/events/hotos03/tech/full_papers/vonbehren/vonbehren_html/">Why Events Are A Bad Idea</a> makes sequential control flow arguments in more depth.</p>

<p>I will cover Fibers and how they achieve both Non-Blocking IO and Sequential codebase and demonstrate it with an expressjs resful service in the this blog.</p>

<p>Pre-emptive and co-operative multitasking is a good place to begin understanding Fibers.</p>

<p><b><i>Pre-emptive Multitasking and Co-Operative Multitasking</i></b></p>

<p><a href="http://en.wikipedia.org/wiki/Pre-emptive_multitasking">Pre-emptive Multitasking</a> :&ndash;</p>

<p><i>In computing, preemption is the act of temporarily interrupting a task being carried out by a computer system, without requiring its cooperation, and with the intention of resuming the task at a later time. Such a change is known as a context switch. It is normally carried out by a privileged task or part of the system known as a preemptive scheduler, which has the power to preempt, or interrupt, and later resume, other tasks in the system. &ndash; from Wikipedia</i></p>

<p> Linux Scheduler (privileged task) pre-empts process tasks without its co-operation. The disadvantage of preemptive multitasking is that the OS may make a context switch at an inappropriate time.</p>

<p><a href="http://en.wikipedia.org/wiki/Computer_multitasking#Cooperative_multitasking.2Ftime-sharing">Co-Operative Multitasking</a> :&ndash;</p>

<p><i>Early multitasking systems used applications that voluntarily ceded time to one another. This approach, which was eventually supported by many computer operating systems, is known today as cooperative multitasking. &ndash; from Wikipedia</i></p>

<p>Co-Operative Multitasking relies on the threads relinquishing control once they are at a stopping point. The disadvantage of co-operative multitasking is that a poorly written application can blocking the entire system. Real-time embedded systems are often implemented using Co-Operative Multitasking paradigm to get real time performance.</p>

<p><b><i>What are Fibers?</i></b></p>

<p>Fibers are lightweight threads (also called green threads) which are process or application level concepts and don&rsquo;t correspond to OS threads. They provide thread like execution flow. While OS threads are pre-emtively scheduled, programmer can use fibers to co-opratively multitask. Fibers are conceptually similar to <a href="http://en.wikipedia.org/wiki/Coroutine">coroutines</a> .i.e. execution can be suspended and resumed programmatically.</p>

<p>Lets see an example of how fibers work</p>

<figure class='code'><figcaption><span>Simple Example Fibers - fibersExample.js </span></figcaption>
<div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
<span class='line-number'>18</span>
<span class='line-number'>19</span>
<span class='line-number'>20</span>
<span class='line-number'>21</span>
<span class='line-number'>22</span>
<span class='line-number'>23</span>
<span class='line-number'>24</span>
<span class='line-number'>25</span>
<span class='line-number'>26</span>
<span class='line-number'>27</span>
<span class='line-number'>28</span>
<span class='line-number'>29</span>
<span class='line-number'>30</span>
</pre></td><td class='code'><pre><code class='js'><span class='line'><span class="kd">var</span> <span class="nx">Fiber</span> <span class="o">=</span> <span class="nx">require</span><span class="p">(</span><span class="s1">&#39;fibers&#39;</span><span class="p">);</span>
</span><span class='line'>
</span><span class='line'><span class="kd">var</span> <span class="nx">log_sequence_counter</span> <span class="o">=</span> <span class="mi">1</span><span class="p">;</span>
</span><span class='line'>
</span><span class='line'><span class="kd">function</span> <span class="nx">sleep</span><span class="p">(</span><span class="nx">task</span><span class="p">,</span> <span class="nx">milliseconds</span><span class="p">)</span> <span class="p">{</span>
</span><span class='line'>    <span class="kd">var</span> <span class="nx">fiber</span> <span class="o">=</span> <span class="nx">Fiber</span><span class="p">.</span><span class="nx">current</span><span class="p">;</span>
</span><span class='line'>    <span class="nx">setTimeout</span><span class="p">(</span><span class="kd">function</span><span class="p">()</span> <span class="p">{</span>
</span><span class='line'>      <span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="nx">log_sequence_counter</span><span class="o">++</span> <span class="o">+</span> <span class="nx">task</span> <span class="o">+</span> <span class="s1">&#39; callback&#39;</span><span class="p">);</span>
</span><span class='line'>        <span class="nx">fiber</span><span class="p">.</span><span class="nx">run</span><span class="p">();</span>
</span><span class='line'>    <span class="p">},</span> <span class="nx">milliseconds</span><span class="p">);</span>
</span><span class='line'>    <span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="nx">log_sequence_counter</span><span class="o">++</span> <span class="o">+</span> <span class="nx">task</span> <span class="o">+</span> <span class="s1">&#39; thread/fiber suspended&#39;</span><span class="p">);</span>
</span><span class='line'>    <span class="nx">Fiber</span><span class="p">.</span><span class="nx">yield</span><span class="p">();</span>
</span><span class='line'>    <span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="nx">log_sequence_counter</span><span class="o">++</span> <span class="o">+</span> <span class="nx">task</span> <span class="o">+</span> <span class="s1">&#39; thread/fiber resumed&#39;</span><span class="p">);</span>
</span><span class='line'><span class="p">}</span>
</span><span class='line'>
</span><span class='line'><span class="kd">var</span> <span class="nx">task1</span> <span class="o">=</span> <span class="kd">function</span><span class="p">()</span> <span class="p">{</span>
</span><span class='line'>    <span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="nx">log_sequence_counter</span><span class="o">++</span> <span class="o">+</span> <span class="s1">&#39; task 1 waiting for sleep to end &#39;</span><span class="p">);</span>
</span><span class='line'>    <span class="nx">sleep</span><span class="p">(</span><span class="s2">&quot; task 1&quot;</span><span class="p">,</span><span class="mi">1000</span><span class="p">);</span>
</span><span class='line'>    <span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="nx">log_sequence_counter</span><span class="o">++</span> <span class="o">+</span> <span class="s1">&#39; task 1 got back from sleep&#39;</span><span class="p">);</span>
</span><span class='line'><span class="p">}</span>
</span><span class='line'>
</span><span class='line'><span class="kd">var</span> <span class="nx">task2</span> <span class="o">=</span> <span class="kd">function</span><span class="p">()</span> <span class="p">{</span>
</span><span class='line'>    <span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="nx">log_sequence_counter</span><span class="o">++</span> <span class="o">+</span> <span class="s1">&#39; task 2 waiting for sleep to end &#39;</span><span class="p">);</span>
</span><span class='line'>    <span class="nx">sleep</span><span class="p">(</span><span class="s2">&quot; task 2&quot;</span><span class="p">,</span> <span class="mi">1000</span><span class="p">);</span>
</span><span class='line'>    <span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="nx">log_sequence_counter</span><span class="o">++</span> <span class="o">+</span> <span class="s1">&#39; task 2 got back from sleep&#39;</span><span class="p">);</span>
</span><span class='line'><span class="p">}</span>
</span><span class='line'>
</span><span class='line'><span class="nx">Fiber</span><span class="p">(</span><span class="nx">task1</span><span class="p">).</span><span class="nx">run</span><span class="p">();</span>
</span><span class='line'><span class="nx">Fiber</span><span class="p">(</span><span class="nx">task2</span><span class="p">).</span><span class="nx">run</span><span class="p">();</span>
</span><span class='line'><span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span> <span class="nx">log_sequence_counter</span><span class="o">++</span> <span class="o">+</span> <span class="s1">&#39; main execution flow&#39;</span><span class="p">);</span>
</span></code></pre></td></tr></table></div></figure>


<p>In the above example, you can notice that</p>

<ul>
<li>Fibers are created using Fiber() function and the task function is executed using run method.</li>
<li>Pattern used to suspend and resume a Fiber. This pattern will be reused while making Non-Blocking IO calls.</li>
<li>Within a fiber thread Fiber.current returns current executing fiber.</li>
<li>Fiber.yield suspends execution of current thread i.e. voluntarily relinquish control. In other words it allows another fiber thread execute co-operatively.</li>
<li><i>task1</i> and <i>task2</i> functions don&rsquo;t have callbacks or promises and is sequential code.</li>
<li><i>task1</i> and <i>task2</i> functions don&rsquo;t know about fibers and developers can read/write these functions as sequential code.</li>
<li>Fibers provide co-operative multi-tasking capability</li>
</ul>


<figure class='code'><figcaption><span>output of fibersExample.js </span></figcaption>
<div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
</pre></td><td class='code'><pre><code class='sh'><span class='line'><span class="nv">$ </span>node fibersExample.js
</span><span class='line'>1 task 1 waiting <span class="k">for </span>sleep to end
</span><span class='line'>2 task 1 thread/fiber suspended
</span><span class='line'>3 task 2 waiting <span class="k">for </span>sleep to end
</span><span class='line'>4 task 2 thread/fiber suspended
</span><span class='line'>5 main execution flow
</span><span class='line'>6 task 1 callback
</span><span class='line'>7 task 1 thread/fiber resumed
</span><span class='line'>8 task 1 got back from sleep
</span><span class='line'>9 task 2 callback
</span><span class='line'>10 task 2 thread/fiber resumed
</span><span class='line'>11 task 2 got back from sleep
</span></code></pre></td></tr></table></div></figure>


<p>The output of fibersExample.js shows the other of execution with sequence numbers. Even though NodeJS is single threaded application, the above code demonstrates &ndash; how multiple tasks are run with-out blocking each other.</p>

<p><b><i>Fibers &ndash; In ExpressJS Restful Service</i></b></p>

<p>Lets look at an ExpressJS restful service example, to keep code simple, I have not included exception handling which can be done using try &ndash; catch blocks as we do other languages. It provides three service methods</p>

<ol>
<li><b>/google</b> :&ndash; Makes a http get call to google and returns html response from google to client.</li>
<li><b>/user/:fb_id</b> :&ndash; Return User JSON for given facebook id.</li>
<li><b>/user/:fb_id/events</b> :&ndash; Returns User and User&rsquo;s Events for a given facebook id.</li>
</ol>


<figure class='code'><figcaption><span>output of server.js </span></figcaption>
<div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
<span class='line-number'>18</span>
<span class='line-number'>19</span>
<span class='line-number'>20</span>
<span class='line-number'>21</span>
<span class='line-number'>22</span>
<span class='line-number'>23</span>
<span class='line-number'>24</span>
<span class='line-number'>25</span>
<span class='line-number'>26</span>
<span class='line-number'>27</span>
<span class='line-number'>28</span>
<span class='line-number'>29</span>
<span class='line-number'>30</span>
<span class='line-number'>31</span>
<span class='line-number'>32</span>
<span class='line-number'>33</span>
<span class='line-number'>34</span>
<span class='line-number'>35</span>
<span class='line-number'>36</span>
<span class='line-number'>37</span>
<span class='line-number'>38</span>
<span class='line-number'>39</span>
<span class='line-number'>40</span>
<span class='line-number'>41</span>
<span class='line-number'>42</span>
<span class='line-number'>43</span>
<span class='line-number'>44</span>
<span class='line-number'>45</span>
<span class='line-number'>46</span>
<span class='line-number'>47</span>
<span class='line-number'>48</span>
</pre></td><td class='code'><pre><code class='js'><span class='line'><span class="kd">var</span> <span class="nx">express</span> <span class="o">=</span> <span class="nx">require</span><span class="p">(</span><span class="s1">&#39;express&#39;</span><span class="p">);</span>
</span><span class='line'><span class="kd">var</span> <span class="nx">fibersMiddleWare</span> <span class="o">=</span> <span class="nx">require</span><span class="p">(</span><span class="s1">&#39;./fib-middleware&#39;</span><span class="p">);</span>
</span><span class='line'><span class="kd">var</span> <span class="nx">request</span> <span class="o">=</span> <span class="nx">require</span><span class="p">(</span><span class="s2">&quot;./fib-request&quot;</span><span class="p">);</span>
</span><span class='line'><span class="kd">var</span> <span class="nx">fib_redis</span> <span class="o">=</span> <span class="nx">require</span><span class="p">(</span><span class="s2">&quot;./fib-redis&quot;</span><span class="p">);</span>
</span><span class='line'><span class="kd">var</span> <span class="nx">redis_client</span> <span class="o">=</span> <span class="nx">fib_redis</span><span class="p">.</span><span class="nx">init</span><span class="p">(</span><span class="nx">require</span><span class="p">(</span><span class="s2">&quot;redis-url&quot;</span><span class="p">).</span><span class="nx">connect</span><span class="p">());</span>
</span><span class='line'>
</span><span class='line'><span class="cm">/*------------------------------------Models----------------------------------*/</span>
</span><span class='line'>
</span><span class='line'><span class="kd">var</span> <span class="nx">User</span> <span class="o">=</span> <span class="p">{};</span>
</span><span class='line'><span class="nx">User</span><span class="p">.</span><span class="nx">get</span> <span class="o">=</span> <span class="kd">function</span><span class="p">(</span><span class="nx">id</span><span class="p">){</span>
</span><span class='line'>              <span class="kd">var</span> <span class="nx">user_json</span> <span class="o">=</span> <span class="nx">redis_client</span><span class="p">.</span><span class="nx">get</span><span class="p">(</span><span class="s2">&quot;user:&quot;</span> <span class="o">+</span> <span class="nx">id</span><span class="p">);</span>
</span><span class='line'>              <span class="k">return</span> <span class="nx">JSON</span><span class="p">.</span><span class="nx">parse</span><span class="p">(</span><span class="nx">user_json</span><span class="p">);</span>
</span><span class='line'>          <span class="p">};</span>
</span><span class='line'>
</span><span class='line'><span class="kd">var</span> <span class="nx">Event</span> <span class="o">=</span> <span class="p">{};</span>
</span><span class='line'><span class="nx">Event</span><span class="p">.</span><span class="nx">getUserEvents</span> <span class="o">=</span> <span class="kd">function</span><span class="p">(</span><span class="nx">user_id</span><span class="p">){</span>
</span><span class='line'>                        <span class="kd">var</span> <span class="nx">user_json</span> <span class="o">=</span> <span class="nx">redis_client</span><span class="p">.</span><span class="nx">mget</span><span class="p">(</span><span class="s2">&quot;user:&quot;</span> <span class="o">+</span> <span class="nx">id</span> <span class="o">+</span> <span class="s2">&quot;:events&quot;</span><span class="p">);</span>
</span><span class='line'>                        <span class="k">return</span> <span class="nx">JSON</span><span class="p">.</span><span class="nx">parse</span><span class="p">(</span><span class="nx">user_json</span><span class="p">);</span>
</span><span class='line'>                    <span class="p">};</span>
</span><span class='line'>
</span><span class='line'><span class="cm">/*----------------------------------------------------------------------------*/</span>
</span><span class='line'>
</span><span class='line'><span class="kd">var</span> <span class="nx">app</span> <span class="o">=</span> <span class="nx">express</span><span class="p">();</span>
</span><span class='line'><span class="nx">app</span><span class="p">.</span><span class="nx">use</span><span class="p">(</span><span class="nx">fibersMiddleWare</span><span class="p">.</span><span class="nx">runInFiber</span><span class="p">);</span>
</span><span class='line'>
</span><span class='line'><span class="nx">app</span><span class="p">.</span><span class="nx">get</span><span class="p">(</span><span class="s1">&#39;/google&#39;</span><span class="p">,</span> <span class="kd">function</span><span class="p">(</span><span class="nx">req</span><span class="p">,</span> <span class="nx">res</span><span class="p">){</span>
</span><span class='line'>  <span class="kd">var</span> <span class="nx">google_response_body</span> <span class="o">=</span> <span class="nx">request</span><span class="p">.</span><span class="nx">get</span><span class="p">(</span><span class="s1">&#39;http://google.com&#39;</span><span class="p">)</span>
</span><span class='line'>  <span class="nx">res</span><span class="p">.</span><span class="nx">send</span><span class="p">(</span><span class="nx">google_response_body</span><span class="p">);</span>
</span><span class='line'><span class="p">});</span>
</span><span class='line'>
</span><span class='line'><span class="nx">app</span><span class="p">.</span><span class="nx">get</span><span class="p">(</span><span class="s1">&#39;/users/:fb_id&#39;</span><span class="p">,</span><span class="kd">function</span><span class="p">(</span><span class="nx">req</span><span class="p">,</span> <span class="nx">res</span><span class="p">){</span>
</span><span class='line'>                  <span class="kd">var</span> <span class="nx">user</span> <span class="o">=</span> <span class="nx">User</span><span class="p">.</span><span class="nx">get</span><span class="p">(</span><span class="nx">req</span><span class="p">.</span><span class="nx">params</span><span class="p">.</span><span class="nx">fb_id</span><span class="p">)</span>
</span><span class='line'>                  <span class="nx">res</span><span class="p">.</span><span class="nx">setHeader</span><span class="p">(</span><span class="s1">&#39;Content-Type&#39;</span><span class="p">,</span> <span class="s1">&#39;application/json&#39;</span><span class="p">);</span>
</span><span class='line'>                  <span class="nx">res</span><span class="p">.</span><span class="nx">send</span><span class="p">(</span><span class="mi">200</span><span class="p">,</span><span class="nx">JSON</span><span class="p">.</span><span class="nx">stringify</span><span class="p">(</span><span class="nx">user</span><span class="p">));</span>
</span><span class='line'>                <span class="p">});</span>
</span><span class='line'>
</span><span class='line'><span class="nx">app</span><span class="p">.</span><span class="nx">get</span><span class="p">(</span><span class="s1">&#39;/users/:fb_id/events&#39;</span><span class="p">,</span><span class="kd">function</span><span class="p">(</span><span class="nx">req</span><span class="p">,</span> <span class="nx">res</span><span class="p">){</span>
</span><span class='line'>                  <span class="kd">var</span> <span class="nx">user</span> <span class="o">=</span> <span class="nx">User</span><span class="p">.</span><span class="nx">get</span><span class="p">(</span><span class="nx">req</span><span class="p">.</span><span class="nx">params</span><span class="p">.</span><span class="nx">fb_id</span><span class="p">)</span>
</span><span class='line'>                  <span class="kd">var</span> <span class="nx">events</span> <span class="o">=</span> <span class="nx">Event</span><span class="p">.</span><span class="nx">getUserEvents</span><span class="p">(</span><span class="nx">user</span><span class="p">.</span><span class="nx">id</span><span class="p">);</span>
</span><span class='line'>                  <span class="kd">var</span> <span class="nx">response</span> <span class="o">=</span> <span class="p">{</span><span class="s1">&#39;user&#39;</span> <span class="o">:</span> <span class="nx">user</span><span class="p">,</span> <span class="s1">&#39;events&#39;</span> <span class="o">:</span> <span class="nx">events</span><span class="p">};</span>
</span><span class='line'>
</span><span class='line'>                  <span class="nx">res</span><span class="p">.</span><span class="nx">setHeader</span><span class="p">(</span><span class="s1">&#39;Content-Type&#39;</span><span class="p">,</span> <span class="s1">&#39;application/json&#39;</span><span class="p">);</span>
</span><span class='line'>                  <span class="nx">res</span><span class="p">.</span><span class="nx">send</span><span class="p">(</span><span class="mi">200</span><span class="p">,</span><span class="nx">JSON</span><span class="p">.</span><span class="nx">stringify</span><span class="p">(</span><span class="nx">response</span><span class="p">));</span>
</span><span class='line'>                <span class="p">});</span>
</span><span class='line'>
</span><span class='line'><span class="kd">var</span> <span class="nx">server</span> <span class="o">=</span> <span class="nx">app</span><span class="p">.</span><span class="nx">listen</span><span class="p">(</span><span class="mi">3000</span><span class="p">,</span> <span class="kd">function</span><span class="p">()</span> <span class="p">{</span>
</span><span class='line'>    <span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="s1">&#39;Listening on port %d&#39;</span><span class="p">,</span> <span class="nx">server</span><span class="p">.</span><span class="nx">address</span><span class="p">().</span><span class="nx">port</span><span class="p">);</span>
</span><span class='line'><span class="p">});</span>
</span></code></pre></td></tr></table></div></figure>


<p>In the above example, we have used few custom/wrapper libraries <i>&lsquo;fib-middleware&rsquo;</i>, <i>&lsquo;fib-request&rsquo;</i> and <i>&lsquo;fib-redis&rsquo;</i>. They are simple extensions of simple fibers example above.</p>

<p>You can notice that</p>

<ul>
<li>Fibers are setup as middleware using <i>app.use(fibersMiddleWare.runInFiber)</i></li>
<li>Controller and Model methods are Synchronous and Sequential Code.</li>
<li>Http get Request and Datastore (redis_client) operations are also Synchronous.</li>
<li>Other than sequential code there is nothing special happening with-in Server.js code above.</li>
<li>Code demonstrates that Non-Blocking IO code can be synchronous and sequential</li>
</ul>


<p>Lets looks at the libraries that server.js depends on</p>

<figure class='code'><figcaption><span>fib-middleware.js </span></figcaption>
<div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
</pre></td><td class='code'><pre><code class='js'><span class='line'><span class="kd">var</span> <span class="nx">Fiber</span> <span class="o">=</span> <span class="nx">require</span><span class="p">(</span><span class="s2">&quot;fibers&quot;</span><span class="p">);</span>
</span><span class='line'>
</span><span class='line'><span class="kd">function</span> <span class="nx">fiberMiddleWare</span><span class="p">(</span><span class="nx">req</span><span class="p">,</span><span class="nx">resp</span><span class="p">,</span><span class="nx">next</span><span class="p">){</span>
</span><span class='line'>  <span class="nx">Fiber</span><span class="p">(</span><span class="kd">function</span><span class="p">(){</span>
</span><span class='line'>      <span class="nx">next</span><span class="p">();</span>
</span><span class='line'>  <span class="p">}).</span><span class="nx">run</span><span class="p">();</span>
</span><span class='line'><span class="p">}</span>
</span><span class='line'>
</span><span class='line'><span class="nx">exports</span><span class="p">.</span><span class="nx">runInFiber</span> <span class="o">=</span> <span class="nx">fiberMiddleWare</span>
</span></code></pre></td></tr></table></div></figure>


<p>ExpressJS middleware is an implementation intercepting filters pattern which can be used to perform any processing before and after passing the request to controller method.</p>

<p>fib-middleware.js is a simple mechanism to process all http requests within a fiber context. It is similar to Fiber(task1).run() in the fibersExample.js above.</p>

<p><b><i>Custom Wrapper Libraries to provide Fibers Support</i></b></p>

<p><i>fib-request.js</i> and <i>fib-redis.js</i> are wrappers which provide Fibers support and are not required if original library (redis.js or request.js) support Fibers.</p>

<figure class='code'><figcaption><span>fib-request.js </span></figcaption>
<div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
<span class='line-number'>18</span>
</pre></td><td class='code'><pre><code class='js'><span class='line'><span class="kd">var</span> <span class="nx">request</span> <span class="o">=</span> <span class="nx">require</span><span class="p">(</span><span class="s1">&#39;request&#39;</span><span class="p">);</span>
</span><span class='line'><span class="kd">var</span> <span class="nx">Fiber</span> <span class="o">=</span> <span class="nx">require</span><span class="p">(</span><span class="s2">&quot;fibers&quot;</span><span class="p">);</span>
</span><span class='line'>
</span><span class='line'><span class="kd">function</span> <span class="nx">get</span><span class="p">(</span><span class="nx">url</span><span class="p">){</span>
</span><span class='line'>  <span class="kd">var</span> <span class="nx">error</span><span class="p">,</span><span class="nx">response</span><span class="p">,</span><span class="nx">body</span><span class="p">;</span>
</span><span class='line'>  <span class="kd">var</span> <span class="nx">fiber</span> <span class="o">=</span> <span class="nx">Fiber</span><span class="p">.</span><span class="nx">current</span><span class="p">;</span>
</span><span class='line'>  <span class="nx">request</span><span class="p">.</span><span class="nx">get</span><span class="p">(</span><span class="nx">url</span><span class="p">,</span>
</span><span class='line'>                    <span class="kd">function</span><span class="p">(</span><span class="nx">err</span><span class="p">,</span> <span class="nx">resp</span><span class="p">,</span> <span class="nx">b</span><span class="p">){</span>
</span><span class='line'>                      <span class="nx">error</span> <span class="o">=</span> <span class="nx">err</span><span class="p">;</span>
</span><span class='line'>                      <span class="nx">response</span> <span class="o">=</span> <span class="nx">resp</span><span class="p">;</span>
</span><span class='line'>                      <span class="nx">body</span> <span class="o">=</span> <span class="nx">b</span><span class="p">;</span>
</span><span class='line'>                      <span class="nx">fiber</span><span class="p">.</span><span class="nx">run</span><span class="p">()</span>
</span><span class='line'>                    <span class="p">});</span>
</span><span class='line'>  <span class="nx">Fiber</span><span class="p">.</span><span class="nx">yield</span><span class="p">();</span>
</span><span class='line'>  <span class="k">return</span> <span class="nx">body</span><span class="p">;</span>
</span><span class='line'><span class="p">}</span>
</span><span class='line'>
</span><span class='line'><span class="nx">exports</span><span class="p">.</span><span class="nx">get</span> <span class="o">=</span> <span class="nx">get</span><span class="p">;</span>
</span></code></pre></td></tr></table></div></figure>




<figure class='code'><figcaption><span>fib-redis.js </span></figcaption>
<div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
<span class='line-number'>18</span>
<span class='line-number'>19</span>
<span class='line-number'>20</span>
</pre></td><td class='code'><pre><code class='js'><span class='line'><span class="kd">var</span> <span class="nx">Fiber</span> <span class="o">=</span> <span class="nx">require</span><span class="p">(</span><span class="s1">&#39;fibers&#39;</span><span class="p">);</span>
</span><span class='line'><span class="kd">var</span> <span class="nx">conn</span><span class="p">;</span>
</span><span class='line'>
</span><span class='line'><span class="kd">function</span> <span class="nx">get</span><span class="p">(</span><span class="nx">key</span><span class="p">){</span>
</span><span class='line'>  <span class="kd">var</span> <span class="nx">error</span><span class="p">,</span> <span class="nx">value</span><span class="p">;</span>
</span><span class='line'>  <span class="kd">var</span> <span class="nx">fiber</span> <span class="o">=</span> <span class="nx">Fiber</span><span class="p">.</span><span class="nx">current</span><span class="p">;</span>
</span><span class='line'>  <span class="nx">conn</span><span class="p">.</span><span class="nx">get</span><span class="p">(</span><span class="nx">key</span><span class="p">,</span> <span class="kd">function</span><span class="p">(</span><span class="nx">err</span><span class="p">,</span><span class="nx">val</span><span class="p">){</span>
</span><span class='line'>      <span class="nx">error</span> <span class="o">=</span> <span class="nx">err</span><span class="p">;</span>
</span><span class='line'>      <span class="nx">value</span> <span class="o">=</span> <span class="nx">val</span><span class="p">;</span>
</span><span class='line'>      <span class="nx">fiber</span><span class="p">.</span><span class="nx">run</span><span class="p">();</span>
</span><span class='line'>    <span class="p">});</span>
</span><span class='line'>    <span class="nx">Fiber</span><span class="p">.</span><span class="nx">yield</span><span class="p">();</span>
</span><span class='line'>    <span class="k">return</span> <span class="nx">value</span><span class="p">;</span>
</span><span class='line'><span class="p">}</span>
</span><span class='line'><span class="kd">function</span> <span class="nx">init</span><span class="p">(</span><span class="nx">connection</span><span class="p">){</span>
</span><span class='line'>   <span class="nx">conn</span> <span class="o">=</span> <span class="nx">connection</span><span class="p">;</span>
</span><span class='line'>   <span class="k">return</span> <span class="p">{</span> <span class="s1">&#39;get&#39;</span><span class="o">:</span><span class="nx">get</span><span class="p">};</span>
</span><span class='line'><span class="p">}</span>
</span><span class='line'>
</span><span class='line'><span class="nx">exports</span><span class="p">.</span><span class="nx">init</span> <span class="o">=</span> <span class="nx">init</span><span class="p">;</span>
</span></code></pre></td></tr></table></div></figure>


<p>As you can see, <i>fib-request.js</i> and <i>fib-redis.js</i> follow code pattern similar to the fibers example of sleep where thread is suspended and resumed to make the function synchronous.</p>

<p>The above sample ExpressJS application shows that it is possible to write sequential Non-Blocking I/O using Fibers. Though I have used NodeJS in the sample codebase. It is not restricted to NodeJS, the same applies to other languages which support Fibers (light-weight threads) like Ruby, Python etc.</p>

<p><b><i>Libraries Supporting Fibers</i></b></p>

<p>Most application codebase can be divided into two major parts</p>

<ol>
<li>Business or functional part :&ndash; All business and function logic of application is written in this part of codebase by project team developers. Most of developers time is spend working on this part of application.</li>
<li>Framework or Library part :&ndash; In all projects we end-up using several libraries like mvc framework, database drivers etc. which are third part libraries developed by developers outside team. These usually are used across projects and developers usually spend every little time modifying or changing this part.</li>
</ol>


<p>In the express sample above</p>

<ol>
<li><i>Server.js</i> belongs to Business application part.</li>
<li><i>ExpressJS, Fibers.js, redis.js, fib-middleware.js, fib-request and  fib-redis.js </i> belong to framework or library part. i.e. once implemented by library developers or project team, it can be re-used across projects.</li>
</ol>


<p>As shown in the above code, creating fiber based wrapper libraries for NodeJS libraries is pretty simple.</p>

<p>Recently, library developers started supporting Promise Library, which was not the case before. As fibers gain wider developer acceptance, library developers would also support fibers.</p>

<p><b><i>Asynchronous Vs Parallel</i></b></p>

<p>Most of the examples we have seen till now (this and previous blogs on reactor pattern) has been an instance of synchronous code converted to asynchronous code to make it non-blocking. While this is a common scenario and in normal projects it covers 90 to 95% of scenarios in NodeJS applications. But there are occasional requirement which require multiple parallel requests to be made and wait for all the responses to get back. This is a genuine case where parallel or async processing is required and should be allowed to work asynchronously in usual NodeJS Async pattern with help Promise Library (Q.all()).</p>

<p><b><i>Performance/Scalability</i></b></p>

<p>Siege based Performance testing of async call-back based code and sequential fibers code (shown above) showed similar results on my MacBook Pro.</p>

<figure class='code'><figcaption><span>Callback code Performance Test Result </span></figcaption>
<div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
</pre></td><td class='code'><pre><code class='sh'><span class='line'><span class="nv">$ </span>siege -r 10 -c 100 http://localhost:3000/users/11265765672
</span><span class='line'>
</span><span class='line'>Transactions:             1000 hits
</span><span class='line'>Availability:           100.00 %
</span><span class='line'>Elapsed <span class="nb">time</span>:            10.06 secs
</span><span class='line'>Data transferred:         0.20 MB
</span><span class='line'>Response <span class="nb">time</span>:                0.01 secs
</span><span class='line'>Transaction rate:        99.40 trans/sec
</span><span class='line'>Throughput:               0.02 MB/sec
</span><span class='line'>Concurrency:              0.66
</span><span class='line'>Successful transactions:        1000
</span><span class='line'>Failed transactions:             0
</span><span class='line'>Longest transaction:          0.05
</span><span class='line'>Shortest transaction:         0.00
</span></code></pre></td></tr></table></div></figure>




<figure class='code'><figcaption><span>Fibers bases Non-Blocking IO and Sequential code Performance Test Result </span></figcaption>
<div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
</pre></td><td class='code'><pre><code class='sh'><span class='line'><span class="nv">$ </span>siege -r 10 -c 100 http://localhost:3000/users/11265765672
</span><span class='line'>
</span><span class='line'>Transactions:             1000 hits
</span><span class='line'>Availability:           100.00 %
</span><span class='line'>Elapsed <span class="nb">time</span>:             9.09 secs
</span><span class='line'>Data transferred:         0.20 MB
</span><span class='line'>Response <span class="nb">time</span>:                0.01 secs
</span><span class='line'>Transaction rate:       110.01 trans/sec
</span><span class='line'>Throughput:               0.02 MB/sec
</span><span class='line'>Concurrency:              0.92
</span><span class='line'>Successful transactions:        1000
</span><span class='line'>Failed transactions:             0
</span><span class='line'>Longest transaction:          0.06
</span><span class='line'>Shortest transaction:         0.00
</span></code></pre></td></tr></table></div></figure>


<p><b><i>Conclusion</i></b></p>

<p>With Lightweight thread (Fibers) we can do Co-Operative multi-tasking which voluntarily relinquish control and resume processing. If application framework and libraries support Fibers or library wrappers created as shown in above example, functional and application logic can be written in synchronous style. Presence of Fibers, async code can be abstracted into Framework and libraries from functional code. As functional code tend to be larger than wrapper code that might be required, this will substantially reduce application complexity.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Reactor Pattern Part 3 - Promises to solve callback hell]]></title>
    <link href="http://venkateshcm.com/2014/04/Reactor-Pattern-Part-3-Promises-to-solve-callback-hell/"/>
    <updated>2014-04-23T00:00:00+05:30</updated>
    <id>http://venkateshcm.com/2014/04/Reactor-Pattern-Part-3-Promises-to-solve-callback-hell</id>
    <content type="html"><![CDATA[<p>In <a href="http://venkateshcm.com/2014/04/Reactor-Pattern-Part-1-Non-blocking-I-O/">Reactor Pattern Part 1 : Applications with Blocking I/O</a>, I went through issues faced by a single threaded application to scale to handle more requests pre box and the corresponding issues it introduces. In <a href="http://venkateshcm.com/2014/04/Reactor-Pattern-Part-2-Non-blocking-I-O/">Reactor Pattern Part 2 : Applications with Non-Blocking I/O</a> I went through what Reactor Pattern is and how it fixes the Blocking IO issues and mentioned call back issue that async code introduces.</p>

<p>Lets get little more detail on what the callback issues are and introduce few options or libraries used to partially solve the issue, in this blog.</p>

<p><b><i>Example scenario</i></b></p>

<p>Consider a simple scenario where Restful service has to return a list of events for a given user. User is identified by Facebook Id. The service datastore has two tables or collections, (a) User table and (b) Event table which stores.</p>

<ul>
<li><p>user information</p>

<ul>
<li>id</li>
<li>fb_id</li>
<li>name</li>
<li>&hellip;.</li>
</ul>
</li>
<li><p>events information.</p>

<ul>
<li>id</li>
<li>user_id</li>
<li>event_name</li>
<li>event_desc</li>
<li>start_date</li>
<li>&hellip;.</li>
</ul>
</li>
</ul>


<p>Assuming, you are not allowed to join user and event table or datastore is mongodb. The service controller will use below Pseudocode steps to get events.</p>

<ul>
<li>Given facebook id, get user id from User collection</li>
<li>Given user id, get events for the user from  events collection.</li>
</ul>


<p><b><i>Sequential Code with Blocking I/O</i></b></p>

<p>In normal scenario the above steps directly translate to below code. If performance or scalability is not something playing on developers mind, Sequential code is the simplest and normal thing to do.</p>

<figure class='code'><figcaption><span>Sequential Code With Blocking I/O </span></figcaption>
<div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
</pre></td><td class='code'><pre><code class='js'><span class='line'><span class="kd">function</span> <span class="nx">getUserEvents</span><span class="p">(</span><span class="nx">request</span><span class="p">,</span><span class="nx">response</span><span class="p">){</span>
</span><span class='line'>  <span class="kd">var</span> <span class="nx">facebook_id</span> <span class="o">=</span> <span class="nx">request</span><span class="p">.</span><span class="nx">param</span><span class="p">(</span><span class="s1">&#39;facebook_id&#39;</span><span class="p">);</span>
</span><span class='line'>  <span class="k">try</span><span class="p">{</span>
</span><span class='line'>      <span class="kd">var</span> <span class="nx">user</span> <span class="o">=</span> <span class="nx">db</span><span class="p">.</span><span class="nx">users</span><span class="p">.</span><span class="nx">findOne</span><span class="p">({</span><span class="nx">fb_id</span><span class="o">:</span><span class="nx">facebook_id</span><span class="p">});</span>
</span><span class='line'>      <span class="kd">var</span> <span class="nx">events</span> <span class="o">=</span> <span class="nx">db</span><span class="p">.</span><span class="nx">events</span><span class="p">.</span><span class="nx">find</span><span class="p">({</span><span class="nx">user_id</span><span class="o">:</span><span class="nx">user</span><span class="p">.</span><span class="nx">id</span><span class="p">});</span>
</span><span class='line'>      <span class="nx">response</span><span class="p">.</span><span class="nx">write</span><span class="p">(</span><span class="nx">events</span><span class="p">);</span>
</span><span class='line'>  <span class="p">}</span><span class="k">catch</span><span class="p">(</span><span class="nx">err</span><span class="p">){</span>
</span><span class='line'>      <span class="nx">response</span><span class="p">.</span><span class="nx">status</span><span class="p">(</span><span class="mi">500</span><span class="p">).</span><span class="nx">send</span><span class="p">(</span><span class="nx">err</span><span class="p">);</span>
</span><span class='line'>  <span class="p">}</span>
</span><span class='line'><span class="p">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>There are religious wars between Ruby on Rails and NodeJS developers on Sequential Vs Evented style code.</p>

<ul>
<li>Key Points

<ul>
<li>Majority of web applications (Ruby on Rails, Java Spring, Django etc) are written in sequential style.</li>
<li>Sequential style is simple and readable.</li>
<li>Most people think in sequential style i.e. Developers tend to break application logic into sequential steps like Pseudocode provided above.</li>
<li>Boundaries of Pseudocode Step does not usually end at network call or IO call.</li>
<li>Non-blocking I/O is considered when we need better scalabilty or performance.</li>
</ul>
</li>
</ul>


<p>Unfortunately Sequential code is linked to blocking I/O calls, becuase threads follow pre-emptive multitasking and not co-operative multitaking. More on this later when talking about Fibers.</p>

<p><b><i>Callback based solution</i></b></p>

<p>To solve Blocking I/O problem, code is split to three parts</p>

<ol>
<li>Processing done before making a network or IO call</li>
<li>Network or IO call</li>
<li>Processing done after getting back data from network or IO call.</li>
</ol>


<p>Execution flow for each of above steps is seperated and such that each of them can be executed from the event loop.</p>

<figure class='code'><figcaption><span>Non Blocking I/O with Call backs </span></figcaption>
<div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
<span class='line-number'>18</span>
<span class='line-number'>19</span>
</pre></td><td class='code'><pre><code class='js'><span class='line'><span class="kd">function</span> <span class="nx">getUserEvents</span><span class="p">(</span><span class="nx">request</span><span class="p">,</span><span class="nx">response</span><span class="p">){</span>
</span><span class='line'>
</span><span class='line'>  <span class="kd">var</span> <span class="nx">returnEvents</span> <span class="o">=</span> <span class="kd">function</span><span class="p">(</span><span class="nx">err</span><span class="p">,</span><span class="nx">events</span><span class="p">){</span>
</span><span class='line'>          <span class="k">if</span> <span class="p">(</span><span class="nx">err</span><span class="p">)</span> <span class="nx">respone</span><span class="p">.</span><span class="nx">status</span><span class="p">(</span><span class="mi">500</span><span class="p">).</span><span class="nx">send</span><span class="p">(</span><span class="nx">err</span><span class="p">);;</span>
</span><span class='line'>          <span class="nx">response</span><span class="p">.</span><span class="nx">write</span><span class="p">(</span><span class="nx">events</span><span class="p">);</span>
</span><span class='line'>      <span class="p">});</span>  
</span><span class='line'>
</span><span class='line'>  <span class="kd">var</span> <span class="nx">givenUserFindAndReturnEvents</span> <span class="o">=</span> <span class="kd">function</span><span class="p">(</span><span class="nx">err</span><span class="p">,</span><span class="nx">user</span><span class="p">){</span>
</span><span class='line'>      <span class="k">if</span> <span class="p">(</span><span class="nx">err</span><span class="p">)</span> <span class="nx">respone</span><span class="p">.</span><span class="nx">status</span><span class="p">(</span><span class="mi">500</span><span class="p">).</span><span class="nx">send</span><span class="p">(</span><span class="nx">err</span><span class="p">);;</span>
</span><span class='line'>      <span class="nx">db</span><span class="p">.</span><span class="nx">events</span><span class="p">.</span><span class="nx">find</span><span class="p">({</span><span class="nx">user_id</span><span class="o">:</span><span class="nx">user</span><span class="p">.</span><span class="nx">id</span><span class="p">},</span><span class="nx">returnEvents</span><span class="p">);</span>    
</span><span class='line'>  <span class="p">};</span>
</span><span class='line'>
</span><span class='line'>  <span class="kd">var</span> <span class="nx">findUserAndReturnEvents</span> <span class="o">=</span> <span class="kd">function</span><span class="p">(){</span>
</span><span class='line'>      <span class="kd">var</span> <span class="nx">facebook_id</span> <span class="o">=</span> <span class="nx">request</span><span class="p">.</span><span class="nx">param</span><span class="p">(</span><span class="s1">&#39;facebook_id&#39;</span><span class="p">);</span>
</span><span class='line'>      <span class="nx">db</span><span class="p">.</span><span class="nx">users</span><span class="p">.</span><span class="nx">findOne</span><span class="p">({</span><span class="nx">fb_id</span><span class="o">:</span><span class="nx">facebook_id</span><span class="p">},</span> <span class="nx">givenUserFindAndReturnEvents</span><span class="p">);</span>
</span><span class='line'>  <span class="p">}</span>
</span><span class='line'>
</span><span class='line'>  <span class="nx">findUserAndReturnEvents</span><span class="p">();</span>
</span><span class='line'><span class="p">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>Notice that request and response objects are not passed to sub-functions. The sub-functions get access request and response since sub-functions are <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Closures">javascript closures</a>. In fact if we move the sub-functions out-side getUserEvents method, it would not work. Which lead to chooice of keeping <i>givenUserFindAndReturnEvents</i> and <i>returnEvents</i> as sub-functions. <a href="http://en.wikipedia.org/wiki/Currying">Curring</a> can be used to fix this problem, more on that in another blog.</p>

<p>Each of the sub-functions (<i>findUserAndReturnEvents</i>, <i>givenUserFindAndReturnEvents</i>, <i>returnEvents</i>) are executed asynchronously. functions <i>givenUserFindAndReturnEvents</i> and <i>returnEvents</i> are called call-back functions since they are triggered after getting back user object and event objects respectively from datastore.</p>

<p>The sub-functions could have been left as in-line or nested lamda functions. Nesting several such functions is another issue with call-backs.</p>

<ul>
<li>Key Points

<ul>
<li>Code is separated based on pre-network call and post network call.</li>
<li>The caller of the sub-function has to pass a callback function to execute after finishing sub-function task.</li>
<li>Sequential logic is expressed asynchronously.</li>
<li>Asynchronous code above is more scalable but may not be more performant (response time).</li>
<li>Call-back causes readability issues &ndash; callback hell.</li>
<li>Following execution flow is difficult, so called spaghetti-code.</li>
<li>Non-Blocking API&rsquo;s impose major constrain on how you structure your code.</li>
<li>Functions are hierarchy, i.e. calling function is responsible for functionality it provides as-well as the sub-function it calls. For example:&ndash; givenUserFindAndReturnEvents includes functionality of finding and returning Events to http response.</li>
</ul>
</li>
</ul>


<p><b><i>Promise based solution</i></b></p>

<p>To solve Call-back issues like spaghetti-code, we could use code structuring library like <a href="http://documentup.com/kriskowal/q/">q promise</a>. Promise library provides some code style standards and structuring, making it more readable compared to call-back based code shown above.</p>

<figure class='code'><figcaption><span>Non Blocking I/O with Promises </span></figcaption>
<div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
<span class='line-number'>18</span>
<span class='line-number'>19</span>
<span class='line-number'>20</span>
<span class='line-number'>21</span>
<span class='line-number'>22</span>
<span class='line-number'>23</span>
</pre></td><td class='code'><pre><code class='js'><span class='line'><span class="kd">var</span> <span class="nx">loadEventsForUser</span> <span class="o">=</span> <span class="kd">function</span><span class="p">(</span><span class="nx">err</span><span class="p">,</span><span class="nx">user</span><span class="p">){</span>
</span><span class='line'>  <span class="k">return</span> <span class="nx">db</span><span class="p">.</span><span class="nx">events</span><span class="p">.</span><span class="nx">find</span><span class="p">({</span><span class="nx">user_id</span><span class="o">:</span><span class="nx">user</span><span class="p">.</span><span class="nx">id</span><span class="p">});</span>  
</span><span class='line'><span class="p">};</span>
</span><span class='line'>
</span><span class='line'><span class="kd">var</span> <span class="nx">findUser</span> <span class="o">=</span> <span class="kd">function</span><span class="p">(){</span>
</span><span class='line'>  <span class="kd">var</span> <span class="nx">facebook_id</span> <span class="o">=</span> <span class="nx">request</span><span class="p">.</span><span class="nx">param</span><span class="p">(</span><span class="s1">&#39;facebook_id&#39;</span><span class="p">);</span>
</span><span class='line'>  <span class="k">return</span> <span class="nx">db</span><span class="p">.</span><span class="nx">users</span><span class="p">.</span><span class="nx">findOne</span><span class="p">({</span><span class="nx">fb_id</span><span class="o">:</span><span class="nx">facebook_id</span><span class="p">});</span>
</span><span class='line'><span class="p">}</span>
</span><span class='line'>
</span><span class='line'><span class="kd">function</span> <span class="nx">getUserEvents</span><span class="p">(</span><span class="nx">request</span><span class="p">,</span><span class="nx">response</span><span class="p">){</span>
</span><span class='line'>  <span class="kd">var</span> <span class="nx">success</span> <span class="o">=</span> <span class="kd">function</span><span class="p">(</span><span class="nx">events</span><span class="p">){</span>
</span><span class='line'>          <span class="nx">response</span><span class="p">.</span><span class="nx">write</span><span class="p">(</span><span class="nx">events</span><span class="p">);</span>
</span><span class='line'>  <span class="p">};</span>
</span><span class='line'>
</span><span class='line'>  <span class="kd">var</span> <span class="nx">error</span> <span class="o">=</span> <span class="kd">function</span><span class="p">(</span><span class="nx">err</span><span class="p">){</span>
</span><span class='line'>      <span class="nx">response</span><span class="p">.</span><span class="nx">status</span><span class="p">(</span><span class="mi">500</span><span class="p">).</span><span class="nx">send</span><span class="p">(</span><span class="nx">err</span><span class="p">);</span>
</span><span class='line'>  <span class="p">};</span>
</span><span class='line'>
</span><span class='line'>  <span class="nx">findUser</span><span class="p">()</span>
</span><span class='line'>  <span class="p">.</span><span class="nx">then</span><span class="p">(</span><span class="nx">loadEventsForUser</span><span class="p">)</span>
</span><span class='line'>  <span class="p">.</span><span class="nx">then</span><span class="p">(</span><span class="nx">success</span><span class="p">)</span>
</span><span class='line'>  <span class="p">.</span><span class="nx">fail</span><span class="p">(</span><span class="nx">error</span><span class="p">);</span>
</span><span class='line'><span class="p">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>Notice how code is split into smaller independent functions and how they are chained together using <i>.then</i> and <i>.fail</i> functions. Another important feature of promise library is how exception flow is handled. Compare promise based code with the call back based one above. Observe that errors are handled in each of the call back functions and when using promise, errors are isolated and handle seperately.</p>

<ul>
<li>Key Points

<ul>
<li>Functions are flat, i.e. calling function is responsible for only its own functionality and can be used independently. For example :&ndash; findUser can be used independent of loadEventsForUser.</li>
<li>Spliting sequential code into indenpendent functions which are reusable in multiple scenarios is not always easy. Many times functions are created just to work around Non-blocking reactive pattern.</li>
<li>Functions can be used in other flows and could form reusable components.</li>
<li>Better readability compared to call back option but not as simpile as sequential option</li>
<li>Better exception handling compared to call back option but not as simple as sequential option.</li>
<li>When libraries don&rsquo;t support promises, we end up writing boiler plat code to create promise and to handle async flows.</li>
</ul>
</li>
</ul>


<p><b><i>Conclusion</i></b></p>

<p>Async or Non-blocking IO introduces new challenges on how applications should to be structured and how async call backs can be abstracted away using promises like library. We need Non-blocking IO application since, sequencial blocking IO applications are not scalable. So Non-Blocking IO or Asynchronous code is not a desired feature but a nessesary evil to achive scalability.</p>

<p>Finally, assumption that Non-blocking IO and Asynchronous code are clubed together and one comes with other. Is it possible to get the best of both the worlds, i.e. Sequential code and Non-Blocking IO scalability. In fact, I think there is an option based on Fibers which can provide best of both the worlds. I will cover Fibers and how they achive both Non-Blocking IO and Sequential codebase in the <a href="http://venkateshcm.com/2014/04/Reactor-Pattern-Part-4-Write-Sequential-Non-Blocking-IO-Code-With-Fibers-In-NodeJS/">Reactor Pattern Part 4 Write Sequential Non Blocking IO Code With Fibers In NodeJS</a>.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Zen of Software Design - Part 1]]></title>
    <link href="http://venkateshcm.com/2014/04/Zen-Of-Software-Design-Part-1/"/>
    <updated>2014-04-11T00:00:00+05:30</updated>
    <id>http://venkateshcm.com/2014/04/Zen-Of-Software-Design-Part-1</id>
    <content type="html"><![CDATA[<p>I call it Zen of Software Design.. instead of <a href="http://legacy.python.org/dev/peps/pep-0020/">Zen of Python</a> since it applies to all of software design and not only to python. The poem itself is presented at the bottom of this blog for reference and below is my interpretations and thoughts on it.</p>

<p>Lines 1 to 9 of <a href="http://legacy.python.org/dev/peps/pep-0020/">Zen of Python</a> is covered in this blog, Lines 10 to 19 will be covered in <a href="http://venkateshcm.com/2014/04/Zen-Of-Software-Design-Part-2/">Zen of Software Design : Part 2</a>.</p>

<br/>


<p><b><i>Interpretation</i></b></p>

<p>The way to read &ldquo;better than&rdquo; statements in poem, is to understand that one does not always win over other and both have their place under sun. But the poem advocates one over another when all things are equal and there is a choice to be made. i.e. leaning or favouring one over another.</p>

<br/>


<p><b><i>Beautiful is better than ugly</i></b></p>

<p>While it is easy to understand that beautiful is better than ugly, it is very subjective to know beautiful from ugly. If you look at source code as an art, like a painting, bad code/design will stink (<a href="http://en.wikipedia.org/wiki/Code_smell">code-smell</a>) and make you  uncomfortable instinctively. I don&rsquo;t have standard rules by which you can differentiate beautiful from ugly design (in same sense as you can not set standard rules for beautiful paintings). I guess it comes from looking at different codebase and experience.</p>

<br/>


<p><b><i>Explicit is better than implicit.</i></b></p>

<p>It should be obvious to figure-out what&rsquo;s happening in code, even for someone not familiar with the codebase. Usually implicit design makes it look like black magic without any clue how it is working or where to look for related code. There are two kind of implicit we face in day-to-day work.</p>

<ul>
<li><p>Well known implicit :&ndash; Things which are well documented and have become standard way of doing things. These implicit usually go across project team boundaries. Example : SpringMVC annotations, Rails conventions</p></li>
<li><p>Project implicit :&ndash; Things which project teams builds within the project which is not something a new developer would be acquainted with in other projects.</p></li>
</ul>


<br>


<p>I have seen developers going overboard with Annotations or conventions in projects, where it is difficult to figure-out how things work. A rule of thumb I use to figure out if we have gone overboard is by asking myself the question &ldquo;Can I explain, to a new developer joining team, all the implicit things happening in the project within 1 hour session?&rdquo;.</p>

<br/>


<p><b><i>Simple is better than complex.</i></b></p>

<p>Again this seems very obvious but still elusive. No one wants to create a complex system but creating simple design/software is a complex job.</p>

<p>Few questions which help me be on track of simplicity</p>

<ul>
<li><p>How many execution flows/paths exists?</p>

<p>if there are few execution paths than its easy to keep them in mind and figure out a specific scenario falls in which one of the paths.</p></li>
<li><p>How easy is it to figure-out a given scenario falls under which execution path?</p>

<p>It should be easy to figure that out, if the application is well designed and simple to remember.</p></li>
<li><p>How many exceptions flows exist as against conventional flows?</p>

<p>In every application there are few exceptional scenarios which don&rsquo;t fall under normal execution paths and need exceptional flows for them. These should be minimal and explicitly identified.</p></li>
<li><p>How easy it is to explain high level design to a new developer?</p>

<p>I found this rule of thumb to be very helpful. It becomes obvious when you explain (or imagining to explain) how application works to a new developer. If you can explain it without flinching several times when the developer says &ldquo;ah in scenario x app will do this&rdquo; and you go hmmm its mostly correct but there are some other issues etc.</p></li>
</ul>


<br/>


<p><b><i>Complex is better than complicated.</i></b></p>

<p>Design can be complex because domain is complex but sometime domain is simple but software is designed or implemented in complicated way. Design should be as-complex or as-simple as the requirement need, not more and not less.</p>

<p>The questions I ask to figure out if design is complicated is</p>

<ul>
<li>What part of requirement is causing the design to be complex?</li>
<li>Is the technology choice introducing additional complexity?</li>
<li>Is there any negotiable requirement which can be removed to make it more simpler?</li>
<li>Are we designing the system for future proofing which might not be required?</li>
</ul>


<br/>


<p><b><i>Flat is better than nested.</i></b></p>

<p>When we look at code there are few obvious cases where this is true. For example it is better to have several flat functions than having one long nested function. For example :&ndash; Using Strategy Design Pattern or Command Design pattern to separate code into independent units. Where it is not very obvious and still useful to think is</p>

<ul>
<li>How many layers are we introducing in software architecture?</li>
<li>How many jumps do we need to make to get to the final value (may be cached value or database lookup) ?</li>
<li>Is the path of execution intermingled and can not be modified independently?</li>
</ul>


<br/>


<p><b><i>Sparse is better than dense.</i></b>
<b><i>Readability counts.</i></b></p>

<p>Few times I have questioned myself if single responsibility principle, unit testing, dependency injection and design patterns are good. The reason for this doubt is that after following single responsibility principle, unit testing with dependency injection and following design pattern, a small codebase grows to considerable code size.  I call this new increased codebase sparse compared with earlier code which was dense.</p>

<p>The advantages of sparse code base compared to dense code is</p>

<ul>
<li>It is easier to understand and modify.</li>
<li>It is easier to extend to add more scenarios.</li>
<li>It is easier to isolate an issue and fix it.</li>
</ul>


<br/>


<p><b><i>Special cases aren&rsquo;t special enough to break the rules.</i></b>
<b><i>Although practicality beats purity.</i></b></p>

<p>Good software Architecture/Design usually settle with a set of rules like</p>

<ul>
<li>Execution flows/paths</li>
<li>Logical Architecture Layers and how each layer communicated with another layer.</li>
<li>Inter-process communication protocols</li>
</ul>


<p>Every now-and-then a new requirement which breaks design rules under which application has operating comes in. Usual tendency is to treat this as special case which works differently to existing architecture.</p>

<p>While it might be the right approach in few cases, we should</p>

<ul>
<li>strive to see if this special case can be modelled as one of the existing flows</li>
<li>check if existing rules can be extended to incorporate the new requirement as first class design decision instead of treating it as special case which breaks the rules.</li>
<li>check if we have been adding a lot of special cases and do a course correction if required.</li>
</ul>


<p>On the other hand if they truly are special cases and trying to extend or modelling it has one of the existing flows make design complicated, we should not hesitate to incorporate the new requirement as special case as a pragmatic/practical architect or developer should do.</p>

<p>Lines 10 to 19 will be covered in <a href="http://venkateshcm.com/2014/04/Zen-Of-Software-Design-Part-2/">Zen of Software Design : Part 2</a> of this blog</p>

<pre><code>$ python

&gt;&gt;&gt; import this
The Zen of Python, by Tim Peters

1 Beautiful is better than ugly.
2 Explicit is better than implicit.
3 Simple is better than complex.
4 Complex is better than complicated.
5 Flat is better than nested.
6 Sparse is better than dense.
7 Readability counts.
8 Special cases aren't special enough to break the rules.
9 Although practicality beats purity.
10 Errors should never pass silently.
11 Unless explicitly silenced.
12 In the face of ambiguity, refuse the temptation to guess.
13 There should be one-- and preferably only one --obvious way to do it.
14 Although that way may not be obvious at first unless you're Dutch.
15 Now is better than never.
16 Although never is often better than *right* now.
17 If the implementation is hard to explain, it's a bad idea.
18 If the implementation is easy to explain, it may be a good idea.
19 Namespaces are one honking great idea -- let's do more of those! 
</code></pre>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Reactor Pattern Part 2 - Applications with Non-Blocking I/O]]></title>
    <link href="http://venkateshcm.com/2014/04/Reactor-Pattern-Part-2-Non-blocking-I-O/"/>
    <updated>2014-04-10T00:00:00+05:30</updated>
    <id>http://venkateshcm.com/2014/04/Reactor-Pattern-Part-2-Non-blocking-I-O</id>
    <content type="html"><![CDATA[<p>In <a href="http://venkateshcm.com/2014/04/Reactor-Pattern-Part-1-Non-blocking-I-O/">Reactor Pattern Part 1 : Applications with Blocking I/O</a>, I went through issues faced by a single threaded application to scale to handle more requests pre box.</p>

<p>In this blog, we will look at an alternative solution to maximise CPU usage.</p>

<p>The diagram below from the part 1 blog we can notice that applications require CPU in busts and they have wait periods between the processing busts.</p>

<p><img class="article-img" border="0" height="325" width="480" src="http://venkateshcm.com/img/blog/ThreeThreads.png" class="" style="display: inline-block;"></p>

<p>If we treat processing busts as events and queue events to be executed on a single thread, we can make sure the thread (CPU) is always occupied and thus giving us maximising CPU usage and avoiding unnecessary context switching.</p>

<p>Consider processing blocks as events without any I/O calls within them which can be executed non-sequentially/asynchronously. The code should be split into execution blocks (events) which can be executed separately with other requests events executed between them.</p>

<br/>


<p><b><i>Event Loop</i></b></p>

<p>An event loop is a program loop where a thread waits for events and executes events that occur in a program. For more info on checkout Event Loop</p>

<br/>


<p><b><i>Unix File Descriptors</i></b></p>

<p>Following Unix principle of everything is a file, file descriptor is used to detect events when reading/writing to file, network communication, device communication and inter-process communication. System calls &ldquo;epoll&rdquo; and &ldquo;pselect&rdquo; are used to detect file descriptor state change without blocking application.</p>

<p>The below diagram shows a simplified event loop which goes through four stages in each loop.</p>

<ul>
<li>Check if a new event is created (i.e. a web request has come in or a call back event has occurred) and add new event is added to the queue.</li>
<li>Pick an event from the queue</li>
<li>Execute event</li>
<li>Create a call-back event (i.e. database query or network access call-back when the response has arrived. Call-back events are handled by epoll or pselect.</li>
</ul>


<p><img class="article-img" border="0" height="325" width="480" src="http://venkateshcm.com/img/blog/EventLoop.png" class="" style="display: inline-block;"></p>

<p>The solution described above is a simplified version of Reactor Pattern.</p>

<br/>


<p><b><i>Advantages of Reactor Pattern</i></b></p>

<ul>
<li>Optimal usage of CPU.</li>
<li>Can handle more requests with same hardware.</li>
<li>Can scale above C10K limit</li>
</ul>


<br/>


<p><b><i>C10K Problem</i></b></p>

<p>Historically, Reactor Pattern came into prominence after <a href="http://en.wikipedia.org/wiki/C10k_problem">C10K problem</a> and <a href="http://www.kegel.com/c10k.html">Solution to C10K problem</a> using Non-Blocking I/O succeeded.</p>

<br/>


<p><b><i>Disadvantages of Reactor Pattern</i></b></p>

<ul>
<li>Asynchronous event based code base makes it difficult to understand and structure code. Promise library can help.</li>
<li>Debugging code will be more difficult since stack trace begins from the call-back instead of start of request.</li>
</ul>


<p>Some of the disadvantages can be mitigated by using fiber (ruby fibers, node fibers), will cover Fibers in another blog.</p>

<p>In part 3, we will look at <a href="http://venkateshcm.com/2014/04/Reactor-Pattern-Part-3-Promises-to-solve-callback-hell/">Callback issue in more detail and how promises can help</a> fix callback issues.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Reactor Pattern Part 1 - Applications with Blocking I/O]]></title>
    <link href="http://venkateshcm.com/2014/04/Reactor-Pattern-Part-1-Non-blocking-I-O/"/>
    <updated>2014-04-09T00:00:00+05:30</updated>
    <id>http://venkateshcm.com/2014/04/Reactor-Pattern-Part-1-Non-blocking-I-O</id>
    <content type="html"><![CDATA[<br/>


<p><b><i>Applications with Blocking I/O</i></b></p>

<p>I am assuming a simple scenario of single threaded application like Ruby on Rails Application running on a computer with single CPU. In real world, OS splits CPU time to multiple applications and does a regular context switching.</p>

<p>In a single threaded application like Ruby on Rails Applications, requests are processed by a single thread. When the thread makes a I/O bound call like database query or network call, application/thread is blocked even though it could be used to work on other requests.</p>

<p><img class="article-img" border="0" height="325" width="480" src="http://venkateshcm.com/img/blog/SingleThread.png" class="" style="display: inline-block;"></p>

<p>A solution to get around the above problem is to have multiple applications running on the same box. So when one application&rsquo;s thread is blocked another application&rsquo;s thread can proceed with another request processing. In below diagram there are two applications competing for CPU time and second application consumes CPU between a2 and a1 time. But we still see that CPU is idle between a1 and t1 and between t2 and a2.</p>

<p><img class="article-img" border="0" height="325" width="480" src="http://venkateshcm.com/img/blog/TwoThreads.png" class="" style="display: inline-block;"></p>

<p>To avoid any idle time on CPU we can add more applications, but this will lead to unnecessary context switch which will degrade performance further. For example in the diagram below, third application is switched with second application while third application is still processing a request and needs CPU time.</p>

<p><img class="article-img" border="0" height="325" width="480" src="http://venkateshcm.com/img/blog/ThreeThreads.png" class="" style="display: inline-block;"></p>

<p>As shown in the above diagram, we can notice two issues</p>

<ul>
<li>OS switches CPU from an application which needs CPU for processing.</li>
<li>OS switches CPU to an application which is still waiting for IO.</li>
</ul>


<p>These two issues are due to pre-emptive thread switching. To achieve optimal CPU allocation, application should be able to request for CPU time or give-up CPU time in a cooperative manner instead of pre-emptive switching.</p>

<p><b><i>C10K Problem</i></b></p>

<p>Early in 2000, a single server could not handle more than 10000 connections at a time. It was a limitation under which applications worked and developers were not able to exceed 10000 connections limit on a single box. The solution that was found is to use nonblocking I/O on each thread i.e. Non-blocking IO stared as a scalability soultion to <a href="http://en.wikipedia.org/wiki/C10k_problem">C10K Problem</a>.</p>

<p>Reactor Pattern provides an work around for the above problem using epoll.</p>

<ul>
<li><a href="http://en.wikipedia.org/wiki/Nonpreemptive_multitasking">http://en.wikipedia.org/wiki/Nonpreemptive_multitasking</a></li>
<li><a href="http://en.wikipedia.org/wiki/Preemption_(computing">http://en.wikipedia.org/wiki/Preemption_(computing)</a></li>
<li><a href="http://en.wikipedia.org/wiki/Reactor_pattern">http://en.wikipedia.org/wiki/Reactor_pattern</a></li>
</ul>


<p>In part 2, we will look at <a href="http://venkateshcm.com/2014/04/Reactor-Pattern-Part-2-Non-blocking-I-O/">Non-Blocking IO</a> as an alternative solution to maximise CPU usage.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Silver Bullet Solution]]></title>
    <link href="http://venkateshcm.com/2014/04/silver-bullet-solution/"/>
    <updated>2014-04-08T00:00:00+05:30</updated>
    <id>http://venkateshcm.com/2014/04/silver-bullet-solution</id>
    <content type="html"><![CDATA[<p>While working on a solution for a problem, we try to find a solution which works in all conditions or situations. There are egos built-up on which solution is better or solves all the problems.
But rarely have I seen a solution which fixes the problem completely with-out any side effects.</p>

<p>What usually happens is we</p>

<ul>
<li><p>move the problem (or issue) from one area to other area.</p>

<p>Example :&ndash; In database normalisation we improve performance of add/update by normalising but causing read performance issues.</p></li>
<li><p>solve one problem at the cost of introducing another problem.</p>

<p>Example :&ndash; We introduce redundancy to gain retrieval performance at the cost of multiple updates (due to redundancy).</p></li>
</ul>


<p>This shows that problems are not really solved but just moved around or converted to a different problem.</p>

<p>But we still find and use solutions you might say. Yes, we do and we do it by trading off one type of problem to another type of problem.</p>

<p>So the Art of finding a solution to a problem is identifying problems you are willing to live-with and problems you can not compromise on.</p>

<p>In fact, I have found different solutions by just compromising on a dimension of existing solution and to find a new solution.</p>

<p>Reference</p>

<ol>
<li><p><a href="http://en.wikipedia.org/wiki/No_free_lunch_theorem">No Free Lunch theorems</a></p></li>
<li><p><a href="http://en.wikipedia.org/wiki/CAP_theorem">CAP theorem</a></p></li>
</ol>

]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Guidelines on Restful Web Services]]></title>
    <link href="http://venkateshcm.com/2014/04/Guidelines-Restful-Web-Services/"/>
    <updated>2014-04-08T00:00:00+05:30</updated>
    <id>http://venkateshcm.com/2014/04/Guidelines-Restful-Web-Services</id>
    <content type="html"><![CDATA[<p><p><b><i>Guidelines to get Restful Web Services right</i></b><p></p>

<p><b><i>Uniform Resource handling</i></b></p>

<ul>
<li>Allow discoverability of new resources. Similar to adding new link to existing page (resource) to allow access to new page (new resource).</li>
<li>Take advantage of intermediary components between client and server. ( Caches, Proxies, Firewalls etc)</li>
<li>Follow consistent approach to view/modify/create operations on any resource.</li>
<li>Make conscious trade-offs between cache-ability, discoverability, performance and convenience</li>
</ul>


<p><b><i>Safe Methods</i></b></p>

<ul>
<li>Client requests are readonly.</li>
<li>Client can make duplicate requests without causing unintended side-effects. Similar to loading the page again in browser.</li>
<li>Does not mean server will respond with same response to the new requests. Similar to reloading(F5) a page in browser may get different/modified response (new data) on dynamic web page.</li>
</ul>


<p><b><i>Idempotent Methods</i></b></p>

<ul>
<li>Client can replay the request if client is not certain server has processed the request due network failure or other errors.</li>
</ul>


<p><b><i>Follow HTTP standards</i></b></p>

<ul>
<li><p>Use Request Methods as defined by HTTP</p>

<ul>
<li>Get, Head, Options methods

<ul>
<li>should be safe (readonly) i.e. should not cause side effects on resource representation.</li>
</ul>
</li>
<li>Get, Head, Options, Put, Delete

<ul>
<li>should be idempotent i.e. replay of request (due to network failure or uncertainty) should not cause issues</li>
</ul>
</li>
<li>Post

<ul>
<li>Can cause side-effects and does not guarantee safety or idempotent</li>
</ul>
</li>
<li>Use Request MIME Types to encode representation</li>
<li>Use HTTP status code for responses status</li>
<li>Keep Restful Services Stateless &mdash; maintain state in client.</li>
</ul>
</li>
<li><p>URL of the resource</p>

<ul>
<li>Url of the resource represents the hierarchy.</li>
<li>For example : www.school.com/class/<1>/subject/<english>/

<ul>
<li>In the above example school has classes</li>
<li>classes has subjects</li>
</ul>
</li>
</ul>
</li>
</ul>


<p><b><i>Frequently Asked Questions :</i></b></p>

<ul>
<li><p>Is PUT Request for Creation and POST for updating ?</p>

<ul>
<li>Both PUT and POST can be used for Creating new resource or Updating an existing resource.</li>
</ul>
</li>
<li><p>Deference between PUT and POST ?</p>

<ul>
<li>PUT is idempotent and client can be replay the request if network failure or system error without causing issues on server. Use PUT to completely replace existing resource representation or create new resource representation.</li>
<li>POST is not idempotent and general purpose method without restrictions and corresponding benefits. Use POST when other verbs don&rsquo;t fit.</li>
</ul>
</li>
<li><p>When to use POST ?</p>

<ul>
<li>POST is general purpose method which can be used when other HTTP verbs don&rsquo;t fit well.</li>
</ul>
</li>
</ul>


<p><br/></p>

<pre><code>[Using] POST only becomes an issue when it is used in a situation for which some other method is ideally suited:
e.g., retrieval of information that should be a representation of some resource (GET), complete replacement of 
a representation (PUT), or any of the other standardized methods that tell intermediaries something more valuable
than “this may change something.” The other methods are more valuable to intermediaries because they say something
about how failures can be automatically handled and how intermediate caches can optimize their behavior. POST does
not have those characteristics, but that doesn’t mean we can live without it. POST serves many useful purposes in
HTTP, including the general purpose of “this action isn’t worth standardizing.”
                    --- Roy T. Fielding (http://roy.gbiv.com/untangled/2009/it-is-okay-to-use-post)
</code></pre>

<ul>
<li><p>How does HTTP Safety and Idempotent work during concurrent requests?</p>

<ul>
<li>Safety and Idempotent are defined in non concurrent condition.

<ul>
<li>Good analogy to understand is load a web page in browser and on reloading the page browser can get new version of the page. Server could also deny GET request if agreed number of requests has been reached. User should not worry about making duplicate requests.</li>
</ul>
</li>
<li>For example,

<ul>
<li>A replay GET request can return new representation if resource is modified by another request.</li>
<li>A replay GET request can return modified representation like updated hit/access count.</li>
<li>A failed GET request after allotted number of calls are made to a given resource, does not violate Safety rule.</li>
<li>Get request with authentication token can fail on second request. Safety does not grantee same response every time.</li>
</ul>
</li>
</ul>
</li>
<li><p>Can a single GET request return two or more different resources? Can a resource contain other resources?</p>

<ul>
<li>Yes, they can but it comes at the cost of cache-ability.</li>
<li>For example:&ndash;</li>
</ul>


<p><b><i>Car Resource</i></b></p>

<p>GET /car/:licenceNumber</p>

<pre><code>{
    make : 'Toyota',
    model : 'Rav4',
    color : 'Red',                              
    owner : {
                link : '/car/:licenceNumber/owner',
                firstName : 'John',
                lastName : 'Smith',
                address : {
                                streetName : '300 Boylston Ave E'
                                city : 'SEATTLE',
                                state : 'WA',
                                zipcode : '98102'
                                country : 'USA'
                        }
            }
}
</code></pre></li>
</ul>


<p>The above GET request for resource Car given a license number will return information on car, owner and owner address. Server might expose owner and owner address as resources as-well. As shown below.</p>

<p><b><i>Car Owner Resource</i></b></p>

<p>GET /car/:licenceNumber/owner</p>

<pre><code>{
    firstName : 'John',
    lastName : 'Smith',
    address : {
                link : '/car/:licenceNumber/owner/address',
                streetName : '300 Boylston Ave E'
                city : 'SEATTLE',
                state : 'WA',
                zipcode : '98102'
                country : 'USA'
             }
}
</code></pre>

<p><b><i>Car Owner Address Resource</i></b></p>

<p>GET /car/:licenceNumber/owner/address</p>

<pre><code>{
    streetName : '300 Boylston Ave E'
    city : 'SEATTLE',
    state : 'WA',
    zipcode : '98102'
    country : 'USA'
}
</code></pre>

<p>In this case, Car Resource contains Owner resource which in turn contains owner address resource. But Server exposes two other end point for owner and owner resource.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[How, What and Why of Software Development]]></title>
    <link href="http://venkateshcm.com/2014/04/How-What-And-Why-of-Software-Development/"/>
    <updated>2014-04-07T00:00:00+05:30</updated>
    <id>http://venkateshcm.com/2014/04/How-What-And-Why-of-Software-Development</id>
    <content type="html"><![CDATA[<p>There are three levels at which a developer can operate during software development.</p>

<p><b><i>How</i></b></p>

<p>First Level or basic level is when someone is told what needs to be done. He/She does what is told. At this level the design is handed over to you and you are just implementing someone else&rsquo;s design without fully understanding implications of design.</p>

<p>Change Area :&ndash; Implementation. Software Design is fixed but implementation is altered by team.</p>

<p>Example :&ndash; Software company is provided with design documents with object class specifications and asked to implement the software.</p>

<p><b><i>What</i></b></p>

<p>Second Level or intermediate level is when someone is given a requirement and allowed to design and implement the software without major restrictions on how the requirement is designed or implemented. At this level developer is given freedom to choose different implementation options which achieve the desired requirement.</p>

<p>Change Area :&ndash; Software Design and Implementation. Requirements is not allowed to change by team.</p>

<p>Example :&ndash; Software company is provided with use case documents or requirement documents and asked to implement the software according to specifications given in requirement documents.</p>

<p><b><i>Why</i></b></p>

<p>Advanced Level is when someone understands the business goals of the application and is allowed to choose requirements, design and implementation to achieve the business goal. As Project Managers, Product Owners, Analysts and Developers start working on designing/implementing features and requirements, they understand the business goals and why something is being build.</p>

<p>Change Area :&ndash; Software Requirements, Design and Implementation. Business goal can not be changed by team.</p>

<p>Example :&ndash; Project team is formed with co-sourced members of business and software company and Teams goes through Inception process. During Inception process, the team gains first hand understanding of business goals and how they relate to features/requirements.</p>
]]></content>
  </entry>
  
</feed>
