Database Caching Strategies Using Redis
Database Caching Strategies Using Redis
Using Redis
May 2017
Notices
Customers are responsible for making their own independent assessment of
the information in this document. This document: (a) is for informational
purposes only, (b) represents current AWS product offerings and practices,
which are subject to change without notice, and (c) does not create any
commitments or assurances from AWS and its affiliates, suppliers or licensors.
AWS products or services are provided “as is” without warranties,
representations, or conditions of any kind, whether express or implied. The
responsibilities and liabilities of AWS to its customers are controlled by AWS
agreements, and this document is not part of, nor does it modify, any
agreement between AWS and its customers.
© 2017 Amazon Web Services, Inc. or its affiliates. All rights reserved.
Contents
You can apply caching to any type of database, including relational databases
such as Amazon Relational Database Service (Amazon RDS) or NoSQL
databases such as Amazon DynamoDB, MongoDB, and Apache Cassandra.
The best part of caching is that it’s easy to implement, and it dramatically
improves the speed and scalability of your application.
Database Challenges
When you’re building distributed applications that require low latency and
scalability, disk-based databases can pose a number of challenges. A few
common ones include the following:
The following are the three most common types of database caches:
Page 1
Amazon Web Services – Database Caching Strategies using Redis
• Local caches: A local cache stores your frequently used data within
your application. This makes data retrieval faster than other caching
architectures because it removes network traffic that is associated with
retrieving data.
Page 2
Amazon Web Services – Database Caching Strategies using Redis
With remote caches, the orchestration between caching the data and
managing the validity of the data is managed by your applications and/or
processes that use it. The cache itself is not directly connected to the
database but is used adjacently to it.
The remainder of this paper focuses on using remote caches, and specifically
Amazon ElastiCache for Redis, for caching relational database data.
Caching Patterns
When you are caching data from your database, there are caching patterns for
Redis5 and Memcached6 that you can implement, including proactive and
reactive approaches. The patterns you choose to implement should be directly
related to your caching and application objectives.
Page 3
Amazon Web Services – Database Caching Strategies using Redis
1. When your application needs to read data from the database, it checks
the cache first to determine whether the data is available.
2. If the data is available (a cache hit), the cached data is returned, and the
response is issued to the caller.
3. If the data isn’t available (a cache miss), the database is queried for the
data. The cache is then populated with the data that is retrieved from the
database, and the data is returned to the caller.
Page 4
Amazon Web Services – Database Caching Strategies using Redis
• The cache contains only data that the application actually requests,
which helps keep the cache size cost effective.
Write-Through
A write-through cache reverses the order of how the cache is populated.
Instead of lazy-loading the data in the cache after a cache miss, the cache is
proactively updated immediately following the primary database update. The
fundamental data retrieval logic can be summarized as follows:
Page 5
Amazon Web Services – Database Caching Strategies using Redis
A proper caching strategy includes effective use of both write-through and lazy
loading of your data and setting an appropriate expiration for the data to keep it
relevant and lean.
Cache Validity
You can control the freshness of your cached data by applying a time to live
(TTL) or “expiration” to your cached keys. After the set time has passed, the key
is deleted from the cache, and access to the origin data store is required along
with reaching the updated data.
Two principles can help you determine the appropriate TTLs to apply and the
type of caching patterns to implement. First, it’s important that you understand
the rate of change of the underlying data. Second, it’s important that you
evaluate the risk of outdated data being returned back to your application
instead of its updated counterpart.
For example, it might make sense to keep static or reference data (that is, data
that is seldom updated) valid for longer periods of time with write-throughs to
the cache when the underlying data gets updated.
With dynamic data that changes often, you might want to apply lower TTLs that
expire the data at a rate of change that matches that of the primary database.
This lowers the risk of returning outdated data while still providing a buffer to
offload database requests.
It’s also important to recognize that, even if you are only caching data for
minutes or seconds versus longer durations, appropriately applying TTLs to
Page 6
Amazon Web Services – Database Caching Strategies using Redis
your cached keys can result in a huge performance boost and an overall better
user experience with your application.
Another best practice when applying TTLs to your cache keys is to add some
time jitter to your TTLs. This reduces the possibility of heavy database load
occurring when your cached data expires. Take, for example, the scenario of
caching product information. If all your product data expires at the same time
and your application is under heavy load, then your backend database has to
fulfill all the product requests. Depending on the load, that could generate too
much pressure on your database, resulting in poor performance. By adding
slight jitter to your TTLs, a randomly generated time value (e.g., TTL = your
initial TTL value in seconds + jitter) would reduce the pressure on your backend
database and also reduce the CPU use on your cache engine as a result of
deleting expired keys.
Evictions
Evictions occur when cache memory is overfilled or is greater than the
maxmemory setting for the cache, causing the engine selecting keys to evict in
order to manage its memory. The keys that are chosen are based on the
eviction policy you select.
By default, Amazon ElastiCache for Redis sets the volatile-lru eviction policy to
your Redis cluster. When this policy is selected, the least recently used keys
that have an expiration (TTL) value set are evicted. Other eviction policies are
available and can be applied in the configurable maxmemory-policy
parameter.
allkeys-lru The cache evicts the least recently used (LRU) keys
regardless of TTL set.
allkeys-lfu The cache evicts the least frequently used (LFU) keys
regardless of TTL set.
volatile-lru The cache evicts the least recently used (LRU) keys from
those that have a TTL set.
Page 7
Amazon Web Services – Database Caching Strategies using Redis
volatile-lfu The cache evicts the least frequently used (LFU) keys
from those that have a TTL set.
volatile-ttl The cache evicts the keys with the shortest TTL set.
no-eviction The cache doesn’t evict keys at all. This blocks future
writes until memory frees up.
Generally, least recently used (LRU)-based policies are more common for basic
caching use cases. However, depending on your objectives, you might want to
use a TTL or random-based eviction policy that better suits your requirements.
Also, if you are experiencing evictions with your cluster, it is usually a sign that
you should scale up (that is, use a node with a larger memory footprint) or scale
out (that is, add more nodes to your cluster) to accommodate the additional
data. An exception to this rule is if you are purposefully relying on the cache
engine to manage your keys by means of eviction, also referred to an LRU
cache.7
Amazon ElastiCache offers a fully managed service for Redis. This means that
all the administrative tasks associated with managing your Redis cluster,
including monitoring, patching, backups, and automatic failover, are managed
Page 8
Amazon Web Services – Database Caching Strategies using Redis
by Amazon. This lets you focus on your business and your data instead of your
operations.
Other benefits of using Amazon ElastiCache for Redis over self-managing your
cache environment include the following:
• An enhanced Redis engine that is fully compatible with the open source
version but that also provides added stability and robustness.
For more information about Redis or Amazon ElastiCache, see the Further
Reading section at the end of this whitepaper.
The basic paradigm when you query data from a relational database includes
executing SQL statements and iterating over the returned ResultSet object
cursor to retrieve the database rows. There are several techniques you can
apply when you want to cache the returned data. However, it’s best to choose a
method that simplifies your data access pattern and/or optimizes the
architectural goals that you have for your application.
To visualize this, we’ll examine snippets of Java code to explain the logic. You
can find additional information on the AWS caching site.10 The examples use
the Jedis Redis client library11 for connecting to Redis, although you can use
any Java Redis library, including Lettuce12 and Redisson.13
Assume that you issued the following SQL statement against a customer
database for CUSTOMER_ID 1001. We’ll examine the various caching
strategies that you can use.
Page 9
Amazon Web Services – Database Caching Strategies using Redis
…
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
Customer customer = new Customer();
customer.setFirstName(rs.getString("FIRST_NAME"));
customer.setLastName(rs.getString("LAST_NAME"));
and so on …
}
…
Iterating over the ResultSet cursor lets you retrieve the fields and values from
the database rows. From that point, the application can choose where and how
to use that data.
Let’s also assume that your application framework can’t be used to abstract
your caching implementation. How do you best cache the returned database
data?
Given this scenario, you have many options. The following sections evaluate
some options, with focus on the caching logic.
• Con: Data retrieval still requires extracting values from the ResultSet
object cursor and does not further simplify data access; it only reduces
data retrieval latency.
Page 10
Amazon Web Services – Database Caching Strategies using Redis
Note: When you cache the row, it’s important that it’s serializable. The following
example uses a CachedRowSet implementation for this purpose. When you
are using Redis, this is stored as a byte array value.
The following code converts the CachedRowSet object into a byte array and
then stores that byte array as a Redis byte array value. The actual SQL
statement is stored as the key and converted into bytes.
…
// rs contains the ResultSet, key contains the SQL statement
if (rs != null) { //lets write-through to the cache
CachedRowSet cachedRowSet = new CachedRowSetImpl();
cachedRowSet.populate(rs, 1);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutput out = new ObjectOutputStream(bos);
out.writeObject(cachedRowSet);
byte[] redisRSValue = bos.toByteArray();
jedis.set(key.getBytes(), redisRSValue);
jedis.expire(key.getBytes(), ttl);
}
…
The nice thing about storing the SQL statement as the key is that it enables a
transparent caching abstraction layer that hides the implementation details. The
other added benefit is that you don’t need to create any additional mappings
between a custom key ID and the executed SQL statement.
The last statement executes an expire command to apply a TTL to the stored
key. This code follows our write-through logic in that upon querying the
database, the cached value is stored immediately afterward.
For lazy caching, you would initially query the cache before executing the query
against the database. To hide the implementation details, use the DAO pattern
and expose a generic method for your application to retrieve the data.
For example, because your key is the actual SQL statement, your method
signature could look like the following:
Page 11
Amazon Web Services – Database Caching Strategies using Redis
The code that calls (consumes) this method expects only a ResultSet object,
regardless of what the underlying implementation details are for the interface.
Under the hood, the getResultSet method executes a GET command for the
SQL key, which, if present, is deserialized and converted into a ResultSet
object.
If the data is not present in the cache, query the database for it, and cache it
before returning.
For all other caching techniques that we’ll review, you should establish a
naming convention for your Redis keys. A good naming convention is one that
is easily predictable to applications and developers. A hierarchical structure
separated by colons is a common naming convention for keys, such as
object:type:id.
Page 12
Amazon Web Services – Database Caching Strategies using Redis
…
// rs contains the ResultSet
while (rs.next()) {
Customer customer = new Customer();
Gson gson = new Gson();
JsonObject customerJSON = new JsonObject();
customer.setFirstName(rs.getString("FIRST_NAME"));
customerJSON.add(“first_name”,
gson.toJsonTree(customer.getFirstName() );
customer.setLastName(rs.getString("LAST_NAME"));
customerJSON.add(“last_name”, gson.toJsonTree(customer.getLastName()
);
and so on …
jedis.set(customer:id:"+customer.getCustomerID(),
customerJSON.toString() );
}
…
For data retrieval, you can implement a generic method through an interface
that accepts a customer key (e.g., customer:id:1001) and an SQL statement
Page 13
Amazon Web Services – Database Caching Strategies using Redis
string argument. It will also return whatever structure your application requires
(e.g., JSON, XML) and abstract the underlying details.
Upon initial request, the application executes a GET command on the customer
key and, if the value is present, returns it and completes the call. If the value is
not present, it queries the database for the record, writes-through a JSON
representation of the data to the cache, and returns.
• Pro: When converting the ResultSet object into a format that simplifies
access, such as a Redis Hash, your application is able to use that data
more effectively. This technique simplifies your data access pattern by
reducing the need to iterate over a ResultSet object or by parsing a
structure like a JSON object stored in a string. In addition, working with
aggregate data structures, such as Redis Lists, Sets, and Hashes
provide various attribute level commands associated with setting and
getting data, eliminating the overhead associated with processing the
data before being able to leverage it.
The following code creates a HashMap object that is used to store the
customer data. The map is populated with the database data and SET into a
Redis.
…
// rs contains the ResultSet
while (rs.next()) {
Customer customer = new Customer();
Map<String, String> map = new HashMap<String, String>();
customer.setFirstName(rs.getString("FIRST_NAME"));
map.put("firstName", customer.getFirstName());
customer.setLastName(rs.getString("LAST_NAME"));
map.put("lastName", customer.getLastName());
and so on …
Page 14
Amazon Web Services – Database Caching Strategies using Redis
jedis.hmset(customer:id:"+customer.getCustomerID(), map);
}
…
For data retrieval, you can implement a generic method through an interface
that accepts a customer ID (the key) and an SQL statement argument. It returns
a HashMap to the caller. Just as in the other examples, you can hide the details
of where the map is originating from. First, your application can query the cache
for the customer data using the customer ID key. If the data is not present, the
SQL statement executes and retrieves the data from the database. Upon
retrieval, you may also store a hash representation of that customer ID to lazy
load.
Unlike JSON, the added benefit of storing your data as a hash in Redis is that
you can query for individual attributes within it. Say that for a given request you
only want to respond with specific attributes associated with the customer Hash,
such as the customer name and address. This flexibility is supported in Redis,
along with various other features, such as adding and deleting individual
attributes in a map.
• Pro: Use application objects in their native application state with simple
serializing and deserializing techniques. This can rapidly accelerate
application performance by minimizing data transformation logic.
• Con: Advanced application development use case.
The following code converts the customer object into a byte array and then
stores that value in Redis:
….
// key contains customer id
Customer customer = (Customer) object;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
Page 15
Amazon Web Services – Database Caching Strategies using Redis
try {
out = new ObjectOutputStream(bos);
out.writeObject(customer);
out.flush();
byte[] objectValue = bos.toByteArray();
jedis.set(key.getBytes(), objectValue);
jedis.expire(key.getBytes(), ttl);
}
…
As the other examples show, you can create a generic method through an
application interface that hides the underlying details method details. In this
example, when instantiating an object or hydrating one with state, the method
accepts the customer ID (the key) and either returns a customer object from the
cache or constructs one after querying the backend database. First, your
application queries the cache for the serialized customer object using the
customer ID. If the data is not present, the SQL statement executes and the
application consumes the data, hydrates the customer entity object, and then
lazy loads the serialized representation of it in the cache.
if (redisObject != null) {
try {
ByteArrayInputStream in = new
ByteArrayInputStream(redisObject);
ObjectInputStream is = new ObjectInputStream(in);
customer = (Customer) is.readObject();
}…
Page 16
Amazon Web Services – Database Caching Strategies using Redis
}…
return customer;
}
Conclusion
Modern applications can’t afford poor performance. Today’s users have low
tolerance for slow-running applications and poor user experiences. When low
latency and scaling databases are critical to the success of your applications,
it’s imperative that you use database caching.
Amazon ElastiCache provides two managed in-memory key value stores that
you can use for database caching. A managed service further simplifies using a
cache in that it removes the administrative tasks associated with supporting it.
Contributors
The following individuals and organizations contributed to this document:
Further Reading
For more information, see the following resources:
Notes
1 https://aws.amazon.com/rds/aurora/
2 https://redis.io/download
3 https://memcached.org/
4 https://aws.amazon.com/elasticache/redis/
5 https://docs.aws.amazon.com/AmazonElastiCache/latest/red-
ug/Strategies.html
Page 17
Amazon Web Services – Database Caching Strategies using Redis
6 https://docs.aws.amazon.com/AmazonElastiCache/latest/mem-
ug/Strategies.html
7 https://redis.io/topics/lru-cache
8 https://www.lua.org/
9 https://aws.amazon.com/vpc/
10
https://aws.amazon.com/caching/
11 https://github.com/xetorthio/jedis
12 https://github.com/wg/lettuce
13 https://github.com/redisson/redisson
14 http://www.oracle.com/technetwork/java/dataaccessobject-138824.html
15 https://d0.awsstatic.com/whitepapers/performance-at-scale-with-amazon-
elasticache.pdf
16 https://redis.io/commands
Page 18