Author: Tarun Chaudhary

Web Performance Done Right

Sharing my views on my favourite and most interesting topic in the web industry. My views on this post are mostly derived from FrontEnd Masters web performance workshop. So to start with I will state performance golden rule by steve souders which is

80-90% of the end-user response time is spent on the frontend. Start there

Below is the backend frontend split waterfall diagram from linkedin and again I took this from steve souders blog.

Screen Shot 2015-08-15 at 9.36.24 PM

From the graph we can easily conclude that we should spent most of our resource for optimization on frontend. Web is all about measurement and perception and we should know how to balance between these two. If our site loads quickly but our user hate the experience of the way our site loads then we have not actually won. Then the user will start hating us more because may we are loading bizarre content first. So we need to properly balance measurement and perception.

We need to focus on improving the efficiency, speed, memory. We need to focus on how well its doing its job the way it was supposed to do. It doesn’t matter that site loads in 6 seconds but what matters is how much bandwidth it takes to load. Measure your website performance, benchmark it and find out where we need optimization and work on it to make it better.

Optimization is all about critical versus non critical. In our software we can find out which part needs optimization and which didn’t. I will state another quote from Donald Knuth

Programmers waste enormous amount of time … worrying about the speed of noncritical parts of their programs… we should forget about small efficiencies, say about 97% of the time … Yet we should not pass up our opportunities in that critical 3%

Non critical optimization or optimization done wrongly is the root of all evil. This article focuses on mature optimization. Most of the frontend optimization happens in the middle-end (term coined by kyle simpson) which is url routing, templating, headers, caching, ajax, etc. and optimizing middle-end is all about focussing on YSlow, resources (Images, CSS/JS), architecture, communication.


  1. Fewer HTTP Requests
  2. Use a CDN
  3. Expires/Cache-control Header
  4. Gzip
  5. Stylesheets at top
  6. scripts at bottom
  7. Avoid CSS Expressions
  8. External CSS/JS
  9. Fewer DNS lookups
  10. Minify JS/CSS
  11. Avoid Redirects
  12. Avoid Duplicate Scripts
  13. ETags
  14. Cacheable Ajax

Don’t use Expires/Cache-control header and ETags both at the same time, you will end up putting extra headers. Some useful tips on fewer HTTP requests are below:

Fewer HTTP Requests:-

  1. Image Sprites – Combine all images into one and optimize it. Remember horizontal sprites are more performant than vertical sprites because CPU takes more time to process vertical sprites.
  2. Concat JS/CSS – Concatenate (combine all files into one) JS and CSS
  3. GZip – gzip your content. Test if gzipping is done correct or not.

This article contains detailed description about all the above rules.


  1. Image – Compress(lossless) images and sprite it.
  2. Minification – Minify your JS and CSS files. You can use google closure compiler for the same. This article has the list of tools for concatenating and minifying CSS and JS files based on the development environment.


The architectural approach should be like doing the least amount of work for making something visible on the page. Single Page Architecture (SPA) is performant for web applications as it reduces round trips to the server. Take an example of gmail which is a huge single page application, it has lots of data but its performant.


  1. JSON – When it comes to data transfer, JSON size should be optimal. Don’t put duplicate entries, don’t put data which can be easily derived with the help of existing properties. If you put redundant data, it will increase the JSON size and will take more time for transfer.
  2. Web Sockets and Ajax – Use web sockets  over Ajax. Ajax requests are heavier because on every connection it uses extra resources like HTTP packets over the wire, server side resources, connection resources. On the other hand web sockets connection happens only once in the request response cycle. There are 1600 overhead bytes in the request response cycle, so why you want these bytes again and again by using ajax.

That was all about middle-end optimization. There is some useful information that I want to share:

