Redis: Core Concepts, Data Structures, and Practical Applications

Redis is a high-performance in-memory data storage system (In-Memory Data Store) that can be used as a cache, database, message broker and real-time data processing component.

Different from traditional relational databases, Redis does not use relational tables and SQL as the main data model. Instead, it organizes data in the form of Key-Value and provides rich data structures and atomic operations.

In modern Web systems, Redis is commonly used for:

  • Caching: Cache database query results and calculation results.
  • Session Storage: Stores temporary status such as login sessions.
  • Counters / Rate Limiting: Counter, access frequency limit.
  • Task Queues: Broker as a task queue system such as Celery.
  • Messaging:Pub/Sub、Streams。
  • Distributed Coordination: Locks, short-term state, and inter-process coordination.

This article focuses on the working mechanism of Redis, common data types, core commands, caching strategies, persistence, message processing, and its actual usage in the Python and Django projects.

1. Basic concept of Redis

The basic data model of Redis is:

Key → Value

For example:

user:1001:name       → "Alice"
post:42:view_count   → 1250
session:abc123       → {...}

Redis's Key are usually strings, while Value's can take a variety of data structures.

Redis Why is it fast?

The main reasons include:

  1. In-Memory Storage: The main data is stored in memory to reduce disk access overhead.
  2. Efficient Data Structures: Efficient operations for different data types.
  3. Event-driven I/O: Handle large number of client connections via event loop and I/O multiplexing.
  4. Low Protocol Overhead: Use the relatively simple Redis Serialization Protocol (RESP).
  5. Atomic Commands: Many common operations can be performed atomically directly on the server side.

Is Redis single-threaded?

Need to distinguish:

  • The core command execution of Redis usually adopts a single-threaded event loop model.
  • Network I/O, persistence, and other work may involve other threads or processes.
  • Different Redis versions and configurations may have different I/O thread support.

Therefore, "Redis is entirely a single-threaded program" is not accurate.

The serial nature of core command execution makes many individual commands naturally atomic, but also means that long-running commands can block other requests.

Redis and PostgreSQL

FeaturesRedisPostgreSQL
Main data modelKey-Value, various data structuresrelational data
Main storage methodMainly memoryPersistent disk storage
Query methodRedis CommandsSQL
Complex relationship querynot good atSupport JOIN etc.
Transactional abilityCommand sequences, atomic operations, etc.Complete ACID transaction
Common usescache, temporary state, messagescore business data

In general Web applications, Redis is usually a complement to PostgreSQL, not a replacement.

For example:

React Frontend
      ↓
Django REST Framework
      ├── PostgreSQL (core business data)
      ├── Redis (caching, counting, rate limiting)
      └── Celery → Redis Broker → Workers

2. Install and start Redis

Docker

One of the most convenient ways to develop locally is Docker:

docker run -d \
  --name redis \
  -p 127.0.0.1:6379:6379 \
  redis:8

Here the port is bound to the host's local loopback address to avoid being exposed to all network interfaces by default.

Connection:

docker exec -it redis redis-cli

Check:

PING

Output:

PONG

Docker Compose

services:
  redis:
    image: redis:8
    restart: unless-stopped
    command:
      - redis-server
      - --appendonly
      - "yes"
    volumes:
      - redis_data:/data
    networks:
      - backend

volumes:
  redis_data:

networks:
  backend:

If only services within Docker Compose need to access Redis, ports does not need to be configured.

Other containers connect via the service name:

redis://redis:6379/0

Here AOF persistence is enabled and the data volume is mounted. The actual production environment also requires further configuration of authentication, resource limits, backup and monitoring.

3. Redis Key and basic commands

All data for Redis is accessed through Key.

Commonly used Key operations

SET user:1:name "Alice"
GET user:1:name

EXISTS user:1:name
TYPE user:1:name

DEL user:1:name

Common commands:

commandfunction
SETSetting String Value
GETGet String Value
EXISTSDetermine whether Key exists
DELDelete Key
UNLINKAsynchronously reclaim the memory occupied by Key
TYPEView Value type
TTLView remaining validity time (seconds)
EXPIRESet expiration time
SCANIncremental traversal Key

Key naming

Redis does not enforce the naming format of Key, but colons are generally used to separate business levels:

user:1001:profile
user:1001:session
article:42:views
cache:poi:123
rate_limit:user:1001

This naming method facilitates management, monitoring and search.

For example:

KEYS user:*

KEYS traverses Keyspace, which can cause significant blocking in large production instances.

Recommended to use:

SCAN 0 MATCH user:* COUNT 100

