Bookmarks
ReferenceData & AIBackendVerified

Redis

Redis is an in-memory data structure store for caching, queues and counters. This reference covers data types, TTL, Pub/Sub and Streams, RDB and AOF, Cluster, ACL and Valkey.

checked 7 Nov · next check 14 Nov · 75 min read

Sections
13
Reading
75 min
Current version
8.10.3
Written from
redis.io/docs/latest

Check status of the reference

Verified 7 Nov · next check 14 Nov

The sections were compared with the release notes, the check found nothing, and all source links respond.

  1. Verified
  2. Scheduled check

What Redis is and how it works

Redis is an in-memory data structure store. Each key holds a value of one type: string, hash, list, set, sorted set, stream or JSON. Commands run in fractions of a millisecond because the data lives in RAM.

When Redis is a good fit

Redis suits small data that must be accessed fast and can be rebuilt if needed:

  • caching of query results and pages;
  • user sessions with a key time to live (TTL);
  • counters and rate limiting;
  • job queues and event streams;
  • rankings and leaderboards built on sorted sets.

Redis is not suitable as the only store for data you cannot afford to lose: even with persistence enabled, the last few commands may not reach the disk. Your data must also fit in the server’s memory: beyond the limit, Redis either evicts keys or refuses writes. Keep your primary data in a relational database and run Redis alongside it.

How Redis processes commands

A single thread serves commands: it accepts requests from all clients through multiplexing and executes them strictly one at a time. This makes every command atomic and removes the need for locks between clients. The downside is that a command that walks a large collection delays every other client. Redis uses background threads only for slow I/O operations, such as disk work.

Dashed lines are background processes: writing to disk and sending data to the replica.

Where the data is stored

The working set is always in memory. To survive a restart, Redis can periodically save a snapshot of the whole dataset (RDB) or append every write command to a log (AOF); the modes can be combined or disabled. For details, see the section “Persistence: RDB and AOF”. Copies of the data on other servers are replicas; they are covered in the section “Replication, Sentinel and Cluster”.

How it differs from Valkey and Kafka

In March 2024 Redis changed its licence, and the community created the Valkey fork under the Linux Foundation. A comparison based on the documentation of both projects:

AspectRedis Open SourceValkey
Originthe original project, led by Redis Ltd.a fork of Redis OSS 7.2, a Linux Foundation project
Protocol and commandsits own new commands and typescompatible with Redis OSS 7.2 and earlier
Licence up to 7.2BSDBSD
Licence of newer versions7.4 to 7.8: RSALv2 or SSPLv1; 8 and later: also AGPLv3BSD
New featuresJSON, vector sets and other types are includedthe 7.2 fork evolves independently, with its own releases
Where to get itredis.io, GitHub redis/redis, Docker imagesvalkey.io, GitHub valkey-io/valkey

For most applications, clients work with both servers in the same way as long as you stick to the Redis features available up to 7.2. Commands and types added later may differ between the projects: check the ones you need in the documentation of the server you choose.

Redis Streams and Kafka solve similar problems, event delivery, but Redis streams are held in the server’s memory, while Kafka is a distributed log on disk; see the Kafka reference for a comparison.

What you should know first

  • The Linux command line: files, processes, permissions (see the Linux reference)
  • Docker, if you run Redis in a container (see the Docker reference)

Section sources

the section is written from these pages

Cheat sheet

This page collects the Redis commands you need every day: strings and key time to live (TTL), hashes, lists, sets, sorted sets, streams, transactions and server diagnostics. The flags and pitfalls of each command are covered in its own section of the reference.

Run the examples in redis-cli. A prefix in a key name shows what it refers to: user:42 is the user with ID 42, session:abc is their session. The type names in the documentation are string, hash, list, set, sorted set and stream; how they work is described in the section “Data types and keys”.

Keys and time to live

TaskCommand
Write a string with a 60-second time to liveSET session:abc "data" EX 60
Read a valueGET session:abc
Set a time to live on an existing keyEXPIRE user:42 3600
Show the seconds left before deletionTTL session:abc
Remove the time to live so the key becomes permanentPERSIST user:42
Delete one or more keysDEL user:42 session:abc
Start iterating over keys by patternSCAN 0 MATCH user:* COUNT 100
Continue iterating from the returned cursorSCAN 17 MATCH user:* COUNT 100
Check the type of a valueTYPE user:42
Check whether a key existsEXISTS user:42
Write a new value and get the previous oneSET user:42 "anna" GET
Count the keys in the current databaseDBSIZE

Hashes, lists and sets

TaskCommand
Write several hash fields at onceHSET user:42 name "Anna" age 33
Read one fieldHGET user:42 name
Read the whole hashHGETALL user:42
Append to the end of a listRPUSH tasks:42 "email"
Pop an element from the start of a listLPOP tasks:42
Read a range of a listLRANGE tasks:42 0 9
Add a set memberSADD tags:42 "redis"
Intersect two setsSINTER tags:42 tags:43
List all members of a setSMEMBERS tags:42
Count the members of a setSCARD tags:42

Sorted sets

TaskCommand
Add a member with a scoreZADD board 1520 user:42
Top 10 members in descending orderZRANGE board 0 9 REV WITHSCORES
Member’s position in ascending score orderZRANK board user:42
Member’s scoreZSCORE board user:42
Members within a score rangeZRANGE board 100 200 BYSCORE
Count the membersZCARD board

Streams

TaskCommand
Add an entry to a streamXADD events:42 * event signup
Trim a stream to roughly 1,000 entriesXADD events:42 MAXLEN ~ 1000 * event login
Read new entries as part of a groupXREADGROUP GROUP workers w1 STREAMS events:42 >
Count the entries in a streamXLEN events:42

Transactions

TaskCommand
Start queuing commandsMULTI
Apply the queued commands as a wholeEXEC
Discard the queued commandsDISCARD
Watch a key until EXECWATCH user:42
bashin redis-cli
# watch the session keyWATCH session:abc# a nil reply from EXEC means the key changed; retryMULTISET session:abc "new-token" EX 60EXEC

Server and diagnostics

TaskCommand
Server memory summaryINFO memory
Cache hit and miss countersINFO stats
Most recent slow commandsSLOWLOG GET 10
Analysis of latency causesLATENCY DOCTOR
Current value of a settingCONFIG GET maxmemory
Memory used by a single keyMEMORY USAGE user:42:profile

Dangerous commands

TaskCommand
Clear all databasesFLUSHALL ASYNC
Clear the current databaseFLUSHDB ASYNC
Find keys by pattern (not on a production server)KEYS user:*
Change a setting until restartCONFIG SET maxmemory 512mb
Write the changes to the configuration fileCONFIG REWRITE
bashin redis-cli
# change the memory limit until the next restartCONFIG SET maxmemory 512mb# persist it in redis.confCONFIG REWRITE

Section sources

the section is written from these pages

Installation and first run

Install Redis Open Source on Ubuntu and Debian from the official APT repository at packages.redis.io; for development on any system, run the server in Docker. You can verify the installation with one command: redis-cli ping should reply PONG.

Linux: Ubuntu and Debian

The redis package installs the server, the redis-cli client and utilities, and new releases arrive from the packages.redis.io repository. It supports Ubuntu 22.04, 24.04 and 26.04, and Debian 12 and 13.

bashon an Ubuntu or Debian server
# dependencies for working with the repositorysudo apt-get install lsb-release curl gpg# the key that signs the repositorycurl -fsSL https://packages.redis.io/gpg | \  sudo gpg --dearmor -o /usr/share/keyrings/redis-archive-keyring.gpgsudo chmod 644 /usr/share/keyrings/redis-archive-keyring.gpg# add the repository to /etc/apt/sources.list.decho "deb [signed-by=/usr/share/keyrings/redis-archive-keyring.gpg] https://packages.redis.io/deb $(lsb_release -cs) main" \  | sudo tee /etc/apt/sources.list.d/redis.listsudo apt-get updatesudo apt-get install redis

apt policy redis lists the available versions; to pin a specific version, list the redis, redis-server and redis-tools packages with the version number in the apt-get install command. After installation, the redis-server service starts on its own and starts at boot; if it does not:

bashon the server
sudo systemctl enable redis-serversudo systemctl start redis-server

Docker

On macOS and Windows, or when you need the server only during development, run the official redis image in Docker. Put the data in a named volume called redis-data: Redis uses the /data directory inside the container for persistence. You do not need to install the client, because redis-cli runs inside the container with docker exec -it redis redis-cli.

bashon a host with Docker
docker run -d --name redis \  -p 127.0.0.1:6379:6379 \  -v redis-data:/data \  redis:8.10

macOS and Windows

On macOS, install the Homebrew redis formula: it installs the latest release and puts the configuration in $(brew --prefix)/etc/redis.conf. On Windows, Redis Open Source is supported only through Docker; run the same container in PowerShell, as there is no separate server build for Windows.

