Questions
How do you use Redis as a cache?
The Scenario
You are a backend engineer at an e-commerce company. You are building a new service that needs to get product information from a database.
The database is slow, so you want to use Redis as a cache to speed up the service.
The Challenge
Explain how you would use Redis as a cache. What are the key commands that you would use, and what are the different cache eviction policies that you can use?
A junior engineer might try to solve this problem by just storing the data in Redis without setting an expiration time. This would not be a very good solution, because the cache would eventually fill up and you would have to manually evict the old data.
A senior engineer would know that Redis is the perfect tool for this job. They would be able to explain how to use the `SET` command with the `EX` option to set an expiration time, and they would be able to explain the different cache eviction policies that are available.
Step 1: Understand the Key Commands
| Command | Description |
|---|---|
SET | Sets the value of a key. |
GET | Gets the value of a key. |
EXPIRE | Sets an expiration time on a key. |
TTL | Gets the remaining time to live of a key. |
Step 2: Use Redis as a Cache
Here’s how we can use Redis as a cache:
import redis
r = redis.Redis()
def get_product(product_id):
product = r.get(f"product:{product_id}")
if product is None:
product = get_product_from_db(product_id)
r.set(f"product:{product_id}", product, ex=3600)
return productIn this example, we first check if the product is in the cache. If it is, we return it. If it is not, we get it from the database, store it in the cache with an expiration time of 1 hour, and then return it.
Step 3: Choose a Cache Eviction Policy
When the cache is full, Redis needs to evict some keys to make room for new ones. There are several different cache eviction policies that you can use:
| Policy | Description |
|---|---|
noeviction | Don’t evict any keys. Just return an error when the cache is full. |
allkeys-lru | Evict the least recently used keys. |
allkeys-random | Evict random keys. |
volatile-lru | Evict the least recently used keys that have an expiration time set. |
volatile-random | Evict random keys that have an expiration time set. |
volatile-ttl | Evict the keys that have the shortest time to live. |
You can configure the cache eviction policy in the redis.conf file.
Practice Question
You are using Redis as a cache and you want to evict the least recently used keys. Which of the following would you use?