SCAN Progressive traversal using a cursor.

Need to pay attention to:

  • COUNT is a prompt value, and there is no guarantee that the specified amount will be returned accurately every time.
  • Duplicate results may occur when data changes during the traversal.
  • Iteration must continue until the cursor returns to 0.

4. Redis Data Types: Data structure

The most important basic data structures of Redis include:

TypeFeaturesCommon uses
Stringbyte stringcache, counter
HashField-Value mappingUser attributes, object status
Listordered listsimple queue
SetUnordered and non-repeatingRemove duplicates and set relationships
Sorted SetSort by ScoreRanking list, sliding window
StreamAppending event logMessage queue, event processing

In addition, modern Redis also supports JSON, geospatial index, probabilistic data structure and other functions. Some functions and commands are related to the specific version.

For daily back-end development, you should prioritize mastering the first six types.

5. String: string

String is the most basic and commonly used type.

Redis String can essentially store a sequence of bytes and is not limited to plain text.

basic commands

SET username "Alice"
GET username

MSET a 1 b 2
MGET a b

Set expiration time:

SET verification:123456 "valid" EX 300

Indicates that the validity period of Key is 300 seconds.

NX and XX

SET supports conditional writing:

SET task:123 "processing" NX EX 60

NX means Key is written when it does not exist.

SET task:123 "updated" XX

XX means writing only when Key exists.

These conditional operations are performed by Redis atoms and can be used to implement part of the concurrent coordination logic.

Counter: Counter

SET article:42:views 0

INCR article:42:views
INCRBY article:42:views 10

DECR article:42:views

INCR is an atomic operation.

Multiple requests are executed simultaneously:

INCR article:42:views

There will be no lost updates typical of the normal "first GET, then SET" problem.

Python example

import redis

r = redis.Redis(
    host="localhost",
    port=6379,
    decode_responses=True,
)

r.incr("article:42:views")

Suitable for:

  • Page view count.
  • API call count.
  • Temporary indicator.
  • Simple frequency limit.

But if the counting involves strict persistence or financial settlement, a reliable database is usually also required as the final source of data.

6. Hash: Hash table

Hash is similar to Python Dictionary.

For example:

user:1001
├── name: Alice
├── age: 25
└── city: Tokyo

Common commands

HSET user:1001 name Alice age 25 city Tokyo

HGET user:1001 name
HMGET user:1001 name city

HGETALL user:1001

HDEL user:1001 age
HEXISTS user:1001 name

Add numeric field:

HINCRBY user:1001 login_count 1

The difference between Hash and String JSON

For example, there are two ways to store user data.

String:

SET user:1001 "{\"name\":\"Alice\",\"age\":25}"

Hash:

HSET user:1001 name Alice age 25

Hash can directly modify a single field through HSET.

Ordinary JSON strings usually need to be read, deserialized, modified and re-written.

Note: Redis also provides the native JSON data type, which supports partial updates of structured JSON, and should not be confused with storing JSON text in plain String.

7. List: list

Redis List is a list of strings organized in insertion order.

Supports inserting and popping elements at both ends.

Basic operations

LPUSH jobs task1
LPUSH jobs task2

LRANGE jobs 0 -1

LPOP jobs
RPOP jobs

Common commands:

commandfunction
LPUSHInsert from left
RPUSHInsert from the right
LPOPpop up from left
RPOPpop up from right
LRANGEGet the specified range
LLENGet the length
BLPOP / BRPOPBlock wait and pop

simple message queue

Producer:

LPUSH jobs "process_document:123"

Consumer:

BRPOP jobs 0

Among them, 0 means continuing to wait until an element is available.

But be careful:

Normal List's pop operation will remove the element. If the consumer crashes after retrieving the task, the task may be lost.

Therefore, List can be used for simple queues, but reliable task processing usually requires additional acknowledgment, recovery and retry mechanisms, or the direct use of a full-fledged task queue system.

8. Set: Collection

Set stores unique string elements.

Common commands

SADD article:42:likes user1 user2 user3

SMEMBERS article:42:likes

SISMEMBER article:42:likes user1

SCARD article:42:likes

SREM article:42:likes user1

Set operations

SINTER set:a set:b
SUNION set:a set:b
SDIFF set:a set:b

Respectively:

  • Intersection: intersection.
  • Union: Union.
  • Difference: difference set.

Usage scenarios

For example, record online users or users who temporarily participate in an activity:

SADD campaign:100:participants user1 user2

Because elements are automatically deduplicated, Set is suitable for membership and set calculations.

