Introduction: Building a fast session store for your online applications
Follow step-by-step instructions to learn how to use Amazon ElastiCache for Redis as a distributed cache for session management
There are many ways of managing user sessions in web applications, ranging from cookies-only to distributed key/value databases, including server-local caching. Storing session data in the web server responding to a given request may seem convenient, as accessing the data incurs no network latency. The main drawback is that requests have to be routed carefully so that each user interacts with one server and one server only. Another drawback is that once a server goes down, all the session data is gone as well. A distributed, in-memory key/value database can solve both issues by paying the small price of a tiny network latency. Storing all the session data in cookies is good enough most of the time; if you plan to store sensitive data, then using server-side sessions is preferable.
In this tutorial you will learn how to use Amazon ElastiCache for Redis as a distributed cache for session management. You will also learn the best practices for configuring your ElastiCache nodes and how to handle the sessions from your application.
The Amazon ElastiCache node created in this tutorial is eligible for the AWS free tier.
Time to complete: 20 minutes
This tutorial illustrates some mechanisms with examples written in Python and the Flask microframework for web development. Hopefully the code will be easy to translate to your language of choice.
In order to complete this tutorial, you need access to an EC2 instance. If you don’t already have one running, follow these instructions to provision one.
Make sure the security group of that instance allows incoming TCP connections on port 5000.
Once you have access to your EC2 instance, run the following commands:
$ sudo yum install git $ sudo yum install python3 $ sudo pip3 install virtualenv $ git clone https://github.com/aws-samples/amazon-elasticache-samples/ $ cd amazon-elasticache-samples/session-store $ virtualenv venv $ source ./venv/bin/activate $ pip3 install -r requirements.txt $ export FLASK_APP=example-1.py $ export SECRET_KEY=some_secret_string $ flask run -h 0.0.0.0 -p 5000 --reload
This will start a Flask application on port 5000. If the server doesn’t report any errors, you should be able to visit the application from the command line in your EC2 instance with the following line:
$ curl http://127.0.0.1:5000/
It it works, you can now fetch the public IP address of your EC2 instance and try to access the web application from your computer.
In order to access the application from your browser, copy the Public DNS name of your EC2 instance and append the port number 5000. For example, given the address in the screenshot, the URL would be http://ec2-54-175-201-152.compute-1.amazonaws.com:5000/.
Now you are all set to start the tutorial.
This workshop is divided into three modules.