Performance tips for web


Published on

Performance tips for web - DotNet Platform

Published in: Technology
1 Like
  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Performance tips for web

  1. 1. Mahmud HasanLead Software Engineer Jaxara
  2. 2.  For any website performance depends on the following factors:1. Server configuration.2. Server side implementation.3. Client side implementation.4. Database implementation.5. Hardware configuration.6. Network configuration.
  3. 3.  In this session we will discuss on blue highlighted items below:1. Server configuration.2. Server side implementation.3. Client side implementation.4. Database implementation.5. Hardware configuration.6. Network configuration.
  4. 4. We know: For websites we use IIS as webserver. We hold all of our website specific configurations in web.config file. But do we know about 2 more config files that hold different configurations of our application? Those are machine.config and web.config inside “C:WindowsMicrosoft.NETFrameworkv2.0.5072 7CONFIG” folder.
  5. 5.  Web.config in your website’s root directory holds configuration of your website. On the other hand web.config and machine.config in “C:WindowsMicrosoft.NETFrameworkv2.0. 50727CONFIG” folder holds global configuration of your webserver and it is global for all the websites of your server.
  6. 6.  Now a days most of the sites have dependencies on external services and resources. You can adjust the settings of few server variables to scale your site for better accessibility and performance.
  7. 7.  Process Model In machine.config file you will find the following block under system.web: <processModel autoConfig="true"/> This will set all the process model parameters value to its default. Though the default process model configuration is not defined in machine.config or root web.config, you can see the default values set by an application here:
  8. 8. <processModel enable="true" timeout="Infinite" idleTimeout="Infinite" shutdownTimeout="00:00:05" requestLimit="Infinite" requestQueueLimit="5000" restartQueueLimit="10" memoryLimit="60" webGarden="false" cpuMask="0xffffffff" userName="machine" password="AutoGenerate" logLevel="Errors" clientConnectedCheck="00:00:05" comAuthenticationLevel="Connect" comImpersonationLevel="Impersonate" responseDeadlockInterval="00:03:00" responseRestartDeadlockInterval="00:03:00" autoConfig="true" maxWorkerThreads="20" maxIoThreads="20" minWorkerThreads="1" minIoThreads="1" serverErrorMessageFile="" pingFrequency="Infinite" pingTimeout="Infinite" asyncOption="20" maxAppDomains="2000" />
  9. 9.  We will see how we can improve application’s performance by modifying few of the processModel parameters. Before that, another very important configuration element that has contribution is httpRuntime under system.web. Again, you will not see the default value of this element in either machine.config or root web.config. Here is the default settings:
  10. 10. <httpRuntime executionTimeout="110" maxRequestLength="4096“ requestLengthDiskThreshold="256“ useFullyQualifiedRedirectUrl="false" minFreeThreads="8" minLocalRequestFreeThreads="4" appRequestQueueLimit="5000" enableKernelOutputCache="true" enableVersionHeader="true" requireRootedSaveAsPath="true" enable="true" shutdownTimeout="90" delayNotificationTimeout="5" waitChangeNotification="0" maxWaitChangeNotification="0" requestPriority="Normal" enableHeaderChecking="true" sendCacheControlHeader="true" apartmentThreading="false"/>
  11. 11.  Now let’s see how some of the server level parameter values can help us to gain performance boost for our applications.
  12. 12.  This parameter defines the number of threads can process at a time. The default value of this parameter is 20. It means, if your web server is a single CPU machine, 20 worker threads will be usable by in parallel. For a dual core machine it will be 40. The formula is : maxWorkerThreads * # of CPU. Don’t confuse one important factor here. Say, you have a dual core machine. That does not mean, your webserver can serve 40 simultaneous request based on the default settings. It actually depends on another parameter of httpRuntime. that is minFreeThreads. I will talk on this soon. If your application is less CPU intensive, rather more dependant on database server and external services for data and processing, you may increase the value of maxWorkerThreads significantly. The allowed range of this parameter is 5 to 100. Try to assess which value should be optimum for you. I would set it to 100 for my application. Note that, I knew my application was hosted to a dedicated server and no other applications were served from that server.
  13. 13.  This is a parameter of processModel element. It defines the maximum number of I/O threads to use for the process. Like maxWorkerThreads, the value of this parameter is also multiplied by the number of CPU. So, the folrmula is: maxIoThreads * # of CPU. Default value of this parameter is 20. The range of value it allows is 5 to 100. It is better to have this aligned with maxWorkerThreads. I would set it to 100 for my application.
  14. 14.  minFreeThreads is a parameter of httpRuntime. It determines how many worker threads must be available to start a remote or local request. The default value of this parameter is 8. That means if the value of maxWorkerThreads is set to 100 in a dual core machine, and if minFreeThreads is set to default 8, will be able to serve total 192 requests simultaneously. The formula is: (maxWorkerThreads*number of CPUs)-minFreeThreads You should be careful in setting the value of this parameter. Because, if you increase the value of maxWorkerThreads to 100 and sets a very low value for minFreeThreads, it will hamper your application. Because for every request you application may need some free threads for processing background or parallel tasks. That is why, you always should ensure a good number of free threads in your application. MSDN suggests to set it to 88 * # of CPU. But as my application was hosted to a dedicated server, I would set to 50 * # of CPU. You can think of setting it to an even lower value if your application runs in a dedicated server and does not handle too many asynchronous processing.
  15. 15.  This is a parameter of httpRuntime. It specifies the minimum number of free threads that ASP.NET keeps available to allow execution of new local requests. The specified number of threads is reserved for requests that are coming from the local host, in case some requests issue child requests to the local host during processing. This helps to prevent a possible deadlock with recursive reentry into the Web server. The default value of this parameter is 4. MSDN suggests to set this value to 76 * # of CPU. But according to the ratio of default minLocalRequestFreeThreads and maxWorkerThreads, I would set it to 10 * # of CPU.
  16. 16.  minWorkerThreads indicates the minimum number of threads that should be kept warm. This is a parameter of processModel. The default value of this parameter is 1. Threads that are controlled by this setting can be created at a much faster rate than worker threads that are created from the CLRs default "thread-tuning" capabilities. The suggested value for this parameter is : maxWorkerThreads/2. So, if you set maxWorkerThreads to 100 should set minWorkerThreads to 50. Note that, you should not confuse minWorkerThreads with minFreeThreads.
  17. 17.  This is a configuration parameter of httpRuntime. The default value is 110 seconds. Based on your preference, you may like to alter the value of this parameter.
  18. 18.  MaxConnection is a parameter defined under System.Net.ConnectionManagement. It defines, how many external http connections can be made from a client. Here the client is The suggested value of this parameter according to msdn is 12 * # of CPU. But you can make it even bigger number based on your scenario. If your application has dependencies on many external services for data and it is less CPU intensive you may set it to as maximum as 100. <> <connectionManagement> <add address="*" maxconnection="100" /> </connectionManagement> </>
  19. 19.  So we have talked about different configurations you may set to tune your application for processModel, httpRuntime and These values have dependency on each other. So, you must do it very carefully to get the best output.
  20. 20.  An HttpModule is an assembly that implements IHttpModule interface and intercepts all Http requests. By default loads quite a few HttpModules. Whenever a http request is sent to the server all of the HttpModules take place in in the request pipeline and intercepts each and every request. The default HttpModules are configured at web.config file inside C:WindowsMicrosoft.NETFrameworkv2.0.50727CONFIG directory.
  21. 21. <httpModules> <add name="OutputCache" type="System.Web.Caching.OutputCacheModule"/> <add name="Session" type="System.Web.SessionState.SessionStateModule"> <add name="WindowsAuthentication" type="System.Web.Security.WindowsAuthenticationModule"/> <add name="FormsAuthentication" type="System.Web.Security.FormsAuthenticationModule"/> <add name="PassportAuthentication" type="System.Web.Security.PassportAuthenticationModule"/> <add name="RoleManager" type="System.Web.Security.RoleManagerModule"/> <add name="UrlAuthorization" type="System.Web.Security.UrlAuthorizationModule"/> <add name="FileAuthorization" type="System.Web.Security.FileAuthorizationModule"/> <add name="AnonymousIdentification" type="System.Web.Security.AnonymousIdentificationModule"/> <add name="Profile" type="System.Web.Profile.ProfileModule"/> <add name="ErrorHandlerModule" type="System.Web.Mobile.ErrorHandlerModule, System.Web.Mobile, Version =, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/> <add name="ServiceModel" type="System.ServiceModel.Activation.HttpModule, System.ServiceModel, Version=3 .0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/></httpModules>
  22. 22.  It is obvious that you do not need all of the HttpModules in your application. So, there is no point to keep the un-used HttpModules in your request pipeline and allow them to execute some unnecessary code. For example if you do not use WindowsAuthentication, you can safely remove this module from your configuration. But removing default HttpModules from the global web.config file inside frameworkconfig directory is never wise as it will impace all the websites installed in the server. So you should do this in the web.config of your own application. You can do this in the following way:<httpModules> <remove name="UrlAuthorization" /> <remove name="WindowsAuthentication" /> <remove name="PassportAuthentication" /> <remove name="AnonymousIdentification" /> <remove name="FileAuthorization" /></httpModules> Be confirm that your application does not need a module before you remove it.
  23. 23.  Since webform based application came first, perhaps viewstate is one of the most liked features in the community. You have a server control in your page and after post back you have its value preserved without doing anything. Really for web form developers it is an awesome feature. But while it is a nice feature, it can hamper your site performance too unless you use this efficiently. By default in all pages the viewstate is enabled. So, all the server controls you use in your webform will persist its viewstate. ViewSate always loads in your browser in encoded format. So, the bigger your ViewState is, the bigger your page size becomes. For a small and simple page this may be minor. But when you use a complex and large page where quite a few server controls are used, ViewState can increase your page size significantly. Look at image 1 to see the look of ViewState of a simple page where I had used just a GridView control and populated it with 60 rows and 3 columns.
  24. 24.  You can disable ViewState in your application in 3 levels. 1. application level 2. page level 3. control level. You should always remember the precedence of this settings. Your common sense may tempt you to think you can disable ViewState in application level and even in page level then, you will enable it in control level. But it will not work in this way. In ViewState settings work the other way. Application level setting gets the highest priority, then the page level setting and finally the control level setting. So the suggested way is:1. If you need ViewState even in a single location of your application, keep it enabled at application level.2. The pages where you do not need ViewState at all, disable it in page level.3. The pages where you need ViewState, enable it in page level and then disable it in all the server controls where you actually do not need it. The controls that loads on every get or post request and you do not need its value to be persisted between http requests are most likely the controls where you do not need view state. For example: A GridView control may not need a view state. Application Level Setting > Page Level Setting > Control Level Setting
  25. 25. Disable ViewState in Application Level inside web.config <system.web> <pages enableViewState="false"></pages> </system.web>Disable ViewState in Page Level in Page directive<%@ Page .... EnableViewState="false" %>Disable ViewState at control level<asp:Label runat="server" ID="lblMsg" EnableViewState="false">H ere is your message!</asp:Label>
  26. 26. This is really a 100 level message to most developers.Sometimes, we tend to store information in ViewState when theinformation just needs to be persisted during a post back. But as Ihave already described, we should always try to keep the ViewStatesize as minimum as possible. So, storing large data in ViewState isalways prohibited.
  27. 27. When you develop your based web application, you may like toturn on the trace to profile different matrixes of your application. This isfine. But when you deploy the site to production, you must turn off theAsp.Net Trace.You can turn on the trace through web.config:<trace enabled="true" pageOutput="true"/>This will load the trace data at the bottom of your browser window.When you go to production make sure that you make both “enabled”and “pageOutput” to false. If you just make pageOutput to false stilltracing runs in the background and performance will be affected.
  28. 28.  Turn Debug off. Deploy with release build.
  29. 29.  Use of Page.IsPostBack String Operations
  30. 30.  SSL is Not Cached, so Minimize SSL Use
  31. 31.  Minimize HTTP Requests ◦ Use Sprite Images ◦ Use Image Maps Use CDN Cache your static contents Cache your dynamic contents where appropriate.
  32. 32.  gZip components
  33. 33.  Put Stylesheets at the Top Put Scripts at the Bottom Make JavaScript and CSS External Minify JavaScript and CSS Flush the Buffer Early Split Components Across Domains Reduce Cookie Size Use Cookie-free Domains for static Components
  34. 34.  Use PNG over GIF Dont re-size Images in HTML Make favicon.ico Small and Cacheable
  35. 35.  Create proper indexing De-fragment your indexes
  36. 36.  Write better query ◦ Avoid using cursor ◦ Temporary Table/ Table variable ◦ Avoid Using Dynamic SQL ◦ Avoid “like” when you perform any complex query on large data ◦ Never do “select * from table” ◦ Comment out your print statements ◦ Use Indexed view ◦ Prefer subquery over function if re-usability is not vital. ◦ Use “UNION” over “OR”
  37. 37. Thanks