Out of process session state vs. explicit state management

time to read 2 min | 332 words

The question came up in the alt.net mailing list, and I started replying there, before deciding that it would make a great post. I actually want to talk specifically about the notion that came of avoiding explicit state management in favor of out of process session state (on top of a database or memcached).

The problem is that those two are not interchangeable. Using a session make it easy to preserve the illusion of statefullness on the web, but it is an illusion. In general, you have to give me pretty good reasons before I will go with an abstraction layer. Session state make a lot of sense, but it carry with it its own set of problems.

On the face of it, explicit state management (making direct call to memcached or database) seems like it share the same problem, with the additional problem is that you don’t get the session abstraction to manage that for you.

That is true, but there are distinct advantages for that.

  • Different pieces of the state usually have different longelivity, refresh rate and scope scenarios. With a session, you get a single option (usually predetermined) for all of them.
  • You can pick and choose what you want to read, resulting in less data moving on the network. With the session, you have to get it all or none at all.
  • Reduced writes, because you only write on changes, the session has to flush itself (or do non trivial change tracking) every time.

There is also another issue, of concurrency. With a session, in order to maintain the sequential facade, you take a lock on the session for the duration of the request. That tend to create contention if you have concurrent request from the same user (which are quite frequent now, thanks to ajax and multi tabs), I now that we had to write code around that several times.