bashon macOS
brew install redis# background service, starts at loginbrew services start redis

Verifying the installation

The PING command checks that the server is alive: any connected client gets PONG in reply. INFO server prints details about the running server:

bashon the host
redis-cli ping
textexample output
PONG
bashon the host
redis-cli INFO server
textexample output
# Serverredis_version:8.10.3redis_mode:standaloneos:Linux...config_file:/etc/redis/redis.conf

The redis_mode field shows the operating mode, standalone, sentinel or cluster, and config_file shows the path to the file the server was started with. In a package installation this is /etc/redis/redis.conf.

Connecting with redis-cli

By default, redis-cli connects to 127.0.0.1:6379. The -h and -p flags set the server address and port, -n sets the database number, -a the password and --user the ACL user name (see the section “Security” for the list of users). You can pass everything at once as a URI with the -u flag:

bashon the host
redis-cli -h 192.0.2.10 -p 6380 PING# the password comes from an environment variableREDISCLI_AUTH=$REDIS_PASSWORD redis-cli PINGredis-cli -u redis://app:change-me@example.com:6379/0 PING
FlagWhat it doesDefault
-hserver address127.0.0.1
-pserver port6379
-ndatabase number0
-a, --passpassword; REDISCLI_AUTH is safer—
--userACL user name, used together with -adefault
-uaddress in the form redis://user:password@host:port/db—

A password in the -a argument is visible in the command history and in the ps process list, so the documentation recommends the REDISCLI_AUTH environment variable. Without arguments, redis-cli opens interactive mode: a prompt like 127.0.0.1:6379>, where each line you type is sent to the server as one command and the reply is printed in a readable form. The URI scheme lets you omit the user, password and database number; for a TLS connection the scheme is different, rediss (see the section “Security”).

consoleinteractive mode
redis-cli127.0.0.1:6379> SET greeting "Hello"OK127.0.0.1:6379> GET greeting"Hello"

Inspecting keys and latency

redis-cli has modes for inspecting a running server. --scan prints keys through the SCAN command without blocking the server; --pattern sets the filter. --bigkeys walks the database and shows the largest key of each type. --latency sends PING 100 times a second and prints the minimum, maximum and average response time in milliseconds.

bashon the host
# keys with the user: prefix, without blocking the serverredis-cli --scan --pattern 'user:*'# summary of the largest keys of each typeredis-cli --bigkeys

The redis.conf file

The server can run without a file, using built-in defaults, but the documentation recommends this only for development and testing. The production approach is a redis.conf file: since version 8.10 Redis Open Source has a single one, and its format is directives of the form name value, for example replicaof 127.0.0.1 6380. A self-documented sample file ships with the distribution.

You apply a change without a restart using CONFIG SET, and it takes effect from the next command. To make the change survive a restart, CONFIG REWRITE writes it to the file the server was started with; settings equal to their defaults are not added to the file.

bashon the host
# takes effect immediately, no server restartredis-cli CONFIG SET maxmemory 256mb# write the change to redis.confredis-cli CONFIG REWRITE

Section sources

the section is written from these pages

Data types and keys

Redis stores everything in keys, and each key holds a value of one type: string, hash, list, set, sorted set, stream or another type. The type determines the commands, memory use and speed.

Keys and their names

A key is a byte string that is unique within a database; an empty string is also allowed. Redis has no namespaces, so collisions are avoided by convention within the project: names with a colon, such as user:42 and office:London:1; separate multi-word parts with a dot or a hyphen.

Stick to a type:identifier scheme and a moderate length: a long key wastes memory and slows lookups, while a short one such as u1000flw is hard to read. A scheme lets you find keys by prefix with SCAN MATCH. TYPE shows the type of a value: string, list, set, zset, hash, stream, vectorset.

bashin redis-cli
SET user:42 annaTYPE user:42

Key time to live

You can give any key a time to live (TTL): when it expires, Redis deletes the key along with its value. Set it with EXPIRE in seconds or PEXPIRE in milliseconds, and for strings directly with the EX and PX options of SET. TTL shows the time remaining, and PERSIST removes the expiry.

bashin redis-cli
SET session:abc data EX 60 TTL session:abc # extend, then remove the expiryEXPIRE session:abc 3600PERSIST session:abc

Iterating over keys

To iterate over keys by pattern, use SCAN, not KEYS: KEYS blocks the server until it has walked the whole database. SCAN returns some of the keys plus a cursor, the next call continues from it, and the server handles ordinary commands between calls. In exchange, SCAN gives weak guarantees: elements added or removed during the iteration may be missed or returned twice. There is no guarantee on the number of elements returned: on a large collection it is a few dozen, while on a small one SCAN may return everything at once. COUNT is only a hint about the amount of work per call; the default is 10.

bashin redis-cli
# first step of the iterationSCAN 0 MATCH session:* COUNT 100 # continue from the cursor until 0 is returnedSCAN 17 MATCH session:* COUNT 100

Strings

A string (string) is the basic type: a binary-safe sequence of bytes up to 512 MB. INCR atomically increments an integer: a counter starts from zero, and there are no races between clients. SET with NX writes a value only if the key does not exist, which is how you take a lock, and EX sets the expiry in the same call.

bashin redis-cli
# counter: atomic across all clientsINCR page:about:views # lock: written only if the key does not existSET lock:report worker-1 NX EX 30

Hashes

A hash (hash) stores field–value pairs under one key and suits objects: HSET writes fields, HGET reads one, HGETALL returns everything and HINCRBY increments a numeric field. Hashes cannot be nested; a structure deeper than one level calls for JSON.

bashin redis-cli
# a user object under a single keyHSET user:42 name anna age 33HGETALL user:42 # a field as a counterHINCRBY user:42 logins 1

Individual hash fields can have their own time to live: since Redis 7.4, HEXPIRE sets a TTL in seconds for the listed fields and HTTL shows the time remaining. This is handy for windowed counters.

bashin redis-cli
# the sensor field lives for 60 secondsHSET sensor:1 air_quality 256HEXPIRE sensor:1 60 FIELDS 1 air_qualityHTTL sensor:1 FIELDS 1 air_quality

Lists

A list (list) is an ordered sequence of strings in insertion order: LPUSH and RPUSH add to the head and the tail, and LPOP and RPOP remove, which is why queues and stacks are built on lists. If the list is empty, BLPOP does not reply immediately but blocks the connection until an element appears; a timeout of 0 waits forever. LMOVE atomically moves an element between lists, which is how you build a reliable queue.

bashin redis-cli
# queue: push on the right, pop from the left and waitRPUSH queue:mails task-101BLPOP queue:mails 0 # reliable queue: the element moves to processingLMOVE queue:mails processing:mails LEFT LEFT

Sets and sorted sets

A set (set) is an unordered collection of unique strings: a repeated SADD of an existing element is ignored. It supports membership checks and set operations, SINTER, SUNION and SDIFF, so sets are used for tags and unique lists.

bashin redis-cli
# an article’s tags: no duplicates appearSADD article:7:tags redis databasesSADD article:8:tags redis performance # tags shared by two articlesSINTER article:7:tags article:8:tags

A membership check costs O(1), but only SMEMBERS can return the whole set, and on a large collection it is O(N) and the server serves no other commands while it runs; read large sets with SSCAN.

A sorted set (zset) holds unique strings with a numeric score and orders them by it. ZADD adds a member or updates its score, ZRANGE with the REV flag returns the top of the list, ZINCRBY adds to a score and ZRANK shows a position. You can change a score at any time in O(log N), which makes the type a good fit for rankings and leaderboards.

bashin redis-cli
# leaderboard: write and increase pointsZADD board 1520 user:42ZINCRBY board 50 user:42 # top 10 in descending order with scoresZRANGE board 0 9 REV WITHSCORES

Other types

The other types cover specific tasks and are described in detail in their own sections of the reference. A stream (stream) is an append-only log with consumer groups; JSON holds nested documents accessed by JSONPath; bitmaps are bit operations on a string; HyperLogLog counts unique items approximately, with an error of 0.81% at 12 KB per key; a geospatial index stores coordinates and searches by radius; vector sets find similar vectors. Choose the type by the task: almost anything can be modelled with strings, but each type has its own trade-offs in memory and speed.

TaskTypeKey commands
Session, cache entry with a time to livestringSET with EX, GET
View and like counterstringINCR, INCRBY
Object with fields: user, producthashHSET, HGETALL, HINCRBY
Job queue and stacklistLPUSH, RPUSH, BLPOP, LMOVE
Tags and unique visitorssetSADD, SINTER, SDIFF
Ranking and leaderboardsorted setZADD, ZRANGE … REV, ZINCRBY
Event log and consumer groupsstreamXADD, XREADGROUP
Nested documentJSONJSON.SET, JSON.GET
Flags and uniqueness without an exact countbitmap, HyperLogLogSETBIT, PFADD, PFCOUNT
“What is nearby” by coordinatesgeospatial indexGEOADD, GEOSEARCH
Finding similar vectorsvector setVADD, VSIM