But in businesses that require strict constraints, auditing, or complex relational queries, relational databases should still be considered.

9. Sorted Set: ordered set

Sorted Set (ZSet) is similar to Set, the members are not repeated, but each member is associated with a value Score.

Redis is sorted according to Score.

Basic operations

ZADD leaderboard 100 alice
ZADD leaderboard 150 bob
ZADD leaderboard 120 charlie

Check out the top scoring users:

ZREVRANGE leaderboard 0 9 WITHSCORES

View member scores:

ZSCORE leaderboard bob

Update scores:

ZINCRBY leaderboard 10 alice

Ranking list

Sorted Set is perfect for leaderboards:

bob       150
charlie   120
alice     110

Common commands:

commandfunction
ZADDAdd members and Score
ZSCOREGet Score
ZINCRBYAdd Score
ZRANGEQuery by ranking range
ZREVRANGEQuery by Score reverse ranking
ZRANK / ZREVRANKGet member ranking
ZREMDelete member

Another important use of Sorted Set is to implement sliding window rate limiting based on timestamps.

10. TTL: Key expiration mechanism

TTL (Time To Live) indicates the remaining valid time of the data.

Setting TTL

SET cache:user:1001 "Alice" EX 600

Or:

EXPIRE cache:user:1001 600

Check:

TTL cache:user:1001

Typical results:

  • Positive integer: seconds remaining.
  • -1: Key exists but has no expiration time.
  • -2: Key does not exist.

Redis How to clear expired Key?

Redis mainly combines:

  • Passive Expiration: Check whether it is expired when accessing Key.
  • Active Expiration: The background active sampling cleanup expired Key.

Therefore, TTL does not mean that Redis will complete all physical memory reclamation immediately at a precise point in time.

TTL and data deletion

Need to distinguish:

  • Expiration: Key reaches the expiration time.
  • Eviction: After the memory reaches the limit, Key will be eliminated according to the policy.

They are two different mechanisms.

11. Caching: cache

Caching is the most common usage scenario of Redis.

For example, a Django API needs to return popular POI information:

Client
   ↓
Django API
   ↓
Check Redis Cache
   ├── Hit → Return Cached Result
   └── Miss → Query PostgreSQL
                    ↓
                Write Cache
                    ↓
                Return Result

Cache-Aside Pattern

Cache-Aside is a common caching strategy.

Read:

  1. Query Redis.
  2. If hit, return to cache.
  3. If there is a miss, the database is queried.
  4. Write the result to Redis and set TTL.
import json
import redis

r = redis.Redis(
    host="localhost",
    port=6379,
    decode_responses=True,
)

def get_poi(poi_id):
    key = f"cache:poi:{poi_id}"

    cached = r.get(key)

    if cached is not None:
        return json.loads(cached)

    poi = query_poi_from_database(poi_id)

    if poi is None:
        return None

    r.set(
        key,
        json.dumps(poi),
        ex=600,
    )

    return poi

query_poi_from_database() here represents the actual database query function.

Cache Invalidation: Cache invalid

One of the hardest problems with caching is maintaining data consistency.

For example:

PostgreSQL Medium POI Update
           ↓
Redis still saves old data
           ↓
API returns expired content

Common strategies:

TTL-based Expiration

Allow cached data to expire within a limited time.

Invalidate on Write

After the business data is modified, the corresponding cache is deleted.

r.delete(f"cache:poi:{poi_id}")

Explicit Refresh

Actively recalculate cache after data update.

For Django ORM, cache invalidation logic can be performed after the database transaction is successfully committed:

from django.db import transaction

transaction.on_commit(
    lambda: r.delete(f"cache:poi:{poi_id}")
)

It should be noted that this approach can reduce the problem of incorrect cache invalidation when the transaction is rolled back, but it cannot provide strict cross-system atomicity between the database and Redis.

Common caching issues

Cache Penetration (cache penetration)

A large number of requests query data that does not exist.

You can consider methods such as short TTL null value caching, input verification and rate limiting.

Cache Breakdown (hotspot Key failed)

High concurrent access to the same hotspot Key that just expired caused the database to receive a large number of requests instantly.

You can use Single Flight, mutually exclusive reconstruction, early refresh, etc.

Cache Avalanche (cache avalanche)

A large number of Key expired at similar times, causing centralized back-to-origin.

Random jitter can be added to TTL:

import random

ttl = 600 + random.randint(0, 120)

r.set(key, value, ex=ttl)

Caching should not be used by default for all queries

Particularly suitable for caching:

  • Read frequently.
  • The computational cost is high.
  • Data changes infrequently.
  • Ability to tolerate short periods of stale data.

