10. Custom SessionRepository

Implementing a custom SessionRepository API should be a fairly straightforward task. Coupling the custom implementation with @EnableSpringHttpSession support allow to easily reuse existing Spring Session configuration facilities and infrastructure. There are however a couple of aspects that deserve a closer consideration.

During a lifecycle of an HTTP request, the HttpSession is typically is persisted to SessionRepository twice. First to ensure that the session is available to the clients as soon as the client has access to the session ID, and it is also necessary to write after the session is committed because further modifications to the session might be made. Having this in mind, it is generally recommended for a SessionRepository implementation to keep track of changes to ensure that only deltas are saved. This is in particular very important in highly concurrent environments, where multiple requests operate on the same HttpSession and therefore cause race conditions, with requests overriding each others changes to session attributes. All of the SessionRepository implementations provided by Spring Session use the described approach to persisting session changes and can be used for guidance while implementing custom SessionRepository.

Note that the same recommendations apply for implementing a custom ReactiveSessionRepository as well. Of course, in this case the @EnableSpringWebSession should be used.