Redis

What is Redis?

Redis is an in-memory, key–value data store designed for extremely fast data access. Unlike traditional relational databases, Redis stores data primarily in RAM, making it ideal for use cases where performance and low latency are crucial. Redis can persist data to disk, but its main strength lies in speed rather than long-term storage.

Redis is commonly used for caching, session storage, real-time analytics, message queues, leaderboards, and rate limiting. It is often used in conjunction with databases like MySQL or PostgreSQL to reduce load and enhance application performance.

Syntax

Redis does not use SQL. Instead, it works with simple commands operating on keys and data structures. Key characteristics include:

  • Key–value based: data is accessed using unique keys.
  • In-memory storage: data is kept in RAM for fast reads and writes.
  • Rich data types: strings, lists, sets, sorted sets, hashes, and more.
  • No tables or rows: data is organized by keys, not schemas.
  • Optional persistence: data can be saved to disk using snapshots or append-only files.

Running a Redis server

Before we can use Redis in Python, we need a Redis server running locally or remotely. Redis is a server-client database, so the Python redis module connects to a running server. On Windows, we can install it using Memurai for Redis. After installation, Memurai will by default listen on port 6379.

Python implementation

Redis can be used in Python via the redis module. A Redis server must be running locally or remotely before connecting.


import redis
r = redis.Redis(host = "localhost", port = 6379, decode_responses = True) # connecting to the Redis server

# Setting individual key-value pairs for a user's information
r.set("user:1:name", "Alice")
r.set("user:1:age", 30)

# Getting and printing the stored values
name = r.get("user:1:name")
age = r.get("user:1:age")
print(name, age)

r.hset("user:2", mapping = {"name": "Bob", "age": 25}) # storing multiple related fields under a single key using a Redis hash
user = r.hgetall("user:2") # retrieving all fields and their values from the hash
print(user)