38
Performance Tips For Web DotNet Platform Mahmud Hasan Lead Software Engineer Jaxara

Performance tips for web

Embed Size (px)

DESCRIPTION

Performance tips for web - DotNet Platform

Citation preview

Page 1: Performance tips for web

Performance Tips For WebDotNet Platform

Mahmud HasanLead Software Engineer

Jaxara

Page 2: Performance tips for web

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.

Areas of Performance Concern

Page 3: Performance tips for web

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.

Areas of Performance Concern

Page 4: Performance tips for web

We know: For asp.net 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:\Windows\Microsoft.NET\Framework\v2.0.50727\CONFIG” folder.

Server configuration

Page 5: Performance tips for web

Web.config in your website’s root directory holds configuration of your website. On the other hand web.config and machine.config in “C:\Windows\Microsoft.NET\Framework\v2.0.50727\CONFIG” folder holds global configuration of your webserver and it is global for all the websites of your server.

Server configuration

Page 6: Performance tips for web

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.

Server configuration

Page 7: Performance tips for web

Process ModelIn 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:

Server configuration

Page 8: Performance tips for web

<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" />

Server configurationProcess Model

Page 9: Performance tips for web

We will see how we can improve asp.net 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:

Server configuration

Page 10: Performance tips for web

<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"/>

Server configurationhttpRuntime

Page 11: Performance tips for web

Now let’s see how some of the server level parameter values can help us to gain performance boost for our applications.

Server configuration

Page 12: Performance tips for web

This parameter defines the number of threads asp.net 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 asp.net 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.

Server configurationmaxWorkerThreads 

Page 13: Performance tips for web

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.

Server configurationmaxIoThreads

Page 14: Performance tips for web

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, asp.net 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.

Server configuration minFreeThreads

Page 15: Performance tips for web

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.

Server configuration minLocalRequestFreeThreads

Page 16: Performance tips for web

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 CLR's 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.

Server configuration minWorkerThreads

Page 17: Performance tips for web

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.

Server configuration executionTimeout

Page 18: Performance tips for web

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 asp.net. 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.

<system.net> <connectionManagement>

<add address="*" maxconnection="100" /> </connectionManagement>

</system.net>

Server configuration Max Connection

Page 19: Performance tips for web

So we have talked about different configurations you may set to tune your application for processModel, httpRuntime and system.net. These values have dependency on each other. So, you must do it very carefully to get the best output.

Server configuration

Page 20: Performance tips for web

An HttpModule is an assembly that implements IHttpModule interface and intercepts all Http requests. By default asp.net 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:\Windows\Microsoft.NET\Framework\v2.0.50727\CONFIG directory.

Server configurationRemove unnecessary http modules

Page 21: Performance tips for web

<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=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>            

<add name="ServiceModel" type="System.ServiceModel.Activation.HttpModule, System.ServiceModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>        

</httpModules>

Server configurationRemove unnecessary http modules

Page 22: Performance tips for web

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 framework\config 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.

Server configurationRemove unnecessary http modules

Page 23: Performance tips for web

Since asp.net 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 asp.net 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 asp.net page where I had used just a GridView control and populated it with 60 rows and 3 columns.

Server Side ImplementationDisable ViewState

Page 24: Performance tips for web

Server Side ImplementationDisable ViewState

Page 25: Performance tips for web

You can disable ViewState in your asp.net 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 asp.net 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

Server Side ImplementationDisable ViewState

Page 26: Performance tips for web

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">Here is your message!</asp:Label>

Server Side ImplementationDisable ViewState

Page 27: Performance tips for web

This is really a 100 level message to most asp.net developers. Sometimes, we tend to store information in ViewState when the information just needs to be persisted during a post back. But as I have already described, we should always try to keep the ViewState size as minimum as possible. So, storing large data in ViewState is always prohibited.

Server Side ImplementationDo not store large data in view state

Page 28: Performance tips for web

When you develop your asp.net based web application, you may like to turn on the trace to profile different matrixes of your application. This is fine. But when you deploy the site to production, you must turn off the Asp.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 still tracing runs in the background and performance will be affected.

Server Side ImplementationTurn trace off

Page 29: Performance tips for web

Turn Debug off. Deploy with release build.

Server Side Implementation

Page 30: Performance tips for web

Use of Page.IsPostBack String Operations

Server Side Implementation

Page 31: Performance tips for web

SSL is Not Cached, so Minimize SSL Use

Server Side Implementation

Page 32: Performance tips for web

Minimize HTTP Requests◦ Use Sprite Images◦ Use Image Maps

Use CDN Cache your static contents Cache your dynamic contents where appropriate.

General Practice

Page 33: Performance tips for web

gZip components

General Practice

Page 34: Performance tips for web

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

General Practice

Page 35: Performance tips for web

Use PNG over GIF Don't re-size Images in HTML Make favicon.ico Small and Cacheable

General Practice

Page 36: Performance tips for web

Create proper indexing De-fragment your indexes

Database

Page 37: Performance tips for web

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”

Database

Page 38: Performance tips for web

Thanks