Relational databases are a cornerstone of most applications. When it comes to scalability and low latency though, there’s only so much you can do to improve performance. Even if you add replicas to scale reads, there’s a physical limit imposed by disk based storage. The most effective strategy for coping with that limit is to supplement disk-based databases with in-memory caching.
In this tutorial, you will learn how to boost the performance of your applications by adding an in-memory caching layer to your relational database. You will implement a cache-aside strategy using Amazon ElastiCache for Redis on top of a MySQL database. The cache-aside strategy is one of the most popular options for boosting database performance. When an application needs to read data from a database, it first queries the cache. If the data is not found, the application queries the database and populates the cache with the result. There are many ways to invalidate the cache if the relevant records are modified in the underlying database, but for this tutorial we will use the Time To Live (TTL) expiration feature provided by Redis.
The ElastiCache for Redis node and the MySQL database created in this tutorial are eligible for the AWS free tier.
Time: 120 minutes
Cost: Free Tier Eligible
Use Cases: Caching, Scaling, High Availability, Real-Time Application
Products: Amazon ElastiCache for Redis, Amazon RDS MySQL, and AWS Free Tier
Level: Beginners to Intermediate
Last Updated: July 25, 2019
*This estimate assumes you follow the recommended configurations throughout the tutorial and terminate all resources within 2 hours.
**Accounts that have been created within the last 24 hours might not yet have access to the resources required for this project.
Please allocate 20 minutes to complete the prerequisite section.
This tutorial illustrates some mechanisms with examples written in Python to illustrate some caching techniques. 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.
Once you have access to your EC2 instance, run the following commands:
$ sudo yum install git -y $ sudo yum install mysql -y $ sudo yum install python3 -y $ pip3 install --user virtualenv $ git clone https://github.com/aws-samples/amazon-elasticache-samples/ $ cd amazon-elasticache-samples/database-caching $ virtualenv venv $ source ./venv/bin/activate $ pip3 install -r requirements.txt
Now you are all set to start the tutorial.