Caching with Redis
Hello everyone! Today, I want to share my understanding on a recent concept I came across in my learning, caching, and how I implemented it in a simple application.
Caching is the process of storing copies of data in a cache, or temporary storage location, so that they can be accessed more quickly.
For instance, if you have an e-commerce app and a web visitor requests a list of products, your application pulls this information from a database like MySQL or MongoDB, which stores data to your server's disk. This requires a roundtrip to the disk, which is costly in cases where your client base increases to millions. This, in turn, will slow down your application.
This is where Redis comes to the rescue. Redis is an industry-standard caching tool. It can also be used for other functions, but today we will focus on its caching capabilities.
Implementing Redis Caching
The goal here is to implement Redis caching in a simple e-commerce site using redis-py on a Linux OS. Below are the steps I took to do just this.
Step 1: Installing Redis
The first step was to install Redis on our server. I followed the official documentation to get Redis up and running on my Linux machine. The installation was straightforward:
sudo apt update
sudo apt install redis-server
Step 2: Connecting to Redis with redis-py
After installing Redis, I needed to connect our application to the Redis server. Since our application was written in Python, I used the redis-py library to interact with Redis. I installed the library using pip:
pip3 install redis
Next, I established a connection to the Redis server:
import redis
# Connect to the local Redis server
redis_client = redis.Redis(host='localhost', port=6379, db=0)
Step 3: Caching Data in Redis
With the connection established, I started caching the product lists. The idea was to cache the results of the database queries so that subsequent requests could be served from the cache instead of querying the database every time.
Storing Data in Redis
I modified the product retrieval function to first check if the data was available in the cache. If not, it would fetch the data from the database and store it in the cache:
def get_products():
# Check if the products are in the cache
cached_products = redis_client.get('products')
if cached_products:
# Return the cached data
return cached_products.decode('utf-8').split(',')
else:
# Fetch data from the database
product_list = fetch_products_from_db()
# Store the data in the cache
redis_client.set('products', ','.join(product_list))
return product_list
In this function, fetch_products_from_db() is a placeholder for the actual database query. The product list is converted to a comma-separated string before being stored in Redis.
Retrieving Data from Redis
When retrieving the product list, the function first checks if the data is available in the cache. If it is, the cached data is returned. Otherwise, the data is fetched from the database, cached, and then returned.
Step 4: Testing and Optimizing
After implementing the caching logic, I tested the application to ensure that the response time was optimal and all code was working correctly.
I further optimized the caching strategy by implementing expiration times for the cached data. This ensured that the cache stayed up-to-date with the latest product information from the database:
redis_client.set('products', ','.join(product_list), ex=3600)
This line sets an expiration time of one hour (3600 seconds) for the cached product list.
HNG INTERNSHIP
I have always been passionate about backend development, and I seek to enhance my skills, collaborate with talented individuals, and contribute to meaningful projects. That's why I signed up for HNG Internship.
HNG Internship is a fast-paced bootcamp for learning digital skills. It's focused on advanced learners and those with some pre-knowledge, and it gets people into shape for job offers. Sign up or you can also sign up for the HNG Premium network here if you want to connect with top techies, grow your career and collaborate with others.
I believe that this internship will provide me with invaluable learning opportunities and allow me to work on impactful projects. I look forward to embarking on this journey with you.
About the author
I'm a Software Engineer who aims to create resource-efficient and engaging software that maximises user experience whilst documenting my learning process.
Comments
Join the discussionNo comments yet. Be the first to comment.


