Tuesday, July 24, 2018

Improve performance of web app

Suppose we have a spring boot app which is hosting some of our web services, best way to optimize and improve performance using below:-

1) We can use gatlin tool which can work with an http app and give us a good picture of whats going in terms of request and response time.

Some of the code level optimization:-

1) Use string builder/buffer instead of string. All though with Java 8, there has been some optimization on string pool.
2) Avoid recursive programming as it leads to stack overflow exception at times.
3) When using regular expressions, avoid building patterns every time , better create a static pattern and use it for each validation.
4) Avoid creating/destroying too many threads as they are costly and heavy for JVM to create and destroy.

5) Heap size tuning:-

There are number of factors which should be taken into account while we are tuning the heap size

     (a) On a single instance of the server, how many war to ear files are going to live ?
     (b) How many class files will be loaded (including the third party) ?
     (c) Caching in terms of database and app etc
     (d) How many threads will be opened per app.

One good way to know this is by running Gatlin on the app with proper load and get the metrics and based on that , it can help us decide the numbers to configure for heap size (xms xmx), stack size(xss) etc.

6) Fine tune the sql queries
7) Connection pooling is also a good way to improve the performance of the app.
8) Use JDBC batching instead of executing single query which will also improve performance (We can do that with prepared statement and hibernate in java).
9) Use caching solutions like memcache, redis etc
10) Have a load balancer to scale up your system.

JVM notes

What is stack and heap in JVM ?






How to avoid memory leaks:-

1) Do not hold heavy objects or collections in static variables as they prevent GC to kill the object.
2) Use StringBuffer or builder to concatenate the strings instead of using string as the later will keep filling the string pool which can prevent heap size to exhaust.
3) String is no more stored in permgen space as with java 8 it has been discontinued, so because of string pool, there will be no memory out of exception.
4) Unclosed streams, although with Java 8/7 we can use try with resource and it will auto close.
5) Unclosed connections
6) Start adding objects in HashSet without implementing the hashcode and equals method for these objects, as a result, all objects , even though some of them being equal will keep getting added.

How to inspect memory leakage:-

1) Good code review
2) -verbose:gc parameter to the JVM configuration 
3) Eclipse memory analyzer