Skip to main content
AIDevOps
  • Learn
  • Learning Paths
  • Practice
  • Open Source
  • Books
  • Engineering

    AI DevOpsThe full map of building and operating AI servicesLLMOpsLLM deployment · evaluation · observabilityHands-on ProjectsBuild AI Agent projects

    Knowledge

    DocsTechnical documentationBlogEngineering articlesPloggerDevelopment log feed

    Validate

    Certification3-level skills certification · coming soon
AI Models
LlamaTutorial|MistralTutorial|GemmaTutorial|DeepSeekTutorial|QwenTutorial
🧱 Infrastructure
Infrastructure Intro & RoadmapNginxRedis
🤖 AI Applied Development
Applied AI Intro & RoadmapHugging FaceLangChainLlamaIndexLLMOps|LangGraphMCPMulti-AgentAgent Evaluation
🧠 AI Core
AI Intro & RoadmapML FundamentalsLLM Fundamentals|Python AIC++|PyTorchTensorFlowJAX
🧠 AI Agent Development
Finance AI AgentLLM API ServerStock Investing AgentAIOps AI AgentEducation AI AgentCoding AI Agent
🌱 Spring Cloud
Spring Intro & RoadmapSpring Cloud GatewaySpring BootJava|Spring AISpring SecuritySpring BatchSpring JPA
🐳 DevOps
DevOps Intro & RoadmapLinuxDockerCI/CD|Kubernetes BasicsK8s AdvancedPrometheusGrafana
☁️ Cloud
Cloud Intro & RoadmapAWSGCPAzureNCPCloudflare
🎨 Frontend
Frontend Intro & RoadmapJavaScriptTypeScript|ReactNext.js|VueNuxt|Electron
📱 Mobile
Mobile Intro & RoadmapKotlinAndroidFlutter
⚙️ Backend
Backend Intro & RoadmapPython BasicsFastAPIDjangoFlask|CGoGinNode.js
💾 Database
DB Intro & RoadmapCore SQLOracleMySQLPostgreSQL|MongoDBVector DB
🧪 Testing
k6JMeternGrinder
AIDevOps

Engineering AI. From Code to Production.
An engineering learning platform for building and operating AI and AI Agents

Learn

  • All Guides
  • Learning Paths
  • AI Tutorial
  • Practice
  • Books

Resources

  • AI DevOps
  • LLMOps
  • Hands-on Projects
  • Docs
  • Blog
  • Plogger
  • Open Source
  • Certification (coming soon)

Start Here

  • AI Core Roadmap
  • AI Applied Development Roadmap
  • Spring Cloud Roadmap
  • DevOps Roadmap
  • Infrastructure Roadmap

 

  • Cloud Roadmap
  • Frontend Roadmap
  • Mobile Roadmap
  • Backend Roadmap
  • Database Roadmap
© 2026 AIDevOps. All rights reserved.
Terms of ServicePrivacy PolicySitemaptestforge.kr
  1. Home
  2. Learn
  3. Infrastructure
  4. Redis
Guide to the in-memory cache & data structure store

🔴 Redis Complete Guide

Visitors

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)

Contents

0 / 9
  1. How to use this guide
  2. Architecture diagrams
  3. Installation
  4. Core data types
  5. Caching patterns
  6. Pub/Sub messaging
  7. Persistence (RDB/AOF)
  8. Client integration
  9. Frequently asked questions
Contents 9 sections
  1. How to use this guide
  2. Architecture diagrams
  3. Installation
  4. Core data types
  5. Caching patterns
  6. Pub/Sub messaging
  7. Persistence (RDB/AOF)
  8. Client integration
  9. Frequently asked questions

How to use this guide

How to read it

Understanding Redis as a real-world workflow

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

# macOS
brew install redis && brew services start redis

# Ubuntu/Debian
sudo apt install -y redis-server

redis-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 hour
GET session:abc123
TTL session:abc123                     # check the remaining time to expiry (seconds)
DEL session:abc123
TypeExample commandUsed for
StringSET user:1:name "Kim"Simple cached values, counters (INCR)
HashHSET user:1 name Kim age 30Storing one object field by field
ListLPUSH queue:jobs job1Job queues, lists of recent items
SetSADD tags:post:1 ai devopsUnique tags, intersection/union operations
Sorted SetZADD leaderboard 100 user1Score-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, json

r = 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 user

def 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

Tip

Too long a TTL leaves stale data exposed for a long time, and too short a TTL gives no caching benefit — tune it to how often the data changes.

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
# Publisher
r.publish("notifications", "A new order has arrived")

# Subscriber
pubsub = 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".
MethodBehaviorCharacteristics
RDB (snapshot)Periodically saves the whole memory to diskRestarts are fast, but data since the last snapshot can be lost
AOF (Append Only File)Records every write command sequentially, like a logLow risk of data loss, but the file grows and restarts are slow

Tip

For a pure cache, turning persistence off is fine, but for uses where data loss matters, such as sessions and queues, turn on AOF or use RDB+AOF together.

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.
BASH
pip install redis        # Python
npm install ioredis       # Node.js
redis-client.jsJAVASCRIPT
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");

Tip

As a next step, try bundling Redis with other services using docker-compose in the docker guide, or wiring it in as a caching layer on a real API server in the fastapi/nodejs guides.

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.

← Previous guideNginx