In this article, I will explain how you can use AWS Hosted ElasticCache to easily share ASP.NET session state data across multiple web servers, therefore eliminating the need for sticky sessions within AWS Elastic Load Balancer (ELB). There are also other options which you can find out about here, here, and here, but I won’t cover those in this article. To do this we will use an out-of-process session state provider downloadable from NuGit called the “RedisSessionStateProvider”. I will also add that I have not build state-full apps or used something like a server side session management layer in quite some time, however this is an existing (and older) app that I am doing some improvements on.
Using an ASP.NET session state provider, your application can maintains a user’s session data between requests. Now, keep in mind the preferred method for scalable, distributed, and performant web applications is to build them as stateless envrionments and as a matter of fact, AWS Lambda does not even support state. However back to the topic at hand, if you are using using the default provider in a clustered envrionment, your load balancer must send every request to the same web server every time. So, distrubitin the load evenly can become a problem and when a server terminates unexpectedly this can cause a poor user experience.
Since this is just an example, I would create a new VPC and Security group in an Availability Zone that you are not currently using, or better yet a separate AWS Account all-together. The security group that you create, will need to allow inbound requests on TCP port 6379.
Setup ElasticCache inside of a VPC within your AWS Account.
- Under the ElasticCache launch a new instance and select Redis.
- Specify the cluster details
- Select the subset within the VPC you created, and the Security Group that has the Open Port specified
- Within Visual Studio, open your we project and add a NuGet reference to RedisSessionStateProvider
- Finally, get the endpoint address of the node instance you just created (click the blue linke in the Nodes clolumn) and add it into the host attribute. Note that you must wait a few minutes for the cluster to launch before the address is available
- Find the endpoint in the Endpoint column and copy this
- Update your web.config file to the following, deploy your app on an EC2 withhin the same subnet as your ElasticCache cluster is located and you should be good to go !
<sessionState mode=”Custom” customProvider=”MySessionStateStore”>
<add name=”MySessionStateStore” type=”Microsoft.Web.Redis.RedisSessionStateProvider” host=”xxxxx.cache.amazonaws.com” accessKey=”” ssl=”false” />