13 Jul 2011

Load-Balanced IIS 7.5 Web Server ASP.NET SQL Session State problem

We had a problem recently with an ASP.NET website where the users' sessions were behaving oddly - session data appearing, disappearing and re-appearing.

As the site is hosted on two webservers using network load-balancing, I figured the problem must have something to do with that, but I was puzzled because I thought my configuration's use of a single, central, standard ASP.NET SQL Session State database would remove such problems.

Well, apparently this is only true if IIS is set up correctly and consistently on all your webserver machines. You see, if you check the AspStateTempApplications table in the AspState database, you'll see reference to website Instance IDs (e.g. /W3SVC/1/Root, /W3SVC/2/Root etc). So, ASP.NET hooks up your browser's session cookie to your session data using the Instance ID of the website serving you.

But what if the load-balanced servers host several sites, and due to the order of setup, your site on one server has a different Instance ID to the one on the other? That's right, you end up getting served up with different session data depending which server the load-balancer allocates to your HTTP request.

So, how to fix the prob? You just need to get the IIS Instance IDs in sync on the 2 servers. For IIS 6 there's a script you can run.

For IIS 7.5 however, you can't use adsutil.vbs style solutions anymore. However that's because the Metabase is old-hat and we rock config files now baby! You can set the id of a site using its id attribute found in C:\Windows\System32\inetsrv\config\applicationHost.config. You need admin privs to edit that, and need to restart IIS afterwards.

Easier still,

1. Remote Desktop onto server 1, open IIS Mgr, click on the problem Site and choose Advanced Settings in the sidebar.
2. Change the ID to something unique e.g. 10. Click OK.
3. Restart the web service (c:\windows\system32\iisreset /restart)

Do the same for server 2 (ensure the Site ID is the same as on server 1).

Again, restart the website after the change for it to take effect.
If I helped you out today, you can buy me a beer below. Cheers!