DeployU
Interviews / Databases / How do you use Redis as a cache?

How do you use Redis as a cache?

practical Caching Interactive Quiz Code Examples

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?

Wrong Approach

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.

Right Approach

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

CommandDescription
SETSets the value of a key.
GETGets the value of a key.
EXPIRESets an expiration time on a key.
TTLGets 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 product

In 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:

PolicyDescription
noevictionDon’t evict any keys. Just return an error when the cache is full.
allkeys-lruEvict the least recently used keys.
allkeys-randomEvict random keys.
volatile-lruEvict the least recently used keys that have an expiration time set.
volatile-randomEvict random keys that have an expiration time set.
volatile-ttlEvict 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?