Web Engineering 115: Sessions and Scaling
Having just finished a release of a new product as Lead Software Developer at Spinning-Fox, I realized that it is not obvious to most developers that Sessions are hard, and especially so once you move past single server apps.
Most session storage systems default to writing files on the filesystem of the server. This is fine and dandy when your app is a baby, and you don’t need to worry about scaling it from 1 to 2 servers. Even then with technologies like Sticky-Sessions you can get away with not dealing with horizontal scaling properly.
But since you’re here, let’s actually talk about how to do it properly. Let’s say we need to have auto-scaling inside our app so we can handle bursts of unbalanced traffic. Sticky-Sessions is kind of meh. We want to do it properly. We need a better session storage solution, what are the options?
Essentially we want another piece of infrastructure to manage the sessions (Kind of like SRP, but in terms of infrastructure). I much prefer Redis / ElasticCache if you’re in AWS land. Redis is a key-value storage solution and a goto for session / application level caching. It also supports pooling in case you are facebook and need multiple redis servers. But this all comes at a cost. The cost is development time.
session_start(); //php
Well this just isn’t going to work anymore. You’re going to need to do a few things…
Either add this to your bootstrap…
ini_set('session.save_handler', 'redis');
ini_set('session.save_path', "tcp://localhost:6379");
Or set them in your php.ini config.
Well that’s pretty much it. Use session_start() and ur good to go. any $_SESSION[] will now write to redis. Keep in mind that accessing $_SESSION directly is a bad idea (SRP and what not). You should have a class that handles the writing and reading of Session data, I like to call it the SessionProxy class. The benefits of this are to get strong types on data in and out of the session, which just makes for a great developer experience and will lead to less bugs. I also recommend using Fluent Interfaces with the proxy classes.
In the end refactoring your app to stop using Globals is an important way to limit the scope and brain space required to work inside your app. A SessionProxy allows every developer to understand what is or is not in the session. Having Redis back your sessions is a great way to initially scale an app from 1 to 2 application servers.
Come back to read about application caching using redis and PSR-6.