DEV Community

Cover image for AWS session management

AWS session management

Session stickiness in Elastic Load balancer

In case of Blue Green/Canary deployment, there are situations when client has to experience the same version of the application for a specified duration. Or client is currently using the app to not switch to the newly deployed (green) version during their session. For a target group (set of instances) we can configure session stickiness, and can mention a duration too (maximum is 7 days). So, all the requests from a client are sent to the same target group for that specified time duration.

Image description

Web cookie

We can save the session in web cookies. In this way the session will be at client side and server doesn’t need to worry about it. Hence it is stateless. Although http request is heavier and there are some security risks too. So ec2 needs to validate the user cookies and cookies need to be less than 4 kb

Image description

*ElastiCache *

Another way is server session, so instead of sending entire data in web cookies we can send just the session id specific for that user. In background we can have multi availability zone spanned ElastiCache (Redis/Memcached) where we would store the same data. And the id to retrieve the data would be the same session id. When there is a second request with the same session id and it goes to another EC2 instance, it will lookup the data in ElastiCache using that session id and retrieve the session data

This is more secure as ElastiCache is the one source of truth and attackers can’t change what’s there in EC

Image description

RDS

We can also save user data in RDS and each instance can get to communicate with RDS. This one is another effective multi AZ stateless solution. As the users navigate through website and reads/asks more information, there is a need of read replica. Well we can use an RDS Master which takes the writes but we can also have RDS Read Replicas with some replication happening. And so, anytime we read stuff, we can read from the Read Replica and we can have up to five Read Replicas in RDS. And it will allow us to scale the reads of our RDS database.

Write Through

There's an alternative pattern called Write Through where an ec2 instance looks in the cache directly for the information. If it doesn't have it then it's going to read from RDS and put it back into ElastiCache so just this information is cached. And the other ec2 instances, they're doing the same thing but this time when they talk to ElastiCache, they will have the information and they get a cache hit and so, they directly get the response right away because it's been cached.

This pattern allows us to do less traffic on RDS. Basically, decrease the CPU usage on RDS and improve performance at the same time. But we need to do cache maintenance now and this has to be done application side.

Image description

Discussion (0)