Microsoft.NET

……………………………………………….Expertise in .NET Technologies

Archive for December, 2010

IIS and ASP.NET: The Application Pool

Posted by Ravi Varma Thumati on December 24, 2010

In this article, we will take a look at one of the new features in IIS 6.0, named Application Pool, and demonstrate the use of application pools in isolating ASP.NET Web applications, thereby increasing the reliability of your ASP.NET Web applications. Then, we also will explore how these application pools affect ASP.NET applications in terms of the identity that is used to run your ASP.NET applications. Along the way, we will also look at the steps to be followed for creating application pools and assigning ASP.NET applications to run under a specific application pool. Finally, we will illustrate how to configure an application pool to run using the credentials of a specific user account.

What is an Application Pool?

An Application Pool can contain one or more applications and allows us to configure a level of isolation between different Web applications. For example, if you want to isolate all the Web applications running in the same computer, you can do this by creating a separate application pool for every Web application and placing them in their corresponding application pool. Because each application pool runs in its own worker process, errors in one application pool will not affect the applications running in other application pools. Deploying applications in application pools is a primary advantage of running IIS 6.0 in worker process isolation mode because you can customize the application pools to achieve the degree of application isolation that you need.

When you configure application pools for optimum availability, you also should consider how to configure application pools for application security. For example, you might need to create separate application pools for applications that require a high level of security, while allowing applications that require a lower level of security to share the same application pool. In the later part of this article, we will see how to configure identities at the application pool level.

The Performance tab of IIS 6.0 application pool configuration properties contains settings that monitor the performance of the application pool and the worker processes running in it. These are the Performance configuration properties:

  • Shutdown worker processes after being idle for (time in minutes): This setting limits the number of minutes that a worker process can remain idle before it will be shut down by the system.
  • Limit the kernel request queue (number of requests): This setting limits the number of requests that can be queued for this application pool before 503 HTTP error messages are returned to users.
  • Enable CPU monitoring: This setting activates CPU monitoring and enables the next three settings to be used.
  • Maximum CPU use (percentage): This setting specified the maximum CPU usage allowed before an action is taken.
  • Refresh CPU usage number (in minutes): This setting specifies the intervals at which the CPU usage should be checked.
  • Action performed when CPU usage exceeds maximum CPU use: This setting specifies the action performed when the CPU usage is found to have exceeded the maximum CPU use. Two options are available:
    • Take No Action – IIS logs the CPU maximum usage event in the System event log but takes no corrective action.
    • Shutdown – IIS logs the event and requests that the application pool’s worker processes be recycled, based on the Shutdown Time Limit set on the Health tab.
  • Maximum number of worker processes: This setting specifies the maximum number of worker processes that will be created to handle this application pool.

<Shutting Down Idle Worker Processes>

Although worker processes start on demand based on incoming requests and thus resources are allocated only when necessary, worker processes don’t free up the resources they use until they are shut down. In the default configuration, worker processes are shut down after they have been idle for 20 minutes. This ensures that any physical or virtual memory used by the worker process is made available to other processes running on the server, which is especially important if the server is busy.

Shutting down idle worker processes is a good idea in most instances, and if system resources are at a premium you might even want idle processes shut down sooner than 20 minutes. For example, on a moderately busy server with many configured sites and applications where there are intermittent resource issues, reducing the idle time-out could resolve the problems of resource availability.

Keep in mind though that shutting down idle worker processes can have unintended consequences. For example, on a dedicated server with ample memory and resources, shutting down idle worker processes clears cached components out of memory. These components must be reloaded into memory when the worker process starts and requires them, which might make the application seem unresponsive or sluggish.

< Limiting Request Queues>

When hundreds or thousands of new requests pour into an application pool’s request queue, the IIS server can become overloaded and overwhelmed. To prevent this from occurring, you can limit the length of the application pool request queue. Once a queue limit is set, IIS checks the queue size each time before adding a new request to the queue. If the queue limit has been reached, IIS rejects the request and sends the client an HTTP Error 503: Service Unavailable message.

Requests that are already queued remain queued even if you change the queue limit to a value that is less than the current queue length. The only consequence here would be that new requests wouldn’t be added to the queue until the current queue length is less than the queue limit.

The default limit for an application pool is 4000 requests. On a moderately sized server with a few application pools configured, this might be a good value. However, on a server with multiple CPUs and lots of RAM, this value might be too low. On a server with limited resources or many application pools configured, this value might be too high. Here you might want to use a formula of Memory Size in Megabytes x Number of CPUs x 10 divided by Number of Configured Application Pools to determine what the size of the average request queue should be. This is meant to be a guideline to give you a starting point for consideration and not an absolute rule. For example, on a server with two CPUs, 1024 MB of RAM, and twenty configured application pools, the size of the average request queue limit would be around 1,000 requests. You might have some application pools configured with request queue limits of 750 and others with request queue limits of 1,250. However, if the same server had only one configured application pool, you probably wouldn’t configure a request queue limit of 10,000.