Resource loading:

  1. Preloading Images – Preload your content by using the below code:

    <link rel=”prefetch” href=”image.jpg”>

    var img = new Image();
    img.src = “image.jpg”;

  2. Lazy load – (On demand loading or post loading)
    Use script loaders like LABjs or you can do the following:

    function scriptLoaded(){

    var script = document.createElement(“script”);
    script.src = “abc.js”;

    script.onload = scriptLoaded; // not supported in some browsers so have to use onreadystatechange

    script.onreadystatechange = function(){
    if(script.readyState === “loaded” || script.readyState === “complete”)   {

  3. Reduce abstractions in your JavaScript code.
  4. Use CSS animation over JS animations.
  5. Use websites like jsperf to test performance of your JS code.
  6. Do every UI operation in less than 100 ms because user can perceive an action which takes more than 100 ms. According to research if an action(on button click etc.) takes more than 100 ms then user can treat it as a slow operation. Perceived performance matters.

There are lot of things you need to focus when it comes to optimizing web application. I listed some of them, hope it helps.

My Views on handling website load (Basic version ;-) )

Handling load depends upon various things. May be I am not the right guy for this but I can share my thoughts over it. I made a flowchart which depicts basic website modal:-

Wesite basic Flow

Requests hits LB(Load Balancer) and LB passes the request to the server which is in rotation. Server picks up the request and do some business logic which includes talking to the services and then to the DB and then somehow requests completes and user sees the webpage in the browser.

Load Balancer:-
Every request comes directly to the Load Balancer. Its a smart device that acts as a reverse proxy and distributes network or applications traffic across no. of servers. They are used to increase capacity and reliability of applications. So it basically distributes requests to various servers based on the configured algorithm. Some Algorithm are:-

  • Round Robin
  • Weighted Round Robin
  • Least Connection
  • Least Response Time

A content delivery network or content distribution network is a large distributed system of servers deployed in multiple data centers across the internet. The goal of CDN is to serve content to the end users with high availability and high performance. They are basically used to store static contents. For eg:- Amazon cloud, Akamai, Microsoft Azure, etc.

Handling Load:-

In my views handling load is really hard task. First of all our code should be performant. One should not write unoptimised code. One should take care of the time and space complexities while writing code. When you write code, show it to your friend for code review so that he/she can point out your mistake.

Then comes the DB interaction. Minimum calls should happen to the DB. Use optimised SQL queries is a must. In my opinion the best practise is to write all the data to the file and write a CRON job which writes the data from the file to the DB. So there will be no direct connection to the database and your database will never be choked.

Caching should be used as much as you can. THe data which is constant or does not change like static HTML should be cached. Cache dynamic content for a constant amount of time say for 5 minutes and have some mechanism to refresh the cache. There are various system for caching like memcache, PHP:APC cache, etc.

Move static contents(CSS, JS, Images, Sprites, etc.) to CDN so that the requests for these contents will not hit LB. You can see in flowchart there is a dotted line between CDN and LB which depicts if CDN fails then the requests will go to LB for the particular content.

Write tests for your Application which can detect amount of load your website can handle. Write a script which will hit your website and checks for how many concurrent hits your website can serve response. This way you can judge your website capacity.

I don’t have the 100% knowledge of it but shared my views of what I had now. Will share all the other tips and tricks once I will explore it and will get more and more into it.

My efforts to solve “Travelling salesman problem” through JavaScript

Some days back I was searching for NP hard problems and I found out this “Travelling salesman problem”. I read about this on Wiki and I thought of solving it through JavaScript. I knew about google distance matrix api and got an idea of solving this problem by using this api. I read on wikipedia about some mathematical formulation and all the theories related to this.


“Given a list of cities and the distances between each pair of cities, what is the shortest possible route that visits each city exactly once and returns to the origin city?”.


Suppose we have three cities A, B and C. So by distance matrix api we will get distances of A-A, A-B, A-C, B-B, B-A, B-C, C-A, C-B, C-C. I will thank google for this. Now I will create a matrix of the distances, like this:

|[A-A  A-B  A-C]|       |[0  A-B  A-C]|
|[B-A  B-B  B-C]|  =    |[B-A  0  B-C]|
|[C-A  C-B  C-C]|       |[C-A  C-B  0]|

Just check that the distance from A-B and B-A are not equal because it is the distance related to road. It’s not necessary that the path for A-B will be same for B-A that’s why distances are not equal. So going ahead I will calculate the permutations of all the cities and will store it in an array, like this:
I will name city A as 1, B as 2 and C as 3.
then the permutations will be

and I append “1” at the front and at the end of each permutation. So now our new permutation array will become like this:
[1,1,2,3,1] -> So it will be 1 to 1 to 2 to 3 to 1

After this, I will proceed with the mapping of these permutations and the distance matrix which we created above. So by doing this I will calculate all the distances related to every permutation and the permutation with shortest distance will be your shortest route.

I created a npm package which you can check out here and GitHub repo which you can visit here.  I uploaded the demo on appfog and you can visit it on this link

To solve NP hard problems we have to follow some combinatorial optimization and computational complexity theories. Actually I don’t know about these two phrases mentioned above but this is my approach through JavaScript. I didn’t solved this problem fully, need some optimization though in mapping algorithm I wrote because I think it will fail for large no. of cities.

You are fully welcome to state your own views and comments and if this helped you then I will be touched. 🙂

Hackathon : A portray of hard work and dedication

Having passion and dedication about something drives us in many directions. The same happened with us when me and my friend Joji Augustine, “a team of two” laid our steps in hackathon organised by tnooz at cleartrip office bangalore. We figured out an idea last night and went for it with lot of enthusiasm. After reaching there all of us gathered in a seminar room, there were about 60-70 people and all of them were from reputed companies like Amadeus, Nibodha Technologies, C-soft Technologies, TripThirsty, OLA Cabs, Cleartrip, Yahoo, Armor Technologies, FindMyCarrots, PayPal and we added to the list.

After the seminar we started working on our idea. Our idea was to built a real time group trip planning service that will bring people who wish to travel together into a closed group where they can discuss their travel ideas, details and can also create a travel plan. All these things will happen realtime so that the group users can get update. We were coding, discussing, optimizing and doing all the things possible for creating an effective and optimized solution for the end users. We were not there to just finish our project but we were there to build it in an optimized way as Joy is not in finishing the activity but in doing it. 

We used technologies like Node.js and Redis for realtime communication between users. Also wikipedia pages were scraped and google api like search, images, maps, places were used. We also wrote some algorithms like finding the best possible order of cities based on distance. We will open source some of the algorithms shortly so don’t worry.

So our coding journey was going on a smooth track but half an hour prior to the ending time accidentally our main file got reverted. We got panicked and lost at that time as we were afraid that our hard work will go to waste. But somehow we managed and fixed all the things.

The price of success is hard work, dedication to the job at hand and the determination that whether we win or lose, we have applied the best of ourselves to the task at hand. So at last we won the 2nd prize. We were so happy and had an amazing feeling at that time.

This was our first hackathon. We had an amazing experience and we are looking forward to participate in more and more hackathons. This is just the beginning.

PS Photos will be uploaded soon in this post itself.

Call and apply Invocation Pattern in JavaScript

So I think most of the guys have confusion about call and apply invocation pattern in Javascript. Let me clear all your confusion. First I will talk about apply invocation pattern which I love the most .. 

Apply Invocation Pattern:-

As Javascript is functional object oriented language , Here functions can have methods. The apply invocation pattern allow us to create an array of arguments to use to invoke the function. The apply invocation pattern takes two parameters :-

  1. The value that should be bounded to this pointer
  2. Array of parameters

For example:-

var add=function(a,b){

return a+b;


var array=[2,3]


In above example this pointer is bound to null because here the function add is not an object, so it is not needed. Now Let me show you the way we can change ‘this’ pointer.

var display=function(){



var greeting={

property:”Hi Good Morning”




Here the value of the ‘this’ pointer is bound to an object called ‘greeeting’. So we can explicitly change the value of ‘this’ pointer here.


Call Invocation Pattern:-

So here we can’t create array of parameters. We have to pass all the parameters. So call invocation pattern has a signature like this:- pointer,parameter1,parameter2,…)

For Example:-

var display=function(obj){



var person={



Here the value of this parameter is bound to the person object. So lets take another example of call invocation pattern.

var display=function(text1,text2){



var person={




So the output for the above code will be Hi,Bye,Me,Awesome. 

So this is all about call and apply invocation patterns in javascript. The major difference is that apply invocation pattern allow us to create an array of parameters and pass it as an argument. Thats why I love apply pattern the most. 


My Journey From a Public Sector Bank To redBus

So here I am writing about a shift from being a government officer to a software engineer. I graduated from IIT Rajasthan(Electrical Engg.) in august 2012 and due to my fate I got selected in a public sector bank through campus placement. This bank quoted a huge CTC in front of us. They included everything in that and we got baffled by looking at the quoted CTC and then I made a mood to join it. I appreciate Bank for taking such a good effort in our training in CBD belapur (Navi Mumbai) and one week in NIBM pune. We enjoyed a lot in our training and seriously I learnt a lot there and my presentation skills got a charm from being in dark. Then after training we all were posted at the individual branches. I got a posting in Indore (Madhya pradesh).  I thought that Bank hired IIT graduates for something worth but my feeling got changed when I laid my first step in that branch. There were lots of people and lots of noise everywhere. Then there was a guy sitting who was a typical Government servant. I reached to him and said all the necessary things and he told me with anger to sit and wait. Then I realized there was no respect for us. I came to know that I have to sign on vouchers and I have to fill documents and I have to do everything related to computers right from copy paste to sending mails. They don’t know how to send mails but it’s not the fault of them it’s about generation gap. So after graduating from IIT my job was to sign on vouchers. That was not the work I was looking for and on the very first day I made a mood to leave this place. I Somehow managed there for 7 months and I used to curse myself about joining this Bank every night. Then I studied hard and passed the interview for Redbus and I got selected for a post of software engineer there. Now I am very much concerned about me and my life and want to do something big in this field of software. I want to say about Bank that It helped me shaping my presentation skill but they had ruined the status of IIT’s.

A Book Search Engine in Nodejs

So here it is a result of my learning nodejs and express framework. Journey for this started from my thing about books. I am fond of novels and so I thought let’s build a search engine for books where I can see at what price they are on various merchant websites. I thought this can be good for my learning nodejs. So I learnt nodejs and learnt how express framework works with node. I learnt the request response chain in nodejs and it was a nice experience for me. I have used for isbn database and fetched everything from that and I have also used google book api a lil bit. Sometimes this book search engine will not function because of (They have a problem of handling multiple request at the same time). But don’t worry reload it… 😉 I have hosted this engine on appfog as it is a nice hosting for nodejs. The site is live at here … If you are interested in how this functions then feel free to look at the code on github. The github repo link is Github.

Feel Free to use it and modify it to fit your needs.

My Webpage…

So finally my webpage is up and running. I have learnt many things while creating it. Firstly I want to create it in Ember.js, then I shifted to Node.js and express … then I finally created it with Ember.js , leaving Node.js for other project… ;). So I have Learnt how Node.js can be combined with Ember.js and got a feel of convoy and connect. I integrated some CSS3 transitions so that viewers has some great feel about it and used facebook graph api for my image. So If I will change my profile pic on my Facebook Account then the image at my webpage will update automatically.  I also used google analytics to keep track of users visiting my site. So if you are interested in code then you can grab it from Github Repo Link. Now I have revamped my webpage and it is live at this link.

Ember.js Thought Search engine based on Attitude

As I have mentioned about my tweet search engine in my previous post  named . So looking at it one of my friends said “So what twitter also provides this feature” and I said that “those who are not on twitter can use it as a thought search” but I was not fully satisfied with my application.

Then I got an idea of integrating behaviour in this application to use it as a real thought search engine and so here it is my tweet thought search engine which loads tweets on the basis of a keyword and a behaviour or attitude. Suppose you have to search a thought (Tweet :P) about say “ember.js” and you want to have these thoughts with a positive attitude in it like “ember.js is awesome… “… So go ahead and type ember.js in textfield and choose an Attitude negative/positive/normal ant hit “Go” button and see the magic… 🙂

I have designed this application in ember.js and hosted on and the github repo is here ..

Feel Free to use it and make the most of it.. 🙂