DEV Community

Discussion on: Why you should never use sticky sessions

Collapse
 
moaxcp profile image
John Mercier

Interesting. I just read this yesterday which mentions these problems. The reasoning behind sticky sessions is explained here:

We noted the example code above is naïve as it doesn’t deal with the fact the session cache is not thread safe. Even this simple example is subject to race conditions that may result in the page count being incorrect. The solution to this problem is to use the traditional thread locks and synchronization features available in Java, but these features are only valid within a single JVM. This means we must ensure that client requests are always directed to a single Tomcat instance, which in turn means that only one Tomcat instance contains the single, authoritative copy of the session state, which can then ensure consistency via thread locks and synchronization. This is achieved with sticky sessions.

I think a lot of these decisions rely on how the application is written and how much performance is needed for a single session. When scaling there is a whole new level of race conditions to consider which could result in rewriting the entire application. I think sticky sessions can be a good balance to rewriting applications as long as a single session will not require scaling past one instance.

Collapse
 
gkoniaris profile image
George Koniaris

Hey John,

Thanks for commenting. I would not rewrite a piece of my application if it was already relying on the server's internal state, but I would make sure that I have some kind of rate limit on these endpoints to avoid server overloading. Now, for race conditions, you can use session storage like Redis and perform atomic operations on the values of the session. Have you ever found any case where it's not possible to use an async service, like Redis, for this job?

Collapse
 
moaxcp profile image
John Mercier

No I think something like that would make sense.