I’m looking to implement sessions for a web server that I’m developing in my free time. Currently, it had cookie support, so users could implement their own session management, but this is something that should be handled by the web server. I’m faced with two secure options:
- Store it in memory, and expire the session if the user does not make a request over a certain amount of time. This has the advantage of speed; accessing the memory is fast. It’s also easier to implement, but this is a non-concern.
or
- Store it in a database of some sort, and expire the session if the last_access time is over a certain amount of time. This has the advantage of persistence; a server shutdown, restart, etc. will not impact this. It would also be possible to use a database on another server for this purpose, allowing multiple servers to share sessions (e.g. for load balancing).
I’m trying to decide whether keeping sessions over a restart or shutdown is important enough to sacrifice the speed of storing it in memory, or whether I should simply cache sessions and store them in a database of some sort as a “backup”, e.g. in the event of a crash or a restart, I would restore sessions (if they’re not expired) from the database. Edit: This is in a single-threaded environment. It’s not an option to multithread it.
From the perspective of the user of the web server, which is more important? Speed, or persistence?
2
Why not both?
I suppose you want a quick turnaround, without waiting for the session to get stored in the database. But this does not prevent you from putting the data into the database eventually, because probably users do not register a new session at every request for prolonged periods.
I’d have an in-memory cache of a limited size, a queue, and a database. When a new session is registered, it stays in the cache and is put into the queue. A background thread keeps reading the queue and putting the new sessions into the database. (Another background process would periodically expire them.)
Session creation and reuse stays instant: immediately following requests find the session in the cache and don’t hit the database at all. Requests for the same session a week later probably will not find it in the cache, and will hit the database once, populating the cache.
Of course it is possible to overpower this scheme by registering so many sessions so fast that most requests will be unable to find recently-created sessions in the cache, and won’t find the data in the database, because the database will not keep up with the queue. But without the cache + queue, even a smaller amount of request would kneel the server.
1