Almost all of the web apps we build nowadays (at least on the circles I usually move around) rely on the beloved and hated session. This artifact, providing a stateful user wide storage, allows us to relate several HTTP requests together and thus implement the concept of authenticated and secure web applications, that “know” who is using them several requests after they authenticated, despite the root stateless characteristic of the HTTP protocol itself.
To provide a very brief recap, sessions are usually implemented using a hash like memory structure on the server, where each session is stored using a unique identifier string. This string is stored also on the users web browser, typically via a cookie or by sending it back and forth on each request as a POST or GET parameter.
I believe it’s time to move away from this approach and start
building session-less web applications that still provide the same
feature set and security.
You might say that this is part of a REST approach to web applications and that it’s been already beaten enough into our heads… but the truth is it’s not, most of the new apps I see are still making heavy use of session storage and their whole architecture is based around it.
Why are session based web apps bad for us?
So why? Why are we supposed to stop using this thing we have been using for 15 years of web development? Well, session variables are no more and no less than global variables and if you still need arguments against the usage of global variables please either go back to college or ask for a refund.
Still not sure? Some stuff why session variables are mean:
- They promote coupling: disparate pieces of code access the same variable without a defined contract
- They reduce scalability: over usage of session storage increases the app memory usage as the user base increases
- They promote harder to read/debug code: some page/method accesses a session variable that “magically” contains the value you need but it’s usually unclear where this data came from and who put it there.
Ok, you convinced me, now what?
Easy, just stop storing stuff on that session!! No, really, stop it!
I bet that in 99.9% of the use cases, you can build your app by just knowing who the user is. So what you must do is just store the user identification on the session and that’s it.
But you will say: ohhhh, but really, I mean, we display his first and last name on every page, isn’t it just easier and faster if we store them too on the session?
And let me tell you, it’s like crack, you don’t want to go down that road. Keep your architecture pure and stateless, let every controller method receive the information it needs from the HTTP request and return all the information the view needs to render itself. If you are worried about IO performance, implement an appropriate caching strategy on the data access layer, do not use the session for performance tuning.