<CPU Monitoring>

Typically, you’ll want to set a value to at least 90 percent. However, to ensure that worker processes are recycled only when they’re blocking other processes, you should set the value to 100 percent.

In most cases you won’t want to check the CPU usage more frequently than every five minutes. If you monitor CPU usage more frequently, you might waste resources that could be better used by other processes.

<Configuring Multiple Worker Processes for Application Pools>

Multiple worker processes running in their own context can share responsibility for handling requests for an application pool. This configuration setting is referred to as a Web Garden. When you define a Web Garden, each new request is assigned to a worker process according to the round-robin load balancing technique.

If a single application is placed in an application pool serviced by multiple worker processes, any and all worker processes available will handle requests queued for the application. This is a multiple-worker-process-to-single-application configuration, and it is best used when you want to improve the application’s request handling performance and reduce any possible contention for resources with other applications. In this care the application might have heavy usage during peak periods and moderate-to-heavy usage during other times, or individuals using the application might have specific performance expectations that must be met.

If multiple applications are placed in an application pool serviced by multiple worker processes, any and all worker processes available handle the requests queued for any applicable application. This is a multiple-worker-process-to-multiple-application configuration, and it is best used when you want to improve request handling performance and reduce resource contention for multiple applications but don’t want to dedicate resources to any single application. In this case the various applications in the application pool might have different peak usage periods or might have varying resource needs.

It’s important to note that worker processes aren’t started automatically and don’t use resources until they are needed. Rather, they are started as necessary to meet the demand based on incoming requests. For example, if you configure a maximum of five worker processes for an application pool, there may be at any given time from zero to five worker processes running in support of applications placed in that application pool.

You also need to keep in mind that when you assign multiple worker processes to a busy application pool that each worker process sues server resources when it’s started and might affect the performance or applications in other application pools. Adding worker processes won’t resolve latency issues due to network communications or bandwidth, and it can reduce the time it takes to process requests only if those requests were queued and waiting and not being actively processed. A poorly engineered application will still respond poorly, and at some point you’d need to look at optimizing the application code for efficiency and timeliness.

Web Garden

Web garden is the equivalent application pool setting for the webGarden and cpuMask ASP.NET process model settings. To enable Web garden, set the Maximum number of worker processes to a value higher than 1. This value also determines the maximum number of processes for the application pool.

Because Web gardens enable the use of multiple processes, each process will have its own copy of application state, in-process session state, caches, and static data. Web gardens should not be used for all applications, especially if they need to maintain state. Be sure to benchmark the performance of the application before deciding whether Web garden mode is appropriate.

When using a Web garden, it is important to understand how session state and round robin works. It is also important to consider of how other application pool settings affect the application.

Session State in a Web Garden Using Worker Process Isolation Mode

When using session state, be aware that worker process isolation mode does not support routing requests back to a process that originated the request back. When an application is running under a Web garden with ASP session state or application state, the application needs to have its requests sent back to the originating process. When using the IIS 6.0 application pooling, make sure the application keeps a connection open so that its requests are sent back to the appropriate process. If the connection is not kept open, the request will be sent to the next available worker process servicing the Web garden.

Round Robin in a Web Garden Using Worker Process Isolation Mode

Round robin is a method of load balancing for the application. As each request arrives, it is automatically sent to the next sequential process. For example, if a Web garden has 4 processes, requests are sent to processes 0, 1, 2, and 3, in that order. The cycle is then repeated for additional requests.

Application Pool Parameters in a Web Garden Using Worker Process Isolation Mode

Some application pool settings have Web garden–specific behavior. The following table summarizes these behaviors.

Application pool setting Behavior
AppPoolQueueLength The value of this parameter is not affected. However, requests are distributed by round robin across the worker processes servicing the Web garden.
DisallowOverlappingRotation No behavior change in a Web garden.
DisallowRotationOnConfigChange No behavior change in a Web garden.
IdleTimeout Individually calculated for each process, so that each process times out independently. Depending on which routing algorithm is chosen, the number of processes will automatically configure itself to the load.
LoadBalancerCapabilities No behavior change in a Web garden.
OrphanAction No behavior change in a Web garden.
OrphanWorkerProcess No behavior change in a Web garden.
PeriodicRestartTime This parameter has a changed meaning in a Web garden. In a Web garden, this parameter specifies the time interval in which all processes are recycled. Processes take turn recycling at even intervals within the specified time amount. For example, if a Web garden has four processes and the PeriodicRestartTime is set to 20 hours, the first process is recycled after five hours, the second process is recycled after 10 hours, and so on.

