Getting started with Redis: It’s easier than you think

‘Redis’, which stands for Remote Dictionary Server. According to Redis official, Redis is an open-source (BSD licensed), in-memory data structure store, used as a database, cache, and message broker. It is a data store that offers performance benefits over traditional databases.

In this quick post, we’ll break down what Redis is and how it works. More importantly, we’ll also see what Redis is not so that you can make good decisions about how to use it. Along the way, we’ll also introduce some example code so you can get a feel for how it works.

No alt text provided for this image


Redis Architecture

Redis has two key features that make it an ideal solution for some software challenges:


  1. Redis is a key-value data store. This means that keys are hashed, and as a result we can look up data in constant — O(1) — time. Instead of querying a database, we just ask Redis if the key exists. If it does, then Redis returns the value.
  2. Redis operates in-memory. On a hardware level, Redis is saving and manipulating data in RAM instead of on disk.

Of course, the fact that Redis operates in-memory has consequences for data persistence. So, Redis does have the ability to save a current snapshot of data to disk as well.

What Redis architecture means practically

These architecture decisions behind Redis lead to interesting consequences:


Pros:

  • Redis is ridiculously fast compared to databases — like 100,000 reads/writes per second
  • Redis implements highly efficient data structures for manipulating data

Cons:

  • Since it’s on RAM, data persistence can be an issue
  • Redis has limited ability to create relationships between data objects — it’s not a replacement for a relational (e.g. MySQL) or document-based (e.g. MongoDB) database


What can I use Redis for?

Redis has a host of potential applications for scenarios where you need quick access to data:


  • Cache the results of an expensive database query across different pages when you know that data is not likely to change significantly
  • Cache recent changes/updates/posts/events to power a “Recently added” section to your website that updates dynamically without needing to query the whole database like SELECT * FROM posts WHERE ... ORDER BY time DESC LIMIT 10;
  • Cache and count new scores/prices/impressions in a leaderboard to power a “Top Scores” or “Top Stories” section of your website, by using Redis’s increment commands to count impressions or add a key to a set if it’s unique and its score exceeds a certain threshold
  • Create a publish-subscribe model where Redis natively manages the pushing of new events to subscribers
  • Create and maintain an independent message queue for passing data between services in your application since Redis lists can be pushed and popped from either the head or the tail in constant time

Command to start Redis stack

This will pull the image if not available locally on the system and run the container :

docker run -d --name redis-stack -p 6379:6379 -p 8001:8001 redis/redis-stack:latest        

The redis server is now running on your localhost at port 6379 and you can access it through redis stack insight which is a GUI for same on port 8001, some thing like this :

No alt text provided for this image

Let's start with Redis sets :

It can store key value pairs where these values are actually sets. So you can add members into it and the key can be any string you want. You can also specify a TTL value that is time to live which actually defines the time for which this set would be available in seconds. After that, it would be removed. You can choose to not fill TTL if you want it to be persistent in redis.

No alt text provided for this image

For the above example the key is "Friends" and the value is the set of all names {Ajinkya,Abhay, .....}

Python code for operation on Redis sets is as below :

import redis

# Create a Redis client
redis_client = redis.Redis(host='localhost', port=6379, db=0)

# Add elements {'banana', 'apple', 'orange'} to the set 'myset'
redis_client.sadd('myset', 'apple', 'banana', 'orange')

# Check if an element is a member of a set
print(redis_client.sismember('myset', 'apple'))  # True
print(redis_client.sismember('myset', 'grape'))  # False

# Get all elements of a set
print(redis_client.smembers('myset'))  # {'banana', 'apple', 'orange'}

# Remove an element from a set
redis_client.srem('myset', 'orange')

# Get the number of elements in a set
print(redis_client.scard('myset'))  # 2

# Get the union of two sets
redis_client.sadd('myset2', 'apple', 'pear', 'kiwi')
print(redis_client.sunion('myset', 'myset2'))  # {'banana', 'apple', 'pear', 'kiwi'}

# Get the intersection of two sets
print(redis_client.sinter('myset', 'myset2'))  # {'apple'}

# Get the difference between two sets
print(redis_client.sdiff('myset', 'myset2'))  # {'banana'}

# Remove all elements from a set
redis_client.delete('myset')
redis_client.delete('myset2')        

In the upcoming edits of this article we would be discussing about the Sorted Sets, String, Json, Pub/Sub queues etc.


If you loved reading this arcticle, please upvote it, it keeps me motivated to continue writing such articles.

To view or add a comment, sign in

Insights from the community

Others also viewed

Explore topics