Not suitable for blind caching:

  • Every change requires immediately consistent data.
  • Queries with extremely low reuse rate.
  • Responses that contain sensitive data but lack permission isolation.
  • The result is very large data with unclear memory benefits.

12. Cache Eviction: Memory elimination strategy

Redis uses memory as the main storage medium, so memory usage usually needs to be limited.

For example in redis.conf:

maxmemory 512mb
maxmemory-policy allkeys-lru

Main strategies:

Strategymeaning
noevictionReject writes that require additional memory after memory limit reached
allkeys-lruEliminate the approximately oldest unused data from all Key
volatile-lruPress LRU to select from Key where TTL is set
allkeys-lfuEliminate low frequency usage data from all Key
volatile-ttlPrioritize the early expiration from Key with TTL
allkeys-randomRandomly eliminated from all Key

LRU and LFU

LRU(Least Recently Used)

Mainly consider the most recent access time.

LFU(Least Frequently Used)

Mainly consider the frequency of access.

Redis's LRU is an approximate implementation, rather than maintaining an absolutely precise ordering of the full set of LRU.

How to choose?

For Redis used exclusively as a cache:

maxmemory-policy allkeys-lru

Usually a reasonable starting point.

But if Redis also stores Celery Broker, queue messages or other status that cannot be lost at will, you cannot simply use a strategy that will actively eliminate the business Key.

A more reasonable approach is usually to configure separate Redis instances for different uses or explicit resource isolation.

13. Persistence: persistence

Redis works primarily in memory, but can save data to disk through a persistence mechanism.

There are two main ways:

  • RDB。
  • AOF。

RDB: Snapshot

RDB (Redis Database Snapshot) generates data snapshots under specific conditions.

For example:

save 900 1
save 300 10
save 60 10000

This means that a snapshot can be triggered when the write count threshold is reached within the corresponding time window.

Advantages:

  • The file is relatively compact.
  • Suitable for backup and recovery.
  • Usually good for fast loading.

Limitations:

  • Data may be lost between snapshots.
  • Background saving still consumes system resources.

AOF: append log

AOF (Append Only File) records the write operation of Redis and is used to reconstruct data after restart.

For example:

appendonly yes
appendfsync everysec

Common synchronization strategies:

StrategyFeatures
alwaysEach write is synchronized to disk as much as possible, which is more expensive.
everysecTypically syncs about once per second
noThe operating system determines the synchronization timing

everysec is a common performance and durability trade-off, but still risks losing recent writes.

AOF Rewrite

As writes increase, AOF can become very large.

Redis Records can be compressed by AOF Rewrite to represent the current data state in a more compact form.

RDB vs AOF

ContrastRDBAOF
mechanismPeriodic snapshotswrite log
file sizeusually smallerusually larger
restoreRead snapshotReplay or load persistent records
Recent write protectionDepends on snapshot intervalDepends on fsync strategy
Main purposeBackup, restoreMore fine-grained persistence

Redis also supports enabling both at the same time.

But please note: Redis persistence does not equal a complete database reliability solution.

Production environments still require monitoring, independent backups, recovery drills, and troubleshooting strategies.

14. Atomic Operations: Atomic operation

Redis A single command is usually executed atomically.

For example:

INCR article:42:views

When multiple clients execute concurrently, there will be no typical race conditions like the following ordinary read-modify process:

Client A: GET counter → 5
Client B: GET counter → 5

Client A: SET counter 6
Client B: SET counter 6

The final result is 6 instead of the expected 7.

Use:

INCR counter

This problem can be avoided.

But be careful:

Multiple independent Redis commands do not necessarily form an atomic operation.

If the business logic requires that multiple operations cannot be inserted by other clients, mechanisms such as Transaction or server-side scripts need to be used.

15. Pipeline and Transaction

Pipeline

Pipeline sends multiple commands in batches to reduce the number of network round-trips (RTT).

Python:

with r.pipeline(transaction=False) as pipe:
    pipe.set("a", "1")
    pipe.set("b", "2")
    pipe.get("a")

    results = pipe.execute()

The main purpose is to improve batch operation efficiency.

Redis Transaction

Redis uses:

MULTI
SET a 1
INCR counter
EXEC

Execute a sequence of transaction commands.

Commands within a transaction are not inserted by other client commands during execution.

But Redis Transaction is different from PostgreSQL Transaction:

  • Redis does not provide the ability of a relational database to automatically roll back all executed commands.
  • If a runtime error occurs on a command during transaction execution, other commands may still be executed.
  • Cannot be used directly for atomic transactions spanning Redis and PostgreSQL.