Note If a process crashes, the replacement process is given a run time value of PeriodicRestartTime. This allows the process that crashed to recycle, along with other processes, within the specified PeriodicRestartTime.

PeriodicRestartRequests This parameter has a changed meaning in a Web garden. In a Web garden, this parameter specifies that all processes are recycled after a certain number of requests. Processes take turn recycling at even intervals within the specified number of requests. For example, if a Web garden has four processed and the PeriodicRestartRequests is set to 40,000 requests, the first process is recycled after 10,000 request, the second process is recycled after 20,000 requests, and so on. After the initial processes are recycled, the next set of processes is assigned a PeriodicRestartRequests value of 40,000.
PeriodicRestartSchedule No behavior change in a Web garden. If an administrator decides to use schedule-based recycling, all Web garden processes are recycled at the same time.
PingInterval No behavior change in a Web garden.
PingResponseTime No behavior change in a Web garden.
PingingEnabled No behavior change in a Web garden.
RapidFailProtection No behavior change in a Web garden. For example, the total failures across a Web garden are calculated and then compared over a time interval. This provides and additional level of resilience.
RapidFailProtectionInterval No behavior change in a Web garden. For example, the total failures across a Web garden are calculated and then compared over a time interval. This provides and additional level of resilience.
RapidFailProtectionMaxCrashes No behavior change in a Web garden. For example, the total failures across a Web garden are calculated and then compared over a time interval. This provides and additional level of resilience.
SMPAffinitized No behavior change in a Web garden.
SMPProcessorAffinityMask In IIS 5.0 isolation mode, you can have only as many worker processes as CPUs. In worker process isolation mode, multiple CPUs can service a single worker process.
ShutdownTimeLimit No behavior change in a Web garden.
StartupTimeLimit No behavior change in a Web garden.

Idle Timeout

Idle timeout is the equivalent application pool setting for the idleTimeout ASP.NET process model setting. It specifies the amount of time before a worker process or application pool is shutdown due to inactivity. Idle timeout is enabled and set to 20 minutes by default. You can specify a different time limit by changing the value in the spin box. To disable Idle timeout, clear the check box.

Request Queue Limit

Request queue limit is the equivalent application pool setting for the restartQueueLimit ASP.NET process model setting. It specifies the maximum number of requests that are queued in the ASP.NET ISAPI while waiting for the worker process to start after an abnormal termination. Request queue limit is enabled and set to 1000 requests by default. You can specify a different limit to the number of requests queued by changing the value in the spin box. To disable Request queue limit, clear the check box.

Creating a new Application Pool

Creating a new application pool is a very simple process that is carried out by using the IIS manager. When you create a new application pool, you have the following two options:

  1. You can either create a new application pool from scratch or
  2. You can create a new application by importing the configuration settings from an external XML file

To create a new application pool from scratch, right-click on the Application Pools node from the tree view and select New->Application Pool from the context menu. You will be presented with the following screen, where you need to enter a name for the application pool.

When creating a new application, you also have the option of inheriting the settings from an existing application pool. For example, if you want your new application pool to inherit the settings from the DefaultAppPool, you can do that by selecting the option Use existing application pool as a template in the above screen. After you pick this option, the Application Pool name dropdown box will be enabled from where you can select an existing application pool.

After the pool is created, you can save the settings of the application pool to an external XML file any time by right-clicking the application pool and selecting the option All Tasks->Save Configuration to a File that is available from the context menu. This is an extremely useful feature that makes it possible for you to easily recreate the same application pool on the same server or on a different server with minimal effort.

Configuring Identity for ASP.NET Web Applications

In previous versions of IIS, worker processes ran as LocalSystem, a powerful account that has system administrator privileges on the server. Because LocalSystem has access to almost all resources on the operating system, this caused security implications. As mentioned previously, in IIS 6.0, you can set the identity of the worker process at the application pool level. The identity of an application pool is the account under which the application pool’s worker process runs. By default, application pools operate under the NetworkService account, which has low-level user access rights. The NetworkService account has the following seven privileges:

  • Adjust memory quotas for a process
  • Generate security audits
  • Log on as a service
  • Replace process level token
  • Impersonate a client after authentication
  • Allow logon locally
  • Access this computer from the network

By running the worker process using a very low-privileged account such as NetworkService, you can reduce the security vulnerability. However, by using IIS manager, you can configure the application pool to run as any of the following pre-defined accounts:

  • NetworkService
  • LocalSystem
  • LocalService

To configure identity for an application pool, right-click the application pool and select Properties from the context menu. In the Properties dialog box, select the Identity tab and you will see the following screen.

