Storing Anything in ASP.NET Session Causes 500ms Delays

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.

Use Cookies Instead

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.

Use MVC Attributes

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)]

Disable Session for Some Routes

You can also disable session through MVC routing, but it’s a bit complicated.

Disable Session on a Specific Page

For WebForms, you can disable session for certain aspx pages.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)