WATCH: optimistic lock

WATCH can monitor whether Key is modified by other clients.

If the monitored Key is modified before the transaction is executed, EXEC will fail.

This is suitable for implementing Compare-and-Set type logic.

But it needs to handle retry after transaction failure.

16. Lua Scripting: Server-side atomic logic

Lua Script can be used when the business needs to combine multiple commands and must ensure that they are not interrupted by other Redis commands.

For example, a fixed window rate limiting script:

local count = redis.call("INCR", KEYS[1])

if count == 1 then
    redis.call("EXPIRE", KEYS[1], tonumber(ARGV[1]))
end

return count

Execute via Redis:

script = r.register_script("""
local count = redis.call("INCR", KEYS[1])

if count == 1 then
    redis.call("EXPIRE", KEYS[1], tonumber(ARGV[1]))
end

return count
""")

count = script(
    keys=["rate_limit:user:1001"],
    args=[60],
)

This script puts the logic for counting and setting TTL for the first time into an atomic execution unit.

Need to pay attention to:

  • When the Lua script is executed, it will block the execution of other ordinary commands.
  • Long calculations should not be performed in scripts.
  • The atomicity of a script does not imply database transactional rollback.
  • Redis Cluster also needs to consider the Hash Slot limitation when multiple Key are involved.

For more complex fixed window or sliding window rate limiting, Sorted Set and Lua can also be used.

17. Rate Limiting: rate limiting

Redis is very suitable for saving the number of requests and time window information.

Fixed Window

For example, each user can request up to 100 times per minute:

rate_limit:user:1001:202611140001 → 72

Idea:

  1. Generate Key based on user and current time window.
  2. Atomic increment count.
  3. Set TTL for Key.
  4. If the threshold is exceeded, the request is rejected.

Sliding Window

Sliding windows can utilize Sorted Set to save request timestamps.

Basic steps:

  1. Delete records outside the window.
  2. Count the number of requests within the statistics window.
  3. If the limit is not exceeded, add the current request.
  4. Set reasonably TTL.

It is usually necessary to ensure the atomicity of multi-step operations through Lua.

Comparison of rate limiting algorithms

methodFeatures
Fixed WindowSimple, but burst traffic may occur at window boundaries
Sliding Window LogMore accurate, higher storage cost
Sliding Window CounterReduce storage costs, often for approximate statistics
Token BucketAllow certain burst traffic
Leaky BucketSmooth request rate

For Django REST Framework, first understand the scope and limitations of Throttling that comes with DRF.

If strict atomic throttling across processes is required, you should generally design the Redis atomic operation or employ a specialized throttling component instead of relying solely on non-atomic cache counts.

18. Pub/Sub: Publish and subscribe

Redis Pub/Sub is used for real-time message broadcast.

Basic structure:

Publisher
    ↓
Redis Channel
    ├── Subscriber A
    ├── Subscriber B
    └── Subscriber C

Post a message

PUBLISH notifications "hello"

Subscribe to news

Another client:

SUBSCRIBE notifications

As long as the client is subscribing, it can receive the corresponding message.

Important limitations of Pub/Sub

Redis Pub/Sub uses At-most-once Delivery Semantics.

This means:

  • Messages are not persisted as records to be consumed.
  • Messages may be missed when subscribers disconnect.
  • Confirmation of successful processing via ACK is not supported.
  • No general historical message replay is provided.

Therefore suitable for:

  • Real-time notification broadcast.
  • Cache invalidation notification.
  • Non-critical real-time events.
  • Online status change broadcast.

Not suitable for direct use for orders, payments, or important background tasks that must be processed reliably.

19. Streams: Message flow

Redis Streams is a data structure that supports message appending, history reading, Consumer Groups and ACK.

It is more suitable than Pub/Sub for message scenarios that require processing status and consumption records.

Add message

XADD events * type document_uploaded document_id 123

Where * means message ID was generated by Redis.

read message

XRANGE events - +

Read new messages:

XREAD COUNT 10 STREAMS events 0

Streams messages will not be automatically deleted just because they are read by ordinary consumers.

Consumer Groups

Consumer Group allows multiple consumers to collaborate on message processing.

Create:

XGROUP CREATE events workers 0 MKSTREAM

Consumption:

XREADGROUP GROUP workers worker1 COUNT 10 STREAMS events >

Confirm:

XACK events workers 1690000000000-0

The message ID here is just an example. In practice, the ID returned when reading is used.

Pending Entries List(PEL)

