Guide to the in-memory cache & data structure store
🔴 Redis Complete Guide
Implement caching, session storage, and Pub/Sub messaging with Redis. Covers everything from the core data types to caching patterns, persistence, and client integration by language.
Intermediate
Updated Oct 1, 2026
~3 min read
6 sections
6 code examples
🔴
API response cachingSession storePub/Sub messagingLeaderboards (Sorted Set)
Implement caching, session storage, and Pub/Sub messaging with Redis. Covers everything from the core data types to caching patterns, persistence, and client integration by language. Rather than listing concepts, this guide is organized so you can follow the content in the order you have to make decisions on a real project.
Key perspective
Infrastructure / operations
Rather than memorizing install commands, understand the order in which traffic, runtime, observability, and incident response connect.
API response cachingSession storePub/Sub messagingLeaderboards (Sorted Set)
Architecture diagrams
To make what you read stick, it helps to capture the flow as a picture first. The two diagrams below are reference maps you can keep coming back to while learning Redis.
Learning flow
Rendering diagram…
Architecture view
Rendering diagram…
Installation
When you first open Redis, the big picture matters more than individual commands. This section starts with the problems the concepts ahead were created to solve.
In a local development environment Redis is simplest to run as a Docker container, and on production servers it is installed with the package manager and kept running through systemd/brew services. If redis-cli ping returns PONG, the server is responding normally.
BASH
# Docker (simplest)docker run -d -p 6379:6379 redis:7-alpine# macOSbrew install redis && brew services start redis# Ubuntu/Debiansudo apt install -y redis-serverredis-cli ping # PONG means it is working
Core data types
Here you look at Core data types alongside real code. Rather than copying the example as-is, read it with an eye on the inputs, the outputs, and the parts most likely to change.
Redis is not a plain key-value store; it supports several data structures natively. Choosing the type that fits the problem is the key to using Redis well.
BASH
SET session:abc123 "user-42" EX 3600 # expires automatically after 1 hourGET session:abc123TTL session:abc123 # check the remaining time to expiry (seconds)DEL session:abc123
Type
Example command
Used for
String
SET user:1:name "Kim"
Simple cached values, counters (INCR)
Hash
HSET user:1 name Kim age 30
Storing one object field by field
List
LPUSH queue:jobs job1
Job queues, lists of recent items
Set
SADD tags:post:1 ai devops
Unique tags, intersection/union operations
Sorted Set
ZADD leaderboard 100 user1
Score-based leaderboards, rankings
Caching patterns
Here you look at Caching patterns alongside real code. Rather than copying the example as-is, read it with an eye on the inputs, the outputs, and the parts most likely to change.
The most common pattern is Cache-Aside. The application checks the cache first and, on a miss, queries the database and fills the cache.
Rendering diagram…
cache_aside.pyPYTHON
import redis, jsonr = redis.Redis(host="localhost", port=6379, decode_responses=True)def get_user(user_id: str) -> dict: cache_key = f"user:{user_id}" cached = r.get(cache_key) if cached: return json.loads(cached) # cache hit user = fetch_user_from_db(user_id) # cache miss → query the DB r.setex(cache_key, 300, json.dumps(user)) # store in the cache with a 5-minute TTL return userdef update_user(user_id: str, data: dict): save_user_to_db(user_id, data) r.delete(f"user:{user_id}") # invalidate the cache on update
Pub/Sub messaging
Here you look at Pub/Sub messaging alongside real code. Rather than copying the example as-is, read it with an eye on the inputs, the outputs, and the parts most likely to change.
For simple real-time notifications or propagating events between services, Redis Pub/Sub is a lightweight option. Messages are not persisted, however (they are lost if nobody is subscribed), so consider a separate message broker if you need a reliable queue.
PYTHON
# Publisherr.publish("notifications", "A new order has arrived")# Subscriberpubsub = r.pubsub()pubsub.subscribe("notifications")for message in pubsub.listen(): if message["type"] == "message": print("Received:", message["data"])
Persistence (RDB/AOF)
Persistence (RDB/AOF) is a point where the options diverge. Using the table to compare what each approach is for and how it differs in operation makes later decisions much easier.
Redis is memory-based by nature, so data is gone on restart, but there are two ways to leave data on disk for recovery. Which to use depends on "how much data loss you can tolerate".
Method
Behavior
Characteristics
RDB (snapshot)
Periodically saves the whole memory to disk
Restarts are fast, but data since the last snapshot can be lost
AOF (Append Only File)
Records every write command sequentially, like a log
Low risk of data loss, but the file grows and restarts are slow
Client integration
Here you look at Client integration alongside real code. Rather than copying the example as-is, read it with an eye on the inputs, the outputs, and the parts most likely to change.
With the official or popular client library for each language, you can run commands through familiar function calls without handling the Redis protocol yourself. ioredis is widely used in the Node.js ecosystem for its broad support of reconnection, clusters, and Pub/Sub.
import Redis from "ioredis";const redis = new Redis({ host: "localhost", port: 6379 });await redis.set("key", "value", "EX", 60);const value = await redis.get("key");
Redis: frequently asked questions
What is Redis used for?
The most common uses are caching and session storage. It is also used for rate limiting, leaderboards, distributed locks, and simple message queues. Data lives in memory, so responses are very fast, and besides strings it offers data structures such as lists, hashes, and sorted sets.
Is data lost when Redis restarts?
It depends on the persistence settings. With RDB, which saves snapshots at intervals, and AOF, which logs write commands, data is recovered after a restart. With snapshots alone, changes since the last save can be lost. If Redis is only a cache, turn persistence off; if the data must not be lost, the rule is to keep the source of truth in a database.
How do I handle the cache and the database getting out of sync?
The most widely used approach is to update the database first and then delete the cache key when data changes. Add an expiry (TTL) as well, so that even if the delete fails the value corrects itself after a while. Perfect consistency is hard, so decide per kind of data how much delay is acceptable.