Section sources

the section is written from these pages

Caching and eviction

Redis is often used as a cache in front of a slow database: keys are copies of data that can be re-read from the database at any time. A key’s time to live (TTL) limits how stale a copy can get, while the maxmemory limit and the eviction policy decide what to delete when memory runs out.

The main pattern is cache-aside: the application reads the cache itself, goes to the database on a cache miss, and stores the result in Redis with a TTL. The cache holds only the data that was actually requested, so memory is bounded by the working set rather than the whole table.

Dashed arrows are replies; step numbers match the list below.
  1. Cache miss: GET user:42 returned nil, so the key is not in the cache.
  2. The application reads the row from the database with an ordinary query.
  3. The result is stored with SET and the EX 300 option, so the key lives for 300 seconds.
  4. The next GET for the same key returns the row from the cache: a cache hit.

On a write, the application updates the database and then immediately deletes the key from the cache (DEL user:42): the next reader gets a miss and puts the fresh row in the cache. Deleting the key before the database write is risky, because another reader can cache the old data between the deletion and the write.

pythonthe cache-aside pattern
def get_user(user_id):    key = f"user:{user_id}"    cached = redis.get(key)    if cached is not None:        return json.loads(cached)    row = db.one(        "SELECT id, name, email FROM users WHERE id = %s",        (user_id,),    )    # 60 s of jitter so keys don’t all expire at once    ttl = 300 + random.randint(0, 60)    redis.set(key, json.dumps(row), ex=ttl)    return row

Choosing a TTL

A TTL is an upper bound on staleness: it is how long readers can keep getting a copy after it was written to the cache. The shorter the TTL, the fresher the data and the heavier the load on the database; the longer it is, the higher the hit rate. If the business can tolerate data that is a second old, start with 60 seconds and watch the hit rate.

Give each key a range rather than an exact TTL: add random jitter to a base value. Otherwise keys written in one batch expire in the same second and cause an avalanche of misses: when a popular key expires under load, dozens of processes hit the database for the same record at once. This is called a cache stampede.

Memory limit and eviction policies

While the data fits within the limit, the policy does nothing: Redis checks memory on every write and acts only once the limit is exceeded. The limit is set by maxmemory and the policy by maxmemory-policy.

bashredis.conf
# cache data limit and eviction policymaxmemory 512mbmaxmemory-policy allkeys-lrumaxmemory-samples 5

The default policy is noeviction: keys are never deleted. When memory is full, commands that add data (SET, HSET, RPUSH) return an out-of-memory (OOM) error, while reads of existing keys continue. The client sees the write rejected and decides for itself: retry, serve the data from the database or bypass the cache. If accuracy matters more than speed, this is a deliberate choice; for a cache you normally pick a policy that frees memory by itself.

The other policies are split into allkeys-*, where every key is a candidate, and volatile-*, where only keys with a TTL are. Since Redis 8.6 there is also eviction by last modification time, allkeys-lrm and volatile-lrm; they work like the LRU variants but look at writes instead of reads.

PolicyWhat it evictsWhen to choose it
noevictionnothingRedis is the primary data store and writes must not be lost
allkeys-lruany keys, least recently used firsta pure cache; a good choice if you are unsure
allkeys-lfuany keys, least frequently used firstuneven popularity, “hot” keys
allkeys-randomrandom keyskeys are read roughly uniformly
volatile-lrukeys with a TTL, least recently used firstcache and permanent data in one instance
volatile-lfukeys with a TTL, least frequently used firstthe same, with uneven popularity
volatile-randomrandom keys with a TTLthe same, with uniform access
volatile-ttlkeys with a TTL, shortest remaining time firsta short TTL is assigned in advance to eviction candidates

Approximated LRU and LFU

Redis computes LRU (least recently used) approximately rather than exactly: when evicting, the server samples a few random keys (5 by default, set by maxmemory-samples) and deletes the one that was used longest ago. So the “oldest” key may survive a round while a fresher one is deleted: accuracy improves with the sample size at the cost of CPU time. Since Redis 3.0 the algorithm keeps a pool of the best candidates, and in approximate measurements it is almost indistinguishable from exact LRU.

LFU (least frequently used) counts frequency: each key has an access counter, and rarely used keys go first. The counter is probabilistic and takes a few bits, and it decays over time so that it stops protecting keys that were only popular in the past. By default the counter saturates at about a million accesses and decays once a minute; the settings are lfu-log-factor and lfu-decay-time.

Monitoring effectiveness

bashin redis-cli
# hit, miss and eviction countersINFO stats

The hit rate is keyspace_hits divided by the sum of keyspace_hits and keyspace_misses from INFO stats. Measure it after warm-up: misses are unavoidable in the first minutes. If the rate is lower than expected, check evicted_keys: many evictions mean the policy is deleting the wrong keys. If evictions are few but the hit rate is still low, look at expired_keys: the TTL may be too short.

A cache can also live in the application’s own memory: in client-side caching mode the application enables tracking with CLIENT TRACKING, and the server sends notifications when tracked keys change, so the application can drop the stale copy.

For a summary of cache commands, see the “Cheat sheet” section; memory per key is measured in the “Performance and memory” section.

Section sources

the section is written from these pages

Pub/Sub and Streams

Redis delivers events through two mechanisms: Pub/Sub broadcasts messages to the subscribers of a channel and stores nothing, while streams keep entries in a log and let consumers acknowledge processing. Choose Pub/Sub for fire-and-forget notifications to live subscribers, and streams for jobs where losing an entry is unacceptable.

In Pub/Sub, subscribers receive only the messages published while they are connected: a publisher sends a message to a channel with PUBLISH, and the server hands it to every subscriber of that channel. If a subscriber is not there at the moment of publishing, or its connection has dropped, the message is lost for good: Redis keeps no channel history and will not deliver it retroactively. PUBLISH returns the number of subscribers the message was sent to; the pattern PSUBSCRIBE news.* catches messages from every channel with that prefix.

consolethe news:deploy channel
# terminal 1: subscriberSUBSCRIBE news:deploy # terminal 2: publisherPUBLISH news:deploy v1.4.2 # terminal 1 receives:# 1) message  2) news:deploy  3) v1.4.2

Channels are not tied to keys or databases: a message published in database 10 is heard by a subscriber in database 1, so separate environments with a prefix such as staging:events. In a cluster, regular Pub/Sub sends every message to all nodes; since 7.0, the SSUBSCRIBE and SPUBLISH commands forward a message only within the shard that owns the channel.

Streams: a log with entry IDs

A stream is a key of type stream: an append-only log of entries. XADD adds an entry made of field-value pairs and returns its ID: the time in milliseconds and a sequence number within that millisecond, joined by a hyphen, for example 1793964453109-0. Entries can be read back by ID, so events in a stream are not lost even if no reader was connected yet.

bashin redis-cli
XADD orders * item tea amount 2XADD orders * item coffee amount 1 # the whole stream historyXRANGE orders - + # entries from a single millisecond, 1793964453109XRANGE orders 1793964453109 1793964453109
bashin redis-cli
# keep about 1000 entriesXADD orders MAXLEN ~ 1000 * item tea # wait up to 5 seconds for new entriesXREAD BLOCK 5000 STREAMS orders $

IDs increase strictly: XADD with an ID lower than the last one returns an error. The asterisk asks Redis to generate the ID itself; you can pass your own instead. New entries are read with XREAD and the ID $, meaning “only what appears after this call”, together with the BLOCK option, which waits up to the given number of milliseconds; 0 waits forever.

Without a limit, a stream grows until memory runs out. The MAXLEN option of XADD trims old entries on every insert, and the ~ sign asks for approximate trimming, which is much cheaper and leaves a few dozen entries more than the limit. XTRIM trims a stream in a separate call, including by ID (MINID).

Consumer groups

A consumer group divides the entries of a stream among several workers: each entry goes to exactly one of them. XGROUP CREATE creates a group starting from $ (fresh entries) or 0 (the beginning of the stream); the MKSTREAM flag also creates an empty stream. One stream can serve several independent groups.

bashin redis-cli
# a group from the start of the stream; create the stream if it doesn’t existXGROUP CREATE orders workers 0 MKSTREAM # worker alice takes two unread entriesXREADGROUP GROUP workers alice COUNT 2 STREAMS orders > # worker bob takes the next onesXREADGROUP GROUP workers bob COUNT 2 STREAMS orders >

The ID > means “only entries the group has not yet delivered to anyone”. After receiving an entry, a worker processes it and acknowledges it with XACK; until then the entry counts as pending. Each group has its own pending entries list (PEL): XPENDING shows how many entries each consumer holds and, in its extended form, the idle time and delivery count of each entry.