After a consumer reads the message, if ACK is not executed, the message will enter the Pending state corresponding to Consumer Group.

You can check:

XPENDING events workers

When a consumer crashes, long-unprocessed messages can be redistributed using mechanisms such as XAUTOCLAIM.

Reliability bounds for Streams

Consumer Group can provide At-least-once type processing power, but still requires:

  • Handle duplicate messages.
  • Clarify the ACK timing.
  • Retry if processing fails.
  • Control message retention periods.
  • Monitor Pending messages.
  • Configure persistence and backup.

Therefore, business handlers usually still need to be idempotent (Idempotency).

For example, when the same document processing event is consumed repeatedly, duplicate records cannot be created unconditionally.

Pub/Sub, List, Streams comparison

FeaturesPub/SubListStreams
Main purposereal time broadcastsimple queueEvent streaming and reliable consumption
historical newsNot reservedRemove after popping upCan be reserved
Consumer GroupNoneNo native Group mechanismsupport
ACKNoneNo native ACKsupport
message replayNot supportedNot directly supportedsupport
Typical complexitylowlowmedium

20. Distributed Lock: distributed lock

When multiple processes need to coordinate access to a resource, Redis can be used to implement short-term distributed locks.

basic way

SET lock:job:123 "unique-token" NX PX 30000

Meaning:

  • NX: The lock can only be obtained if Key does not exist.
  • PX 30000: Expires in 30 seconds.
  • unique-token: The unique identifier of the lock holder.

Why do you need unique Token?

Assumptions:

  1. Worker A acquires the lock.
  2. Worker A takes longer to execute than TTL.
  3. The lock expired.
  4. Worker B obtained new lock.
  5. The Worker A task is completed and DEL is executed directly.

At this time, Worker A may delete the lock of Worker B by mistake.

Therefore, the lock holder needs to be verified when releasing the lock.

Python redis-py

lock = r.lock(
    "lock:job:123",
    timeout=30,
    blocking_timeout=5,
)

if lock.acquire():
    try:
        process_job()
    finally:
        lock.release()

This avoids the need to write the most basic lock token operations directly by hand, but still correctly handles lock timeouts, exceptions, renewals, and task runtimes.

Limitations of Redis Lock

Redis locks are not equivalent to strictly distributed transactions.

In situations such as process suspension, network partition, TTL expiration, etc., it may still happen that multiple executors think they have the right to operate.

For high consistency scenarios, you need to consider:

  • Fencing Tokens。
  • Database unique constraints.
  • Optimistic locking.
  • Idempotent operations.
  • Dedicated consistency coordination system.

For example, to prevent duplicate creation of business records, a database unique constraint is usually more reliable than relying on Redis Lock alone.

21. Python:redis-py

The most commonly used Redis client among Python is redis-py.

Installation:

pip install redis

Sync client

import redis

r = redis.Redis(
    host="localhost",
    port=6379,
    db=0,
    decode_responses=True,
    socket_connect_timeout=3,
    socket_timeout=3,
)

r.ping()
r.set("hello", "world", ex=60)

print(r.get("hello"))

decode_responses=True will convert the return value suitable for decoding into a string to facilitate processing of ordinary text.

connection pool

redis-py supports Connection Pooling.

pool = redis.ConnectionPool(
    host="localhost",
    port=6379,
    max_connections=20,
    decode_responses=True,
)

r = redis.Redis(connection_pool=pool)

Applications should generally reuse clients or connection pools, rather than re-creating a completely independent connection pool for each HTTP request.

Async Redis

If using FastAPI or other asynchronous code, you can use:

import redis.asyncio as redis

async def main():
    r = redis.Redis(
        host="localhost",
        port=6379,
        decode_responses=True,
    )

    try:
        await r.set("hello", "world")
        value = await r.get("hello")
        print(value)
    finally:
        await r.aclose()

Synchronization Django View Usually, you can use the synchronization client directly.

There is no need to change the entire backend to an asynchronous architecture in order to use Redis.

22. Django:Redis Cache

Django natively provides Redis Cache Backend.

Installation:

pip install redis

In settings.py:

CACHES = {
    "default": {
        "BACKEND": "django.core.cache.backends.redis.RedisCache",
        "LOCATION": "redis://redis:6379/0",
        "TIMEOUT": 300,
    }
}

redis here is the service name in Docker Compose.

Basic cache

from django.core.cache import cache

cache.set("poi:123", {"name": "Tokyo Tower"}, timeout=600)

value = cache.get("poi:123")

cache.delete("poi:123")

get_or_set