In the above dialog box, when you select the Predefined option, you can select any of the pre-defined accounts from the dropdown box. Instead of using a pre-defined account, if you want your application pool to run under a different account, select the Configurable option and then set the User name and Password in the textboxes. This approach is particularly useful especially when you are running multiple applications or sites on one Web server. For example, if an ISP hosts two companies—who may even be competitors—on one Web server, it has to guarantee that these two applications run in isolation from each other. More importantly, the ISP has to make sure that a malicious administrator for one application can’t access the data of the other application. You can accomplish this level of isolation by using the configurable worker process identity.

Configuring Identity for an Application Pool

To demonstrate how to configure the identity for an application pool and how ASP.NET uses that identity information at the execution time, we will create a very simple ASP.NET application. We will start off by creating a new ASP.NET application named IdentityExample by using the New Project dialog box in Visual Studio.NET. After the project is created, if you open up IIS manager, you will find that the IdentityExample project is created in the default application pool named DefaultAppPool.

Now, let us add the following lines of code to the Page_Load event of the default Web form WebForm1.aspx.

private void Page_Load(object sender, System.EventArgs e)
{
  Response.Write(
   "ASP.NET application executes using the
           identity :: <b>" +
    WindowsIdentity.GetCurrent().Name + 
         "</b><br>");
}

As you can see from the above code, we simply display the name of the account that the ASP.NET Web application uses to process the service. If you execute thise code by navigating to the page from the browser, you will see the following output.

The above output just reinforces the fact that, by default, the Web application runs using the NetworkService account. Let us change the identity of the DefaultAppPool and then look at the output of our Web application. To do this, right-click the DefaultAppPool node from the IIS manager and select Properties from the context menu. In the properties dialog box, navigate to the Identity tab and select the Configurable option and specify a valid user name and password. Once entered, the screen should look like the following.

Now if you execute your application, you will see the following output.


As expected, the output reflects the change that we made using the IIS manager.

Associating an ASP.NET Web Application with an Application Pool

Create a new Visual Studio.NET project named IISIntegration using the New Project dialog box as shown in the following screen shot.

After creating the new project, if you open up IIS Manager, you will find that the IISIntegration project is created under an application pool named DefaultAppPool. As the name suggests, by default, all the newly created ASP.NET Web applications are created under this application pool. This is shown in the following screen shot.

To associate the IISIntegration ASP.NET Web application with the application pool named DemoAppPool, select the Web Sites node that is present under the Machine Name node in the IIS manager. Then, select Default Web Site-&IISIntegration from the treeview and right-click it to select Properties from the context menu.

In the Properties dialog box shown above, you can change the Application Pool using the Application Pool dropdown option in the Directory tab. Because we want our Web application to run under the DemoAppPool, select DemoAppPool from the list.

Recycling Worker Processes and Their Impact on Application State Information

If a Web application contains code that causes problems, and you cannot easily rewrite the code, it might be useful to limit the extent of the problems by periodically recycling the worker process that services the application. You can accomplish this by using what is known as Worker Process Recycling. Worker process recycling is the replacing of the instance of the application in memory. IIS 6.0 can automatically recycle worker processes by restarting the worker process, or worker processes, that are assigned to an application pool. This helps keep problematic applications running smoothly, and minimizes problems such as memory leaks. You can trigger the recycling of the worker processes assigned to an application pool by using worker process recycling methods that are based on elapsed time, the number of Hypertext Transfer Protocol (HTTP) requests, a set time of day, and two kinds of memory consumption, in addition to recycling on demand.

To configure all the above settings, go to the Properties window of the application pool in which your Web application is running using the IIS manager. Using the Recycling, Performance, and Health tabs in the Properties window, you can specify values for the above settings. Navigating to the Performance tab in the Properties dialog box of the DemoAppPool results in the following output.

When you set the recycling of worker processes using IIS manager, you also need to take the state management strategy of your ASP.NET application into consideration. Because every time the worker process is recycled, the ASP.NET state information will be lost rendering the application in an invalid state. One alternative to overcome this issue is to maintain state data external to the worker process, such as in a database. However, moving data to an external database to allow recycling can affect server performance in the following two ways:

  • Performance is reduced because of the added data management that is needed to move the data between the application and the database.
  • Recycling flushes any in-process data caches, so the caches need to be rebuilt.

If you have an application pool with applications that depend on state data, you must decide whether or not to recycle the worker processes that are assigned to that application pool. If you store state in the same process as that of IIS, and you don’t want the state information to be lost, you must not recycle a worker process using the application pool configuration settings.

Conclusion

In this part, we looked at what application pools are and their role in increasing the reliability of your ASP.NET Web applications. We also understood that by allowing different ASP.NET applications to run under their own application pool, we can also set different identities, thereby controlling the security permissions for different ASP.NET Web applications.

Advertisements

Posted in 1. Microsoft.NET | Tagged: | 1 Comment »