The accent marks the group’s last delivered entry, 3-0; entries 4-0 and 5-0 wait for a request with the “greater than” sign.

If a worker dies, its entries stay pending. Another worker takes them over with XAUTOCLAIM: it finds entries idle for longer than a given time and reassigns them to the specified consumer, like XCLAIM but in a single call. The command returns a cursor for the next call and walks the list in batches; entries that no longer exist in the stream after trimming are removed from the list automatically.

Redis stores the group’s position, the ID of the last delivered entry, itself: after a restart a worker reads the continuation rather than starting over. Without acknowledgements, using the NOACK flag of XREADGROUP, entries do not enter the pending list; this is done when losing a single entry is tolerable. XACK does not delete the entry from the stream; it only removes it from the group’s pending list.

bashin redis-cli
# what workers are holdingXPENDING orders workers - + 10 # claim entries idle for more than a minute, then acknowledgeXAUTOCLAIM orders workers alice 60000 0-0 COUNT 10XACK orders workers 1793964453109-0

Pub/Sub, streams or a list

FeaturePub/SubStreamsList as a queue
Storagenone; the message disappears immediatelya log of entries with historyelements in a list
Who receivesall connected subscribers of the channelall readers; one per entry within a groupa single BLPOP/BRPOP caller
AcknowledgementnoneXACKnone
Retry after a failurenofrom the PEL or XRANGEno
Start after downtimenew messages onlyfrom any IDfrom the start of the queue
Fan-outyesyes, without a groupno

For background jobs such as emails and webhooks, use streams: restarting a worker will not lose a job, and XPENDING will show the stuck ones. Pub/Sub suits real-time hints: client-side cache invalidation, metrics broadcasting, key events. When events must be kept for a long time and shared among many applications, use a message broker; see the Kafka reference, the section “What Kafka is and how it works”.

Keyspace notifications

Keyspace notifications are Pub/Sub in which Redis itself publishes events about keys: writes, deletions, expirations. They are off by default: the notify-keyspace-events configuration string is built from letters, where K selects events of the “what happened to the key” kind, E the “which operation” kind, x expirations, and KEA enables almost everything. In a cluster, a node publishes events only for its own keys.

bashin redis-cli
CONFIG SET notify-keyspace-events KEA # subscriber terminalPSUBSCRIBE __key*__:* # after SET session:abc data EX 60 you receive:# pmessage __keyspace@0__:session:abc set# pmessage __keyevent@0__:set session:abc

An expiration event fires when Redis deletes the key, not when its TTL formally runs out, so the delay can be noticeable. Do not build critical logic on such events: this is the same Pub/Sub with no delivery guarantees.

Section sources

the section is written from these pages

Transactions, Lua and functions

A Redis transaction is a set of commands that run one after another without commands from other connections interleaving. There is no rollback: an error in one command does not cancel the others. When commands need to branch on a value, write a Lua script instead of a transaction: it is also atomic and can decide as it goes.

MULTI opens a transaction. After that, commands are not executed but queued, and the server replies QUEUED to each. EXEC applies the whole set in order and returns an array of replies in queue order, while DISCARD clears the queue and closes the transaction. Until EXEC, the set has no effect: if the connection drops, it vanishes.

bashin redis-cli
MULTISET cart:42:item teaDECR stock:teaEXEC

At the moment of EXEC, the server runs the commands without a break and does not serve other connections; that is what atomicity means here. But this is not a transaction in the database sense: there is no cancellation on error and no isolation levels.

Errors before and during EXEC

Errors fall into two cases. A command with a wrong name or number of arguments is not queued: the server notices at once and, since version 2.6.5, refuses to run the set. EXEC returns an EXECABORT error, nothing is executed, and the connection leaves the transaction.

A command can also be queued successfully and then fail at execution time, for example LPUSH on a string. In that case the server reports a WRONGTYPE error in the array of replies, and the other commands still run. There is no all-or-nothing cancellation: writes made before the failing command stay.

consolean error during EXEC
MULTISET bike:1 DeimosLPUSH bike:1 repairEXEC # 1) OK# 2) WRONGTYPE Operation against a key#    holding the wrong kind of value

WATCH: conditional changes

WATCH monitors keys until EXEC is called. If a watched key changes, whether through another connection or a TTL expiring, EXEC returns nil and the transaction is not executed. This is optimistic locking: you read a value and prepare a change, expecting the key to stay untouched.

textclient pseudocode
# deduct 100 from the account, only if the balance hasn’t changedWATCH account:1balance = GET account:1MULTISET account:1 balance-100EXEC# nil: the key was modified, start over

The side that loses the race repeats the cycle: it reads the fresh value and tries again. For string keys, version 8.4 offers comparison options instead of a loop: SET with the IFEQ option writes a value only if the current one matches the one given, and DELEX deletes in the same way.

consolecomparison in a single command
SET bike:1 DeimosSET bike:1 Ares IFEQ DeimosSET bike:1 Zeus IFEQ Deimos # OK# (nil): the value is already “Ares”, so the write was rejected

After EXEC, all keys stop being watched automatically, even if the transaction did not go through; to stop watching earlier, use UNWATCH.

Lua scripts

A script covers what a transaction cannot: intermediate values stay on the server, and the decision is made on the data rather than on the client’s guess. You can deduct a balance with DECRBY without a script, but “deduct only if the remainder is at least the amount” you cannot: another client’s command can slip in between the read and the write.

bashin redis-cli
EVAL "local b = tonumber(redis.call('GET', KEYS[1])) if not b or b < tonumber(ARGV[1]) then return -1 end return redis.call('DECRBY', KEYS[1], ARGV[1])" 1 account:1 100

EVAL has two required arguments: the script text and the number of keys, followed by the keys themselves and the remaining arguments. Inside the script, keys are available in the KEYS table and other values in ARGV; the script accesses the database through redis.call. Work only with keys passed in KEYS, because in a cluster the server uses them to find the right node.

Every EVAL sends the whole script text. To avoid shipping it over the network each time, load the script with SCRIPT LOAD and then call it with EVALSHA using the returned SHA1 digest. The script cache does not survive a restart: when it gets NOSCRIPT, the client loads the text again, which client libraries do for you.

bashin redis-cli
# the SHA1 digest comes back in the replySCRIPT LOAD "return redis.call('GET', KEYS[1])"# then call the script by that digestEVALSHA d3c21d0c2b9ca22f82737626a27bcaf5d288f99f 1 account:1

Functions: libraries on the server

EVAL scripts live on the application side: after a server restart their cache is empty, and each application instance stores the texts and reloads them. Functions, available since version 7.0, live on the server: a library is loaded with FUNCTION LOAD, survives restarts, is written to the AOF and is replicated along with the data.

textmylib.lua
#!lua name=mylibredis.register_function('spend', function(keys, args)    local b = tonumber(redis.call('GET', keys[1]))    if not b or b < tonumber(args[1]) then return -1 end    return redis.call('DECRBY', keys[1], args[1])end)
bashon the host
cat mylib.lua | redis-cli -x FUNCTION LOAD REPLACEFCALL spend 1 account:1 100

The first line of a library is a shebang with the engine name and the library name; functions are registered with redis.register_function, and the function name is the entry point. The call is FCALL name numkeys key… arg…, as with scripts. A library is updated as a whole with the same FUNCTION LOAD and the REPLACE option; you cannot change a single function.

Functions and scripts access data only through redis.call; declaring global variables is not allowed. This sandbox keeps behaviour identical on the primary and its replicas.

FeatureMULTI/EXEC with WATCHScript or function
Condition on a valuemanual: read, prepare, retry on nilinside the script: read and decide
Rollback on command errornone; a failing command does not cancel the othersnone; whatever was written before the error stays
Round trips to the serverseveral: WATCH, a read, EXECone EVALSHA or FCALL call
Where the code livesnowhere; the client sends the commandsthe script cache or a library on the server
Survives a restartyes; the code is on the client sidefunctions yes, script cache no

Which to choose

For grouped writes with no conditions, use a transaction: no server-side code is needed. Conditional logic based on a key’s value calls for a script or a function; functions suit permanent server-side operations, while EVAL is enough for one-off checks. For a conditional update of a single string, use IFEQ or DELEX: one command instead of a retry loop.

Sending several commands without a transaction is called pipelining: it only saves network round trips and gives no atomicity. For how to enable it and how many commands to keep in a batch, see the “Performance and memory” section.

Section sources

the section is written from these pages

Persistence: RDB and AOF

Redis keeps data in memory, so when the process stops, anything not written to disk is lost. Data reaches disk in two ways: an RDB snapshot, a binary file with the state at the moment of saving, and an AOF (append-only file), a log of every command. The configuration determines how much you lose in a crash.

The two mechanisms can be enabled together, which the documentation recommends if the data is valuable. For a cache that refills itself after a loss, scheduled snapshots are enough.