value = cache.get_or_set(
    "popular_pois",
    get_popular_pois,
    timeout=300,
)

Note: get_or_set() provides a convenient cache reading and filling interface, but when using Cache Miss with high concurrency, it should not be assumed by default that it can guarantee that expensive calculations are only executed once.

Caching QuerySet results

It is generally recommended to cache the serialized results rather than randomly saving ORM QuerySet objects for long periods of time.

For example:

from django.core.cache import cache

def get_popular_pois():
    key = "popular_pois:v1"

    cached = cache.get(key)

    if cached is not None:
        return cached

    result = list(
        Poi.objects
        .filter(is_active=True)
        .values("id", "name")[:100]
    )

    cache.set(key, result, timeout=300)

    return result

Practical applications require adjusting queries based on model fields and business logic.

Django Session

Django can also use Redis via Cache-backed Session.

However, Session typically has higher reliability requirements than a normal droppable cache.

If cache Session is used, the consequences of Redis restarts, Eviction, failure recovery, and users being forced to log in again need to be carefully considered.

23. Celery and Redis

Redis is often Broker or Result Backend as Celery.

For example:

Django API
    ↓
Celery Task
    ↓
Redis Broker
    ↓
Celery Worker
    ↓
Document Processing

Celery Broker

Broker is responsible for delivering task messages.

For example, after a user uploads a document:

process_document.delay(document_id)

Worker gets the task from Broker and executes it.

Result Backend

Result Backend is used to save task status and results.

For example:

PENDING
STARTED
SUCCESS
FAILURE

Whether the specific status appears depends on the Celery configuration and task execution process.

Django configuration example

CELERY_BROKER_URL = "redis://redis:6379/1"

CELERY_RESULT_BACKEND = "redis://redis:6379/2"

Different logical database numbers are used here as an example.

Separate Redis DB numbers do not isolate memory usage, performance, or failures.

If the cache and task queue require independent memory limits, persistence, and high-availability strategies, separate instances should be used.

Responsibilities of Redis and Celery

Redis does not automatically execute the Python task.

Celery Worker is the process that actually performs the task.

Redis only assumes roles such as message passing and task status storage.

In addition, Celery itself contains task confirmation, retry and Worker management mechanisms, and its behavior cannot simply be equated to using Redis Streams directly.

For time-consuming tasks such as document parsing, Embedding calculations, and external API calls, Celery + Redis is a common technology combination.

24. Replication, Sentinel and Cluster

Redis provides multiple usability and expansion mechanisms.

Replication: Master-slave replication

Common structures:

Primary
   ├── Replica A
   └── Replica B

Primary is responsible for receiving writes, and Replicas copies data.

Replication can be used for:

  • Read extension.
  • Failure recovery.
  • Highly available architecture.

Note: Redis replication is usually asynchronous, and some acknowledged but not yet replicated writes may be lost during failover.

Redis Sentinel

Sentinel is mainly responsible for:

  • Monitor the Redis instance.
  • Detect faults.
  • Coordination Failover.
  • Provides discovery capabilities for the current Primary.

Sentinel is not responsible for horizontally fragmenting Key data into multiple Primary.

Redis Cluster

Redis Cluster is used to distribute Key to multiple nodes.

Redis Cluster uses 16384 Hash Slots.

A Key will be assigned to the corresponding Slot based on the hash result.

For example:

Cluster
├── Primary A → Slots 0~5460
├── Primary B → Slots 5461~10922
└── Primary C → Slots 10923~16383

This is just an illustration of the distribution method.

Redis Cluster can also be configured with Replicas for Primary to provide failure recovery.

Limitations of Cluster

Operations across multiple Key need to take Hash Slot into account.

For example via Hash Tag:

user:{1001}:profile
user:{1001}:session

You can have Key containing the same {1001} Hash Tag mapped to the same Slot.

This is important for some multi-Key transactions or script operations.

25. Redis Security: Security configuration

Redis often contains sensitive data such as cache, Session, or task messages.

The production environment needs to pay attention to:

network isolation

Do not expose Redis directly to the public network.

Priority passed:

  • Private Network。
  • Docker Internal Network。
  • Firewall Rules。
  • VPC。

Restrict access to sources.

Authentication / ACL

Redis supports ACL, which is used to set user and command permissions.

Do not allow all business clients to use unrestricted administrator privileges.

TLS

When communicating across untrusted networks, TLS or equivalent secure network channels should be used.

Secrets Management

The password and connection URL should not be committed to the Git repository.

You can use environment variables or a dedicated Secrets Management system.

Untrusted serialized content

