When you use session in an ASP.NET site, it causes dramatic delays (multiples of 500ms) when loading multiple requests at nearly the same time.
Our website uses session exclusively for its SessionId. We use this key to look up a db table that has user info, etc. This seemed to be a good design since it stored minimal session data. Unfortunately, the SessionId will change if you store nothing in session, so we store Session["KeepId"] = 1;
. This is enough to convince SessionId to not change.
On a seemingly unrelated note, the site serves customized product images through a controller action. This action generates an image if needed then redirects to the cached image. This means that one web page may contain images or other resources, sending dozens of requests through the ASP.NET pipeline.
For whatever reason, when you (a) send multiple requests at the same time and (b) have session involved in any way then you will end up with random 500ms delays about 1/2 the time. In some cases these delays will be 1000ms or more, always increasing in intervals of ~500ms. More requests means longer wait times. Our page with dozens of images can wait 10+ seconds for some images.
Create an empty controller action:
public class HomeController : Controller
{
public ActionResult Test()
{
return new EmptyResult();
}
}
Make a test.html page with a few img tags that hit that action:
<img src="Home/Test?1" />
<img src="Home/Test?2" />
<img src="Home/Test?3" />
<img src="Home/Test?4" />
Run the page & watch the fast load times in firebug:
Do one of the follow (both have the same result):
Add an empty Session_Start handler to your Global.asax.cs
public void Session_Start() { }
Put something in session
public class HomeController : Controller
{
public ActionResult Test()
{
HttpContext.Current.Session["Test"] = 1;
return new EmptyResult();
}
}
Run the page again & notice the occasional/random delays in the responses.
How can I use session but avoid these delays? Does anyone know of a fix?
If there's not a fix, I guess we'll have to bypass session & use cookies directly (session uses cookies).
Session is serialized and stored in aspnet_state.exe process. Stateserver sessions can be stored on a separate machine too. ii. SQL Server: 25% slower than InProc.
There are two ways to set a session timeout in ASP.NET. First method: Go to web. config file and add following script where sessionstate timeout is set to 60 seconds.
The Timeout property can be set in the Web. config file for an application using the timeout attribute of the sessionState configuration element, or you can set the Timeout property value directly using application code. The Timeout property cannot be set to a value greater than 525,600 minutes (1 year).
I took a look at the ASP.NET framework. The class where session state is managed is defined here : http://referencesource.microsoft.com/#System.Web/State/SessionStateModule.cs,114
Here is how it works (simplified code) :
LOCKED_ITEM_POLLING_INTERVAL = 500ms; LOCKED_ITEM_POLLING_DELTA = 250ms; bool GetSessionStateItem() { item = sessionStore.GetItem(out locked); if (item == null && locked) { PollLockedSession(); return false; } return true; } void PollLockedSession() { if (timer == null) { timer = CreateTimer(PollLockedSessionCallback, LOCKED_ITEM_POLLING_INTERVAL); } } void PollLockedSessionCallback() { if (DateTime.UtcNow - lastPollCompleted >= LOCKED_ITEM_POLLING_DELTA) { isCompleted = GetSessionStateItem(); lastPollCompleted = DateTime.UtcNow; if(isCompleted) { ResetPollTimer(); } } }
Summary : if the session item cannot be retrieved because it is locked by another thread, a timer will be created. It will regularly pool the session to try to fetch the item again (every 500ms by default). Once item has been successfully retrieved, the timer is cleared. Additionally, there is a check to make sure that there is a given delay between GetSessionStateItem() calls (LOCKED_ITEM_POLLING_DELTA
= 250 ms by default).
It's possible to change the default value of LOCKED_ITEM_POLLING_INTERVAL
by creating the following key in the registry (this will affect all websites running on the machine):
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\ASP.NET SessionStateLockedItemPollInterval (this is a DWORD)
Another way (which is a hack) is to change the value by reflection :
Type type = typeof(SessionStateModule); FieldInfo fieldInfo = type.GetField("LOCKED_ITEM_POLLING_INTERVAL", BindingFlags.NonPublic | BindingFlags.Static); fieldInfo.SetValue(null, 100); //100ms
DISCLAIMER : exact consequences of lowering this value are unknown. It might increase thread contention on server, create potential deadlocks etc... A better solution is to avoid to use session state or decorate your controller with SessionStateBehavior.ReadOnly
attribute as other users suggested.
As Gats mentioned, the problem is that ASP.NET locks session so each request for the same session must run in serial.
The annoying part is if I ran all 5 requests in serial (from the example), it'd take ~40ms. With ASP.NET's locking it's over 1000ms. It seems like ASP.NET says, "If session is in use, then sleep for 500ms & try again."
If you use StateServer or SqlServer instead of InProc, it won't help - ASP.NET still locks session.
There are a few different fixes. We ended up using the first one.
Cookies are sent in the header of every request, so you should keep it light & avoid sensitive info. That being said, session uses cookies by default to remember who is who by storing a ASPNET_SessionId string. All I needed is that id, so there's no reason to endure ASP.NET's session locking when it's just a wrapper around an id in a cookie.
So we avoid session completely & store a guid in the cookie instead. Cookies don't lock, so the delays are fixed.
You can use session, but avoid the locks on certain requests by making session read-only.
For MVC 3 applications, use this attribute on your controller to make session read-only (it doesn't work on a specific action):
[SessionState(SessionStateBehavior.ReadOnly)]
You can also disable session through MVC routing, but it's a bit complicated.
For WebForms, you can disable session for certain aspx pages.
There are a few ways to speed up session in ASP.NET. First of all a few key points:
Session is thread safe which means it doesn't play nice with concurrent client requests that need to access it. If you need asyncronous processes to access session type data, you can use some other form of temporary storage like cache or your database (for async progress tracking this is necessary). Otherwise the users session info will lock on the context of the request to prevent issues with altering it. Hence why request 1 is fine, then the following requests have a delay. PS this is absolutely necessary to garantee the integrity of the data in session... like user orders in ecommerce.
Session is serialized in and out on the server. A cookie is used to maintain session although it's a different type of cookie which means I wouldn't expect much difference in performance.
So my favourite way to speed up session requests is always to use state server. It takes the in process problems away and also means that in testing you can rebuild your project without having to log in again to your site. It also makes sessions possible in simple load balancing scenarios. http://msdn.microsoft.com/en-us/library/ms972429.aspx
PS I should add that technically out of process state service is supposed to be slower. In my experience it is faster and easier to develop with, but I'd imagine that depends on how it's being used.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With