The child process writes the snapshot; the main process writes the log.

RDB snapshots

A snapshot is a compact binary file with the state at the moment of saving; by default it is dump.rdb in the working directory. The schedule is defined by save points: “this many seconds and this many changes”, and there can be several.

bashredis.conf
save 3600 1 300 100 60 10000dbfilename dump.rdbdir /var/lib/redis

The line above reads: once an hour if at least one key changed, every 5 minutes if 100 changed, every minute if 10,000 changed. These are the defaults. You can take a snapshot manually with SAVE and BGSAVE: the first blocks clients, the second works in a child process.

When saving, Redis forks: the child process gets a copy of memory and writes a temporary file, which replaces the old one when finished. While the child writes, the main process keeps serving clients; changes made after the fork do not enter the snapshot. Copy-on-write saves memory because only modified pages are copied, but memory use still grows.

A snapshot is an ideal format for backups: a single file that never changes once written and can be copied straight from a running server. But a save point is also the boundary of your losses: after a crash, everything since the last snapshot is gone, which can be minutes of data.

AOF

An AOF (append-only file) is a log to which the main process appends every write command, in the same protocol clients use; on startup Redis replays the log and restores the data. It is enabled with a single option and is off by default.

bashredis.conf
appendonly yesappendfilename "appendonly.aof"appenddirname "appendonlydir"

Since Redis 7 the log is made of multiple files: a base file (an RDB or AOF snapshot), incremental files with the commands applied on top of it, and a manifest that lists the files and their order, all in the appenddirname directory.

appendfsync modeWhat is lost in a crashLoad
alwaysnothing: fsync after every batch of writesslow; group commit smooths it out
everysecup to 1 second of writesthe default; fast and reliable
noup to the OS: usually up to 30 secondsthe fastest, guarantees nothing

fsync forces data from the OS buffer to disk. By default Redis appends commands to the file quickly and flushes once a second (everysec). The always mode is slow in practice, although concurrent writes are merged into one fsync; the no mode leaves flushing to the OS kernel.

The log grows with writes, so Redis periodically rewrites it. A fork creates a child process, which builds the minimal set of commands for the current state and writes a new base file, while the main process keeps appending new commands; the manifest is replaced atomically. An automatic rewrite triggers when the log has grown by auto-aof-rewrite-percentage percent over its size after the last rewrite, but by no less than 64 MB (auto-aof-rewrite-min-size).

RDB and AOF together

RDB and AOF work at the same time without conflict: the server does not start a BGSAVE during an AOF rewrite, or the other way round, so the two processes do not compete for the disk. When it starts with AOF enabled, Redis restores data from the log, which is more complete than a snapshot.

The documentation recommends enabling both if your data is comparable in value to data in PostgreSQL: snapshots give fast backups and a fast start, the log gives small losses. If you can afford to lose a few minutes in a crash, RDB alone is enough. The documentation does not recommend AOF alone.

bashredis.conf
appendonly yesappendfsync everysecsave 3600 1 300 100 60 10000

Backups

RDB files can be copied straight from a running server: a finished snapshot never changes, and a new one is written under a temporary name and appears through an atomic rename. Archive snapshots for several days so you can roll back to the state before a data error, and keep a copy off the machine running Redis.

Copy the AOF directory with a caveat: during a rewrite, the archive may come out inconsistent. For the duration of the copy, disable automatic rewrites (CONFIG SET auto-aof-rewrite-percentage 0), check in INFO persistence that aof_rewrite_in_progress is 0, and restore the value afterwards.

Redis 8.10 adds a BACKUP command, which takes a copy without stopping writes and without managing rewrites by hand. BACKUP START writes a fresh snapshot of the database to the backupdirname directory and keeps collecting new commands; BACKUP SEAL freezes the set (a snapshot plus an incremental log with a manifest), after which the files listed by BACKUP LIST can be copied; BACKUP CLEANUP removes what was copied. The restored state reflects the moment of SEAL, not of the snapshot.

bashon the server
# create a backup and wait until it is readyredis-cli BACKUP START# freeze the set: the files from BACKUP LIST can be copiedredis-cli BACKUP SEALredis-cli BACKUP CLEANUP

A corrupted log

A truncated AOF tail happens when the last command was not fully written because of a power failure or a full disk. By default, aof-load-truncated yes lets the server load such a file up to the cut-off and start; it reports the cut-off in the log. If the file cannot be read at all, redis-check-aof repairs it; save a copy before repairing.

bashon the server
redis-check-aof --fix appendonlydir/appendonly.aof.manifest

First run the tool without --fix: it shows the offset of the problem and lets you see what exactly is damaged. With --fix it discards everything from the damaged spot to the end of the file, so damage near the start of the log causes a large loss. Redis does not repair damage in the middle on its own.

A replica and Cluster duplicate data even without a disk; see the “Replication, Sentinel and Cluster” section. Latency during forks and log growth is covered in the “Performance and memory” section.

Section sources

the section is written from these pages

Replication, Sentinel and Cluster

Redis replication is an asynchronous copy of the primary server’s data onto replicas, which serve reads only. Sentinel is a supervisor: when the primary fails, it promotes a replica to primary and tells clients the new address. Cluster splits data across several servers, so it gives you extra write capacity and memory beyond a single node, not just a standby.

Replication: how the primary sends data

A replica is attached with the REPLICAOF host port command or the replicaof line in redis.conf. A replica is read-only by default: writes are rejected, which protects the copy from accidental edits. One primary can have several replicas, and replicas can have replicas of their own: chaining offloads the primary but lengthens the data path.

Replication is asynchronous: the primary does not wait for a replica to acknowledge, so writes are fast, but if the primary fails, the latest commands that have not yet reached the replicas are lost. After a dropped link, the replica reconnects and asks for the missing part of the stream (partial resynchronisation). If the backlog is too small or the replication ID has changed, a full resynchronisation happens: the primary takes an RDB snapshot, sends the whole file, then sends the commands accumulated in the meantime. The pair of replication ID and offset identifies a version of the dataset: a replica promoted after a failover gets a new ID but remembers the old one, so the other replicas catch up with it without a full transfer.

bashin redis-cli
# on the replica server (192.0.2.20)REPLICAOF 192.0.2.10 6379 # on the primary: who is connected and how far behind they areINFO replicationROLE

Minimum replicas and the WAIT command

Two techniques narrow the window for losing a write, but they do not give strong consistency. The pair min-replicas-to-write 1 and min-replicas-max-lag 10 lets the primary accept writes only while at least one replica lags by less than 10 s; if no live replicas are left, writes are rejected. The WAIT 1 0 command blocks until the given number of replicas acknowledge the connection’s previous writes.

Both mechanisms are best effort: a replica confirms that it received the writes, not that it saved them to disk, and an acknowledged write can still be lost in a failover. WAIT returns the number of replicas that responded, so compare it with the number you asked for.

Sentinel: automatic failover

Sentinels are separate processes that watch a primary and its replicas and start a failover when the primary fails: they pick a replica, promote it to primary and reconfigure the others. Clients ask a Sentinel for the current primary’s address with SENTINEL get-master-addr-by-name and receive the new address after a switch.

You need at least three Sentinels on independent machines. A failure is declared by a quorum: that many Sentinels must consider the primary unreachable (subjectively down, sdown, becomes objectively down, odown). The failover itself additionally requires votes from a majority of all Sentinels, so if a Sentinel is cut off in the minority, no failover starts. Port 26379 must be open between Sentinels.

inisentinel.conf
sentinel monitor mymaster 192.0.2.10 6379 2sentinel down-after-milliseconds mymaster 10000sentinel failover-timeout mymaster 180000sentinel parallel-syncs mymaster 1

Replicas and other Sentinels are discovered automatically; you do not need to list them. Sentinel rewrites its configuration file on every state change, so the file must be writable. You can follow a failover in the log through the +sdown, +odown and +switch-master events, and check node state with the SENTINEL master and SENTINEL replicas commands.

Cluster: data across several servers

Redis Cluster splits the keyspace into 16384 hash slots; a key’s slot is the CRC16 of the key modulo 16384. Each primary holds its own range of slots and one or more replicas: when a primary fails, one of its replicas is elected as the new primary and the slots stay covered. Slots move between nodes without downtime, which is how you grow and shrink a cluster.

The slot is the CRC16 of the key modulo 16384; the client remembers the slot map.

A client can send a command to any node. If another node owns the slot, that node replies with a MOVED slot address error, a permanent redirection: you should refresh the slot map. While a slot is being migrated, the node replies with ASK, meaning forward just this one request. Smart clients cache the slot map and go straight to the right node, avoiding redirections.

A multi-key command works only if all the keys are in the same slot. A hash tag is the part of a key in curly braces: {user:42}:profile and {user:42}:cart are hashed by the tag and land in the same slot, while MSET with keys from different slots fails with a CROSSSLOT error. During slot migration a multi-key command may reply TRYAGAIN; retry it later.