Do not deserialize Python Pickle data from untrusted sources.

For caching and message payloads, controllable data formats such as JSON should be preferred and the input structure should be verified.

26. Redis Monitoring: Monitoring and performance analysis

Common operation and maintenance commands:

INFO
INFO memory
INFO stats
INFO clients
INFO replication
INFO persistence

Memory

MEMORY USAGE cache:poi:123

View memory footprint estimates for a single Key.

INFO memory

View Redis overall memory metrics.

Need to focus on:

  • Used Memory。
  • Maxmemory。
  • Evicted Keys。
  • Expired Keys。
  • Memory fragmentation or memory usage ratio.

Slow Log

SLOWLOG GET 10

Slow Log records the command execution time that exceeds the configured threshold.

It mainly counts the internal execution time of Redis, which is not equal to the complete client end-to-end network delay.

MONITOR

MONITOR

You can view the commands received by Redis in real time.

However, it will bring significant additional overhead, may also expose sensitive command content, and should not be enabled for a long time in high-load production environments.

Latency

LATENCY DOCTOR

For analyzing Redis delay events, corresponding delay monitoring configuration is required.

Indicators to watch out for

indicatorfunction
Cache Hit RateDetermine cache revenue
Used MemoryMemory usage
Evicted KeysIs the cache being evicted frequently?
Expired KeysProcessing of expired data
Connected ClientsNumber of client connections
Command LatencyCommand execution delay
Replication Lagreplication delay
Stream Pending EntriesWhether consumers have a backlog of messages

27. Common mistakes and practical suggestions

1. Treat Redis as the only storage for all business data

For data that is important and requires complex transactions and relational constraints, reliable databases such as PostgreSQL should generally be preferred.

Redis can save derived state, cache, and temporary data.

2. The cache does not have TTL

If there is no reasonable invalidation mechanism, the cache may store expired data for a long time and occupy a lot of memory.

3. Use GET + SET to maintain high concurrency counters

Atomic commands such as INCR and HINCRBY should be used first.

4. Use KEYS on large data sets

SCAN should be used and limit the amount of data processed at a time.

5. Treat Pub/Sub as a reliable message queue

Pub/Sub does not save offline messages and does not provide ACK.

Streams, Celery or other messaging systems should be considered when reliable consumption is required.

6. Mixed use of cache, Broker, and important status

Different uses have different requirements for persistence, Eviction, and performance.

It is recommended to perform instance-level isolation based on reliability requirements.

7. Ignore idempotence

Message retries, distributed lock expiration, and network abnormalities may cause repeated execution of business operations.

Important businesses should rely on database constraints, idempotent Key, state transition verification and other mechanisms to ensure correctness.

8. Redis The fewer commands, the faster it must be

Not necessarily.

Need to also consider:

  • Command complexity.
  • Network RTT.
  • Pipeline。
  • Data structure size.
  • Memory usage.
  • Client concurrency.
  • Whether there is a blocking command.

Performance optimization of Redis should be based on actual measurements, not just on the judgment that "Redis is in memory so it must be fast".


Summary

Knowledge pointsimportance
Redis / Key-Value / In-Memorycore
String / Hashcore
List / Set / Sorted Setcore
TTL / Expirationcore
Cache-Aside / Invalidationcore
Cache Penetration / Breakdown / Avalancheimportant
Eviction / LRU / LFUcore
RDB / AOFcore
Atomic Commandscore
Pipeline / MULTI / WATCHimportant
Lua Scriptingimportant
Rate Limitingimportant
Pub/Sub / Streamscore
Consumer Groups / ACKimportant
Distributed Lockimportant
redis-py / Async Rediscore
Django Cache / Celery Brokercore
Replication / Sentinel / Clusterimportant
Security / Monitoringcore

Redis The six most important concepts:

  1. Data Structures: Redis is not just String Key-Value Store, but provides a variety of data structures suitable for different business scenarios.
  2. TTL & Caching: Cache needs to consider expiration, invalidation, consistency, hit rate and eviction at the same time.
  3. Atomic Operations: Atomic commands such as INCR and SET NX can solve some common concurrency problems, but they cannot replace complete business transactions.
  4. Persistence: RDB and AOF provide different persistence trade-offs, and the memory storage of Redis does not mean that data will be lost.
  5. Messaging: Pub/Sub is suitable for real-time broadcast, Streams supports historical messages, Consumer Groups and ACK, and Celery provides more complete task execution management.
  6. Operational Reliability: Production environments need to consider memory constraints, security, persistence, replication, failure recovery, and monitoring.

Reference documentation

Back to top