bashon a host with redis-cli
redis-cli --cluster create 192.0.2.10:7000 192.0.2.10:7001 \  192.0.2.10:7002 192.0.2.20:7000 192.0.2.20:7001 \  192.0.2.20:7002 --cluster-replicas 1 # check after creation and after migrationsredis-cli --cluster check 192.0.2.10:7000

Choosing between a replica, Sentinel and Cluster

GoalSingle replicaSentinelCluster
Data backupyes, manualyes, automatic failoveryes, for every primary
Reads from replicasyesyesyes, for their own slots
More memory or write capacitynonoyes, add primaries
Quorum and electionsnoyes, at least 3 Sentinelsyes, primaries vote
Multi-key commandsanyanyone slot only

Choose a single replica when you need a standby and reads, and a person performs the failover. Choose Sentinel when write continuity matters and the data fits on one server. Choose Cluster when there is more data or write load than one server can handle and the application can live with the restriction on multi-key commands.

In all three setups replication is asynchronous, so a window for losing the latest write remains; WAIT and min-replicas-to-write narrow it. Cluster also stops accepting writes if slots are uncovered or a majority of primaries is unreachable, so data consistency takes priority over availability.

More detail: monitoring and tuning

INFO replication shows the replication state: role, connected replicas and their lag, replication ID and offset. ROLE gives the same information in a form convenient for programs. A replica’s lag shows up as the difference between the primary’s and the replica’s offsets.

A full synchronisation puts load on the primary: it takes an RDB snapshot and keeps a command buffer. Diskless mode (repl-diskless-sync yes) sends the snapshot straight over the network without writing it to disk, and repl-diskless-sync-delay waits for several replicas to arrive so that one snapshot serves them all. After a clean restart, a replica catches up partially if it keeps its RDB file and was stopped with SHUTDOWN; after a restart on AOF, partial resynchronisation is impossible.

Section sources

the section is written from these pages

Performance and memory

Redis is mostly single-threaded: one slow command or a pause in a system call (fork, swapping, a log write) delays all clients at once. Look for the cause in SLOWLOG and LATENCY, check memory with INFO memory, and measure throughput with redis-benchmark.

A single-threaded server

An ordinary command runs in a fraction of a millisecond, but the server handles one at a time: a heavy request queues up all the others. There are two sources: commands that work on a whole value or the whole database, and pauses outside Redis (the network, the kernel scheduler, the hypervisor, the disk). A command’s complexity is listed in its documentation; check an unfamiliar one before you use it.

Baseline latency

First measure the background noise that every process on the machine lives with. redis-cli --latency sends PING 100 times a second and prints the minimum, maximum and average in milliseconds. --latency-history starts a new session every 15 seconds so that spikes do not get lost in the overall statistics. The --intrinsic-latency mode measures not Redis but the environment: the kernel scheduler and the hypervisor. Run it on the server that hosts Redis: Redis cannot do better than that baseline, and in a virtual environment the baseline often reaches tens of milliseconds.

bashon the host
# the server’s current response latencyredis-cli --latency# the limit of the environment itself, without connecting to a serverredis-cli --intrinsic-latency 100
textsample output of both commands
min: 0, max: 1, avg: 0.19 (427 samples)Max latency so far: 115 microseconds.

Slow commands

The classic culprit is KEYS in production: it walks the whole database and blocks everyone; use SCAN instead. SORT and SUNION, SMEMBERS on a large set and HGETALL on a huge hash are similar, as they all work on every element of the value. Read large collections in batches with SSCAN, HSCAN and ZSCAN. The slow log stores everything that ran longer than the slowlog-log-slower-than threshold, which is in microseconds; the log length is capped by slowlog-max-len.

bashin redis-cli
# log everything slower than 10 msCONFIG SET slowlog-log-slower-than 10000# the last five slow commandsSLOWLOG GET 5

Latency monitor

The server times latency-sensitive sections of code and records spikes longer than a threshold. You can enable the monitor without a restart: CONFIG SET latency-monitor-threshold 100 sets a threshold of 100 ms. The events are command and fast-command for commands, fork, expire-cycle and AOF writes (aof-write, aof-fsync-always). LATENCY LATEST shows the latest spikes for each event, and LATENCY DOCTOR turns them into a human-readable report with advice.

bashin redis-cli
CONFIG SET latency-monitor-threshold 100LATENCY LATESTLATENCY DOCTOR

Pipelining

Without pipelining, every call waits for its reply: with a 250 ms round trip, a server capable of 100,000 operations per second handles 4. Pipelining sends a batch of commands without waiting for replies and reads the replies in one go, so the whole batch costs a single network round trip. Speed grows almost linearly with batch length, up to about tenfold. In the documentation’s loopback example, 10,000 PING commands took 0.25 s against 1.19 s without pipelining, about a fivefold gain. The aggregate commands MGET and MSET have a similar effect.

bashon the host
# a million SET and GET operations, pipelined by 16, quiet outputredis-benchmark -n 1000000 -t set,get -P 16 -q
textsample output
SET: 1536098.25 requests per second, p50=0.479 msecGET: 1811594.25 requests per second, p50=0.391 msec

Fork, transparent huge pages and swapping

An RDB snapshot and an AOF rewrite both start with a fork. The main thread copies the page table, which is 48 MiB for a 24 GiB instance. The pause shows up in INFO as latest_fork_usec. After a fork, transparent huge pages (THP) lead to copying almost all of the process’s memory, so disable them on a Redis server. Check swapping through /proc: Redis pages on disk are a sure cause of spikes. Writing the AOF can also cause pauses; appendfsync everysec is a sensible compromise between durability and latency.

bashon the server
# disable transparent huge pagessudo sh -c 'echo never > /sys/kernel/mm/transparent_hugepage/enabled'# the server’s process IDredis-cli info server | grep process_id# the process’s pages that were swapped out (replace the PID with yours)cat /proc/5454/smaps | grep 'Swap:'# the si and so columns show swap trafficvmstat 1

Where the memory goes

INFO memory sums up the picture: used_memory is how much Redis itself uses, used_memory_rss is how much the operating system sees, mem_fragmentation_ratio is their ratio, and used_memory_peak is the historical maximum. When RSS is much larger than used memory, memory is fragmented; when used memory is larger than RSS, part of the data has been swapped out. MEMORY USAGE reports the memory a key takes, redis-cli --memkeys finds the keys in the whole database that use the most memory, and --bigkeys finds the keys with the most elements for each type. MEMORY STATS gives a breakdown by component, and MEMORY DOCTOR reports problems.

bashin redis-cli
INFO memoryMEMORY USAGE user:42:profile

Freed memory is not returned to the system immediately: the allocator keeps pages in reserve. Size the machine for the peak used_memory_peak, not the current usage. Active defragmentation compacts the holes: set activedefrag yes and watch it work through active_defrag_running in INFO. MEMORY PURGE asks the allocator to return dirty pages to the system; it works with jemalloc and is a no-op with other allocators. For memory limits and eviction, see the section “Caching and eviction”.

Compact encodings

Redis stores small values of aggregate types compactly: listpack for hashes, lists, sets and sorted sets, and intset for sets of integers. This uses up to ten times less memory, five times less on average. The limits are set in redis.conf; exceeding them converts the value to the regular encoding, and OBJECT ENCODING shows the current one. Instead of a dozen keys per object, create one hash: a small hash lives in a listpack and uses several times less memory.

bashredis.conf
hash-max-listpack-entries 512hash-max-listpack-value 64zset-max-listpack-entries 128zset-max-listpack-value 64

In Redis 8.10, keys with the same field schema can use compact hashes. Keys with the same set of fields store the field names once, and each key keeps only its values: one hash per user with the fields name, email and age is noticeably smaller than ten separate string keys. Load such keys with the HIMPORT command, which stores the key in the compact encoding right away; without changing code, enable automatic conversion on write with CONFIG SET hash-min-template-entries 4. The conversion is one-way: a key keeps its encoding for the rest of its life. The schema is a poor fit if every key has its own fields or the set of fields keeps changing.

bashin redis-cli
HIMPORT PREPARE user name email ageHIMPORT SET user:1 user Alice alice@example.com 34HGETALL user:1

How to measure

redis-benchmark keeps 50 parallel connections (-c) and sends the given number of requests (-n); a quick run is redis-benchmark -q -n 100000. -t set,get selects the commands, -r 100000 spreads operations over random keys in the range 0 to 99,999, and -P 16 turns on pipelining. Without -P the result is understated: each connection waits once per request, so the figures are closer to the worst case.

Compare like with like: the same version, the same pipelining and number of connections, the same machine. Over a network, the link becomes the bottleneck before the server does: 100,000 writes per second of 4 KB each take 3.2 Gbit/s. If the server is not loaded but the figures are low, the bottleneck is in the client. On the same host, a Unix socket gives about 50% higher throughput than TCP loopback.

bashon the host
# a million writes over random keys out of 100,000redis-benchmark -t set -r 100000 -n 1000000
textsample output
====== SET ======  1000000 requests completed in 13.86 seconds  50 parallel clients...99.98% <= 2 milliseconds100.00% <= 3 milliseconds72144.87 requests per second

Summary by symptom

SymptomWhere to lookWhat to do
Latency spikes for all clientsredis-cli --latency next to --intrinsic-latencyCompare with the environment’s baseline; move off noisy virtualisation
Pauses when writing to diskLATENCY LATEST, INFO: latest_fork_usecDisable THP; run the save child process on a different core
Individual requests are slowSLOWLOG GETReplace the O(N) command with the SCAN family or batches
Memory is used, but there is less dataINFO memory: mem_fragmentation_ratioMEMORY PURGE, enable activedefrag
A few keys eat gigabytesredis-cli --memkeysSplit the keys, use compact encodings
Pauses when writing to the AOFLATENCY HISTORY aof-fsync-alwaysappendfsync everysec, a free disk
Throughput below the targetredis-benchmark with -PPipelining in the client, MGET and MSET

Section sources

the section is written from these pages

Security

Redis does not encrypt connections and by default trusts anyone who reaches its port, so it is designed for a trusted network. The main threat is port 6379 exposed to the internet without a password: a single FLUSHALL deletes the whole database.

Network and protected mode

The first barrier is the network. The port should be reachable only by the applications that use this database. The host firewall blocks everything else; see the “Linux server hardening” reference, section “Firewall”. Redis itself restricts access with two directives in redis.conf. bind sets the addresses on which the server listens: specify an internal address or 127.0.0.1.

The second directive is protected-mode. It has been enabled by default since version 3.2. If the default user has no password, Redis accepts connections only from loopback addresses and through a Unix socket. Everyone else gets an error with a hint on how to configure the server. The mode protects against a forgotten password, but you can lose the protection: as soon as you set a password or disable protected-mode by hand, the port is open to everyone again.

A typical bad and good pair for the config:

confdon’t do this
bind 0.0.0.0protected-mode no# no password
confdo this instead
bind 192.0.2.10protected-mode yesrequirepass change-me

Users and permissions: ACL

Since Redis 6, access is managed by ACL (Access Control List): each user has their own passwords, allowed commands and key patterns. Initially there is one user, default, with no password and permission to do everything (user default on nopass ~* &* +@all). The requirepass directive from older versions sets the default user’s password.

Create users with the ACL SETUSER command or with lines in redis.conf. Rules are read left to right, so order matters. Command categories are written with a sign: +@read allows the whole category, -@dangerous removes it. A key pattern with ~ restricts access, for example ~app:*.

RuleWhat it does
on / offenable a user or forbid them to log in
>password / <passwordadd or remove a user’s password
+@read / -@dangerousallow or forbid a command category
-FLUSHALLforbid a single command
~app:*allow keys matching a pattern
&news:*allow Pub/Sub channels matching a pattern
nopasswork without a password (for service tasks only)
resetreturn the user to an empty state

Here is a restricted application user: it can only read and write its own keys, with no settings and no mass deletions. Rules are processed left to right, and a trailing -@dangerous removes the dangerous commands from the categories added before it:

bashredis-cli
ACL SETUSER webapp on >change-me \  ~app:* +@string +@list -@dangerous
consolechecking webapp’s permissions
AUTH webapp change-meSET app:counter 1GET app:counterCONFIG GET maxmemory

The first three calls succeed; the fourth returns NOPERM User webapp has no permissions to run the 'config|get' command. SET app:counter 1 works because webapp has the @string category and the key matches the ~app:* pattern. ACL WHOAMI shows your own identity, ACL LIST shows all users, and ACL GETUSER shows the details of one.

Changes made with ACL SETUSER live in memory and disappear on restart. To keep them, define the users in redis.conf or move them to a separate file and include it with the aclfile /etc/redis/users.acl directive. The format is the same in both places, but you cannot use both at once. With a file, you get the ACL LOAD (reload after editing) and ACL SAVE (write the current state) pair; CONFIG REWRITE does not touch the ACL file.

Dangerous commands

FLUSHALL and FLUSHDB wipe the database, KEYS and DEBUG stall the server on large datasets, CONFIG SET dir changes the directory it writes to, and SHUTDOWN stops the process. Some of these are already blocked by the defaults in the current branch: enable-debug-command no forbids DEBUG for everyone, and protected directives such as dir cannot be changed on the fly. The other commands are still available to everyone, so restrict them through ACL. Do not rename them: the rename-command directive is marked deprecated, and the documentation recommends ACL instead. Forbidding through ACL looks like -@dangerous for the whole category or -FLUSHALL for a single command.

Encryption: TLS

By default the port sends data in plain text, including the password in AUTH. For sensitive data, enable TLS; the protocol itself and certificates are covered in the “TLS and PKI” reference, section “X.509 certificates”. Redis is configured with three directives: tls-cert-file, tls-key-file and tls-ca-cert-file.

confredis.conf: TLS only
port 0tls-port 6379tls-cert-file /etc/redis/tls/redis.crttls-key-file /etc/redis/tls/redis.keytls-ca-cert-file /etc/redis/tls/ca.crt

port 0 closes the unencrypted port; otherwise it stays open alongside the TLS one. By default Redis also requires a certificate from the client, which is mutual authentication (mTLS); to allow clients without a certificate, set tls-auth-clients no.

On a replica, enable tls-replication yes, and in a cluster tls-cluster yes: these directives move replication and node-to-node traffic to TLS. Each node then presents a certificate signed by the same CA to its peers, so the servers verify each other without passwords. tls-expected-peer-name checks the name of a specific node in the certificate.

What to do next

  1. enable protected-mode and bind the server to the right addresses with bind
  2. set a password for default or create users with minimal permissions
  3. forbid @dangerous for everyone except administrators
  4. enable TLS for external traffic
  5. follow patch releases, since security fixes ship in them; for how to choose and adopt versions, see the section “Versions and what’s new”

Section sources

the section is written from these pages

Common errors and diagnostics

Diagnosing Redis starts with three checks: redis-cli ping tells you whether the server is alive, INFO shows memory, persistence and replication in separate sections, and the server log explains startup failures and background task failures. Next come the common errors and a table of symptoms.

Order of checks

  1. redis-cli ping: the server replies PONG if it accepts commands;
  2. INFO server: version, mode (standalone, sentinel, cluster), configuration file;
  3. INFO memory, INFO persistence, INFO replication: memory, persistence, replication;
  4. SLOWLOG GET 10 and LATENCY DOCTOR: what delayed the server;
  5. the server log: startup failures, persistence and replication errors.

The log path is set by the logfile directive in redis.conf: an empty string sends the log to stdout, and under systemd it ends up in journalctl -u redis-server; on a packaged Ubuntu or Debian installation the log is written to /var/log/redis/redis-server.log by default. CONFIG SET changes parameters on the fly and CONFIG GET shows them; see the section “Installation and first run” for details.

bashon the server
redis-cli INFO persistence | grep rdb_last_bgsave_statusjournalctl -u redis-server -n 20

WRONGTYPE Operation against a key holding the wrong kind of value

Cause: the key holds a value of one type, and the command is meant for another. The type is set on write and changes only through a command that replaces the whole value, such as SET. A key with a value of a different type will not work with commands for another type: delete it with DEL and start over. TYPE shows a key’s type; for how the types work, see the section “Data types and keys”.

bashin redis-cli
TYPE user:42DEL user:42HSET user:42 name Anna

NOPERM User default has no permissions to run the 'set' command

Cause: the ACL user has no permission for the command or for a key in its arguments; in the second case the error reads “NOPERM No permissions to access a key”. You may be connected as the wrong user: ACL WHOAMI shows your login. ACL GETUSER lists your permissions; for how to grant them, see the section “Security”.

bashin redis-cli
ACL WHOAMIACL GETUSER webapp

MOVED 3999 127.0.0.1:6381

Cause: in a cluster, another node owns the key’s slot and it redirects you. A client without cluster support has to follow this reply manually; smart clients cache the slot map and refresh a stale map from MOVED replies on their own. CLUSTER KEYSLOT computes a key’s slot, and redis-cli --cluster check checks the cluster’s state. For how a cluster works, see the section “Replication, Sentinel and Cluster”.

bashin redis-cli and on the host
CLUSTER KEYSLOT user:42redis-cli --cluster check 192.0.2.10:7000

ERR EXEC without MULTI

Cause: EXEC was called outside a transaction. This happens when a client opens a new connection after a drop: the command queue lives in the connection, so in the new connection you must enter the commands again, from MULTI to EXEC. Errors inside a transaction itself are covered in the section “Transactions, Lua and functions”.

A client outside cannot connect

The cause is most often bind or protected mode. By default Redis listens only on loopback: the directive is bind 127.0.0.1 -::1. If you list an external address in bind but leave protected mode on, a server with no password for default answers only local clients, and external ones are refused with a hint to configure the server. Check that the server listens on the right address, and set a password or your own ACL users.

bashon the server host
# what the server actually listens onss -ltnp 'sport = :6379'redis-cli -h 192.0.2.10 CONFIG GET bindredis-cli -h 192.0.2.10 CONFIG GET protected-mode

Writes are rejected: memory is full

Cause: the maxmemory limit has been reached and the noeviction policy removes nothing. Write commands get an OOM (out of memory) error while reads continue, which is by design when Redis stores data rather than caching it. For a cache, set an eviction policy; for how to choose one, see the section “Caching and eviction”. INFO memory shows memory use.

bashin redis-cli
redis-cli INFO memory | grep -E 'used_memory_human|maxmemory_human'redis-cli CONFIG GET maxmemory-policy

Writes stopped after a persistence error

Cause: the RDB snapshot failed (out of disk space, no permissions on the directory, fork did not work), and the stop-writes-on-bgsave-error safeguard stopped accepting writes so that you do not silently lose persistence. The client sees an error with a hint to check the log. Fix the cause: the snapshot will be retried on schedule and writes resume by themselves; disable the safeguard only if you have working persistence monitoring. INFO persistence shows the result of the last BGSAVE.

bashon the server
df -h /var/lib/redisredis-cli INFO persistence | grep rdb_last_bgsave_status

The replica answers reads only

Cause: by default a replica does not accept writes (replica-read-only yes), which protects the copy from accidental edits. In a cluster, a write is additionally redirected to the node that owns the key’s slot, and the replica sends it there; the READONLY command allows reads from a replica for the current connection only, but the data may lag. Do not write to a replica: an edit to the copy diverges from the primary. INFO replication shows roles and lag.

bashin redis-cli
redis-cli INFO replication | grep role

Symptoms worth double-checking

SymptomCauseWhat to do
memory grows, RSS is larger than the datafragmentation, or memory used by client and replica buffersINFO memory: mem_fragmentation_ratio, mem_clients_normal, mem_clients_slaves
latency comes in spikes, the average is normala slow command, a fork during a save, swappingLATENCY DOCTOR and the section “Performance and memory”
replicas often resynchronise fullythe replication backlog is too small for the write trafficincrease repl-backlog-size, check the links
startup with a large AOF takes longthe server replays the whole logcheck aof-use-rdb-preamble, wait for loading to finish

High latency most often comes from outside Redis: a slow command blocks everyone, a fork during BGSAVE pauses the thread, and swapping in a virtual machine causes background spikes. First measure the baseline with redis-cli --intrinsic-latency 100 on the server itself, then look for the culprit in LATENCY DOCTOR; the method is covered in the section “Performance and memory”.

bashon the server host
redis-cli --intrinsic-latency 100redis-cli LATENCY DOCTOR

Frequent full resynchronisations of replicas are fixed with the backlog: a replica that was disconnected for the duration of an outage catches up with the primary partially, but only while its offset is still inside the replication backlog. If the backlog is too small, every pause longer than the threshold turns into a full data transfer. A slow start with a large AOF is the price of a complete log: with the RDB preamble (aof-use-rdb-preamble yes), Redis reads the dataset from the snapshot and replays only the tail.

Section sources

the section is written from these pages

Versions and what’s new

This reference covers Redis Open Source 8.10, whose latest release is 8.10.3 of 26 October 2026. Under the release policy, a major version is planned once a year and a minor version six months after it. Only the latest stable branch is fully supported; two more receive fixes for critical bugs and vulnerabilities only.

Redis 8 is the current major branch; its minor versions 8.2–8.10 have in practice come out more often than every six months. A patch release is almost always compatible with the previous one; a minor release may add commands and change the persistence format or the replication protocol.

BranchStatusFirst releaseLatest release
8.10current8.10.0 — July 20268.10.3 — 26 October 2026
8.8maintenance8.8.0 — May 20268.8.4 — 26 October 2026
7.4previous major, maintenance7.4.0 — July 20247.4.12 — 26 October 2026
8.12release candidates only8.12-rc1 — 29 October 20268.12-rc2 — 1 November 2026

By policy, the previous minor branch (8.8) and the previous major branch (7.4) are maintained with critical fixes only; in practice, patches for 8.2, 8.4, 8.6 and 7.2 were also released on 26 October. Valkey is a separate fork of Redis 7.2 with its own releases (valkey.io); this reference does not cover its versions.

What changed in 8.10

The main changes in 8.10.0 (July 2026) compared with 8.8:

  • Compact hashes, a new encoding: when fields share the same schema, their names are stored once, which saves memory; HIMPORT is added for bulk loading. See the section “Data types and keys”.
  • LMOVEM and BLMOVEM move several elements between lists in a single call; the blocking form waits for elements. See the section “Data types and keys”.
  • SUNIONCARD and SDIFFCARD return the cardinality of the union and difference of sets without building them. See the section “Data types and keys”.
  • BACKUP creates a node backup based on the multi-part AOF. See the section “Persistence: RDB and AOF”.
  • XREAD and XREADGROUP gained the MAXCOUNT and MAXSIZE arguments, which limit the number and size of entries in a reply. See the section “Pub/Sub and streams”.
  • Servers authenticate each other with TLS certificates, for both replication and the cluster bus. See the section “Security”.
  • Search and time series: FT.ALIASLIST, blocking TS.READ, multi-series queries with TS.NRANGE, and JSONPath extensions.

Unsupported and removed features

The release notes for 8.10.0–8.10.3 do not declare any command deprecated or removed.

Security updates

Both supported branches received their security fixes on the same date: 8.10.3 and 8.8.4 on 26 October 2026. Over the last 12 months, the following were fixed in the 8.10 branch:

Fixed inWhat was fixed
8.10.1CVE-2026-62356: out-of-bounds write when loading a Count-Min sketch from RDB; a malicious RDB file with a slot ID outside the valid range could cause memory corruption and remote code execution; authentication bypass with a client TLS certificate through a null byte in the CN
8.10.2commands in a transaction could access keys whose ACL permissions had been revoked; the cluster bus without tls-cluster is not authenticated — mitigation: a warning at startup and the cluster-bus-port-protected-mode setting
8.10.3heap overflow when forwarding a PUBLISH or SPUBLISH message larger than 4 GB over the cluster bus

How to upgrade

Upgrading a standalone server comes down to replacing the package. Moving between patch releases is almost always safe, but take a backup before any upgrade.

  1. Take a data snapshot: redis-cli SAVE creates or updates the RDB file (dump.rdb); with AOF, back up the appendonly.aof.* files in the appendonlydir directory.
  2. Copy the data directory to a safe place; redis-cli CONFIG GET dir shows its path.
  3. Stop the running server.
  4. Install Redis 8 the same way as before (see the section “Installation and first run”).
  5. Start the server and check that your data is available.
bashon the host
redis-cli SAVEredis-cli CONFIG GET dircp -r /var/lib/redis/ /backup/redis-8.10/
bashversion check
redis-cli INFO server | grep redis_version

In a cluster, upgrade the nodes one at a time, starting with the replicas: snapshot, copy, stop, install 8.10, start. Until all primaries are upgraded, the search module responds with an error or the message Waiting for all nodes to connect. Check the cluster state with redis-cli --cluster check.

Section sources

the section is written from these pages

End of the reference

What changed

revision history · 3 entries

Every edit is saved as a revision: a snapshot of the reference, the reason and a summary of changes. The published version changes only after the same checks as at creation.

  1. Manual edit

    reason: manual edit
  2. Manual edit

    reason: manual edit
  3. Reference updated

Weekly check

How the reference is checked

Once a week — and right after news of a release or a vulnerability — the reference is checked in three steps.

  1. 1. Freshness

    Sections are compared with the release notes and changelogs from the official sources and with the topic’s news.

  2. 2. Errors

    Every section is read again: wrong facts, outdated APIs and flags, broken examples.

  3. 3. Links — by an HTTP request

    Every source link must respond. A broken link is a reason to recheck the section.

No findings — only the date changes. Findings — only the affected sections are rewritten, and they appear in “What changed”. A new version replaces the published one only after passing the same checks as at creation.

Statuses

Verified
no findings
Updated
sections rewritten, edits are listed
Rechecking
while the check runs, the previous version stays open
Needs review
disputed points: the verified version is shown, editors review

Last check

10 Nov · Check · updated · no findings

Found an error in the reference?

On the topic

tracks, news and other references
The whole “Redis” topic
13 sections
Another reference · Backend

Python

Verified 31 Oct
All references · 61