Erste Schritte
Zum Redis-Server verbinden
redis-cli ist der Standard-Befehlszeilen-Client. Der Standard verbindet zu 127.0.0.1:6379. -h für Host, -p für Port, -a für Passwort (oder die Umgebungsvariable REDISCLI_AUTH setzen, um Geheimnisse in der Shell-History nicht preiszugeben). TLS braucht --tls plus cert/key. Das URL-Schema redis:// wird ab Redis 6+ unterstützt, rediss:// für TLS.
# connect to local server (default port 6379)
redis-cli
# connect to a remote host with custom port
redis-cli -h redis.example.com -p 6380
# connect with authentication
redis-cli -a "yourpassword"
redis-cli -h host -p 6379 -a "yourpassword"
# connect over TLS
redis-cli --tls --cert client.crt --key client.key -h host -p 6379
# connect using a URL (Redis 6+)
redis-cli redis://user:password@host:6379/0
redis-cli rediss://user:password@host:6379/0 # TLSVerbindungsoptionen & Modus
redis-cli unterstützt interaktiven und Einmal-Modus. Ein als Argument übergebener Befehl läuft und beendet sich. Pipe-Modus liest RESP-/Textbefehle von stdin — super fürs Scripting und Bulk-Loads. -n wählt die logische Datenbank. --stat und --latency sind eingebaute Monitoring-Helfer. --raw liefert Werte ohne Typ-Präfixe — nützlich zum Piping.
# select a specific database index (0-15)
redis-cli -n 1 # use database 1
# run a single command and exit (non-interactive)
redis-cli GET mykey
redis-cli -h host PING
# pass command with arguments
redis-cli SET counter 100
redis-cli INCR counter
# read commands from stdin (pipe mode)
echo "SET k1 v1" | redis-cli
cat commands.txt | redis-cli
# repeat a command every second (watch mode)
redis-cli --stat
redis-cli --latency
# pretty-print JSON output (Redis 6+)
redis-cli --raw GET user:jsonPING & Konnektivitätstest
PING ist der einfachste Health-Check — ein funktionierendes Redis liefert PONG. --latency misst kontinuierlich die Round-Trip-Zeit (praktisch, um Netzwerkprobleme zu diagnostizieren). --latency-dist zeigt ein Histogramm. --latency-history loggt rollierende Stats. Damit die Verbindungsqualität als Basislinie festhalten, bevor du die Performance tust.
# basic connectivity test
redis-cli ping
# PONG
# ping with a message (echoed back)
redis-cli PING "hello"
# "hello"
# test auth + connection in one shot
redis-cli -a password PING
# check round-trip latency (continuous)
redis-cli --latency
# output: min: 0, max: 1, avg: 0.27 (3421 samples)
# latency histogram
redis-cli --latency-dist
# latency history (rolling, every 15s by default)
redis-cli --latency-history -i 1Tipps zum interaktiven Modus
Der interaktive Modus ist eine REPL für Redis-Befehle. HELP <command> oder HELP @<group> zeigt eingebaute Doku (kein Internet nötig). CONNECT wechselt in-session den Server. CLEAR leert den Bildschirm. Die CLI erkennt mehrzeilige Eingabe für quotierte Strings automatisch. ':' voranstellen, um CLI-spezifische Befehle (wie :raw) statt Redis-Befehlen auszuführen.
# start interactive mode
redis-cli
# inside the CLI:
127.0.0.1:6379> HELP SET # command help
127.0.0.1:6379> HELP @string # help for a command group
127.0.0.1:6379> SCAN 0 # any Redis command
# clear the screen
127.0.0.1:6379> CLEAR
# connect to a different server without restarting
127.0.0.1:6379> CONNECT host 6380
# exit
127.0.0.1:6379> EXIT
127.0.0.1:6379> QUIT
# multi-line input: end with a backslash
127.0.0.1:6379> SET mykey "this is \
a multi-line value"
# toggle raw output mode
127.0.0.1:6379> :rawDatenbankwahl & Grundlagen
Redis-Datenbanken sind logische Namensräume (0-15), die sich denselben Speicher teilen — keine isolierten Schemas. Die meisten Apps nutzen nur db 0. FLUSHDB leert die aktuelle db; FLUSHALL leert alles (vorsichtig!). Mehrere Datenbanken sind unüblich; separate Instanzen oder Schlüsselpräfixe bevorzugen, da sie sich einen Thread teilen.
# Redis has 16 logical databases (0-15) by default
SELECT 0 # switch to database 0
SELECT 15 # switch to database 15
# move a key to another database
MOVE mykey 1
# flush the current database (DESTRUCTIVE)
FLUSHDB
# flush ALL databases (VERY DESTRUCTIVE)
FLUSHALL
# get the number of keys in the current db
DBSIZE
# swap two databases (Redis 4.0+)
SWAPDB 0 1Hilfe & Befehlsentdeckung
COMMAND introspektiert die Befehlstabelle des Servers — nützlich, um Fähigkeiten und Arity zu entdecken. COMMAND DOCS (7.0+) liefert strukturierte Dokumentation. Der HELP-Befehl der CLI zeigt Offline-Doku, gruppiert nach Kategorie (@string, @hash, @server usw.). 'redis-cli --help' ausführen für alle CLI-Flags und -Optionen.
# list all commands (huge output)
COMMAND
# get details of a specific command
COMMAND INFO GET
COMMAND INFO SET HSET LPUSH
# structured documentation (Redis 7+)
COMMAND DOCS SET
COMMAND DOCS @string
# count available commands
COMMAND COUNT
# CLI help
redis-cli --help
redis-cli --version
# inside interactive mode
HELP
HELP @server
HELP @string
HELP @hash
HELP GETSETStrings
Einfaches SET & GET
SET/GET sind die grundlegenden String-Operationen. NX = setzen, falls nicht vorhanden (genutzt für Locks); XX = setzen, falls vorhanden. EX/PX/EXAT/PXAT setzen den Ablauf atomar (keine Race zwischen SET und EXPIRE). GETSET liefert den vorherigen Wert, während er einen neuen setzt. Strings sind binärsicher bis 512 MB.
# set and get a key
SET mykey "Hello"
GET mykey # "Hello"
# set only if not exists (NX) or only if exists (XX)
SET mykey "new" NX # set only if key does NOT exist
SET mykey "new" XX # set only if key DOES exist
# set with expiration (seconds / milliseconds)
SET token "abc" EX 3600 # expires in 3600s
SET token "abc" PX 60000 # expires in 60000ms
# set with expiration at a Unix timestamp
SET token "abc" EXAT 1700000000
# get and set atomically (returns old value)
GETSET counter 0 # returns old value, sets new
# delete a key
DEL mykeyNumerische Zähler (INCR/DECR)
INCR/DECR sind atomar — sicher für gleichzeitigen Zugriff ohne Locks. Das macht Redis ideal für Zähler, Rate Limiting (INCR + EXPIRE) und das Erzeugen von Sequenz-IDs. INCRBYFLOAT unterstützt Dezimalen, nutzt aber double-Präzision (Rundung beachten). Ist der Wert keine Ganzzahl, liefert INCR einen Fehler.
# increment a numeric string atomically
SET counter 100
INCR counter # 101
INCRBY counter 10 # 111
# decrement
DECR counter # 110
DECRBY counter 5 # 105
# floating point increment
SET price "10.50"
INCRBYFLOAT price 0.25 # "10.75"
INCRBYFLOAT price -1.00 # "9.75"
# all increment ops are atomic and concurrency-safe
# use for: counters, rate limiting, sequence IDs, stats
# INCR on a non-integer value returns an error
SET mystr "hello"
INCR mystr # ERROR: value is not an integerAPPEND & String-Operationen
APPEND verlängert einen String (legt ihn an, falls er fehlt). STRLEN meldet die Länge. GETRANGE/SETRANGE arbeiten auf Teilstrings (binärsicher). GETDEL (6.2+) liefert atomar zurück und löscht — nützlich für Einmal-Lese-Muster. GETEX liefert atomar den Wert und setzt eine TTL — praktisch, um den Session-Ablauf beim Lesen aufzufrischen.
# append to a string value
SET msg "Hello"
APPEND msg " World" # "Hello World"
# get string length
STRLEN msg # 11
# get substring
GETRANGE msg 0 4 # "Hello"
GETRANGE msg 6 -1 # "World"
# overwrite a substring (grows if needed)
SETRANGE msg 6 "Redis" # "Hello Redis"
# get and delete atomically
GETDEL mykey # returns value AND deletes key
# get and set expiration atomically (6.2+)
GETEX mykey EX 3600 # returns value, sets TTL
# append only if key exists
APPEND existing_key "more"MSET & MGET (Batch-Operationen)
MSET/MGET bündeln Operationen in einen Round-Trip — essenziell für die Performance (Redis ist single-threaded, der Overhead pro Befehl zählt also). MSETNX ist atomar: entweder alle Schlüssel werden gesetzt oder keiner. Bei vielen kleinen Key-Value-Paaren überlegen, sie in einen Hash (HSET) zu gruppieren, für bessere Speichereffizienz via listpack-Kodierung.
# set multiple keys at once (atomic)
MSET k1 "v1" k2 "v2" k3 "v3"
# get multiple keys at once
MGET k1 k2 k3 # 1) "v1" 2) "v2" 3) "v3"
# set multiple only if ALL keys are new
MSETNX k1 "v1" k4 "v4" # 1 if all set, 0 if any existed
# MSET/MGET reduce round-trips — much faster than
# separate SET/GET calls in a loop
# get the length of a string value
STRLEN k1 # 2
# set multiple fields of different keys is not possible;
# for per-field updates use hashes (HSET)
# pipeline alternative in CLI:
printf '%s\n' "SET k1 v1" "SET k2 v2" "GET k1" | redis-cli --pipe-modeBitmaps (stringbasiert)
Bitmaps speichern boolesche Flags für bis zu 4 Mrd. Nutzer in ~512 MB — extrem platzsparend. BITOP AND/OR/XOR/NOT kombiniert Bitmaps (z. B. Nutzer, die an mehreren Tagen aktiv waren). BITCOUNT zählt aktive Nutzer. BITFIELD packt mehrere kleine Zähler in einen String. Position = Nutzer-ID. Anwendungsfälle: tägliche aktive Nutzer, Feature-Flags.
# bitmaps are strings operated on at the bit level
# great for boolean flags on a large user base
# set bit at position (0 or 1)
SETBIT user:1:active 7 1 # user 1 active
GETBIT user:1:active 7 # 1
# count set bits
BITCOUNT user:1:active # total bits set to 1
# bitwise operations between strings
SETBIT users:d1 5 1
SETBIT users:d2 5 1
BITOP AND active-both users:d1 users:d2
BITCOUNT active-both # users active on both days
BITOP OR active-either users:d1 users:d2
BITOP XOR diff users:d1 users:d2
# find the first set bit
BITPOS user:1:active 1 # position of first 1-bit
# bitfield: multiple counters in one string
BITFIELD mycnt SET u8 0 100
BITFIELD mycnt INCRBY u8 0 10String-Ablauf & TTL
TTL liefert -2 für nicht existierende Schlüssel und -1 für Schlüssel ohne Ablauf. SET mit EX ist atomar (keine Race zwischen SET und EXPIRE). KEEPTTL (6.0+) erlaubt es, einen Wert zu aktualisieren und seine TTL zu erhalten — nützlich, um gecachte Werte aufzufrischen, ohne das Ablauffenster zurückzusetzen. Expiration ist lazy (beim Zugriff geprüft) plus periodische Hintergrund-Sweeps.
# set a key with expiration in one atomic command
SET session "data" EX 3600 # 1 hour
SET cache "value" PX 60000 # 60 seconds (ms)
# set expiration on an existing key
EXPIRE mykey 60 # 60 seconds
PEXPIRE mykey 60000 # 60 seconds (ms)
EXPIREAT mykey 1700000000 # Unix timestamp
# view remaining time to live
TTL mykey # seconds (-1 = no expiry, -2 = no key)
PTTL mykey # milliseconds
# remove expiration (make key persistent)
PERSIST mykey
# TTL with KEEPTTL option (6.0+): set value, keep existing TTL
SET mykey "newval" KEEPTTLListen
Push & Pop-Operationen
Listen sind zweiseitig: LPUSH+RPOP = Queue (FIFO), LPUSH+LPOP = Stack (LIFO). BLPOP/BRPOP blockieren, bis ein Item verfügbar ist — das Fundament von Redis-Queues (kein Polling nötig). BLPOP immer ein Timeout geben, um Verbindungsabbrüche zu behandeln. Listen sind O(1) für Kopf-/Schwanzoperationen, aber O(N) für Zugriffe in der Mitte.
# lists are ordered sequences of strings (linked lists)
LPUSH mylist "a" "b" # list: [b, a]
RPUSH mylist "c" # list: [b, a, c]
# pop from head or tail
LPOP mylist # "b" (removes from head)
RPOP mylist # "c" (removes from tail)
# pop multiple (6.2+)
LPOP mylist 2 # pop 2 from head
# get length
LLEN mylist # 0
# blocking pop (waits if empty, up to timeout)
BLPOP queue:tasks 30 # blocks up to 30 seconds
BRPOP queue:tasks 0 # blocks forever
# push only if the list exists (don't create new key)
LPUSHX mylist "x" # 0 if key doesn't existLRANGE & Indexierung
LRANGE 0 -1 liefert die ganze Liste. LINDEX ist O(N) für mittlere Elemente — Listen sind für Endzugriffe optimiert. LSET ändert nach Index. LINSERT ist O(N) (bei großen Listen sparsam einsetzen). LPOS findet Elementpositionen, ohne sie zu entfernen. Bei häufigem wahlfreiem Zugriff per Index ist eine Liste die falsche Wahl — einen Sorted Set erwägen.
# get a range of elements (0-based, negative from end)
LRANGE mylist 0 -1 # all elements
LRANGE mylist 0 2 # first 3 elements
LRANGE mylist -3 -1 # last 3 elements
# get element by index (O(N) traversal)
LINDEX mylist 0 # first element
LINDEX mylist -1 # last element
# set an element by index
LSET mylist 1 "newval"
# get length
LLEN mylist
# insert before or after a pivot element
LINSERT mylist BEFORE "pivot" "new"
LINSERT mylist AFTER "pivot" "new"
# find the position of an element (6.0+)
LPOS mylist "value"
LPOS mylist "value" RANK 2 # find 2nd occurrenceBlockierende Pops & Queues
BRPOPLPUSH/BLMOVE bewegt ein Item atomar von Quelle zu Ziel — der Konsument kann es sicher verarbeiten, und wenn er crasht, ist das Item noch im Ziel (reliable-queue-Muster). Das schlägt BRPOP+Verarbeitung, weil ein Crash nach BRPOP das Item verliert. Nach der Verarbeitung aus der Zielliste löschen.
# simple FIFO queue: LPUSH to add, RPOP to consume
LPUSH tasks "job1" "job2"
RPOP tasks # "job1" (FIFO order)
# reliable queue with BRPOP (blocking, waits for work)
BRPOP tasks 0 # blocks until a task is available
# move items between lists atomically
RPOPLPUSH source destination # move one item
# blocking move (reliable queue pattern)
BRPOPLPUSH source destination 30 # blocks up to 30s
# Redis 6.2+: BLMOVE replaces BRPOPLPUSH
BLMOVE source destination RIGHT LEFT 30
# capped queue (e.g., recent events)
LPUSH recent "event"
LTRIM recent 0 99 # keep latest 100LREM, LSET & LTRIM
LTRIM ist ein übliches Muster, um die Listengröße zu deckeln (z. B. nur die letzten 100 Events behalten). LREM entfernt nach Wert (count: positiv=Kopf, negativ=Schwanz, 0=alle). LMPOP (7.0+) poppt aus mehreren Listen in einem Aufruf, praktisch für priorisierte Queues. Bei häufigen Operationen in Listenmitte ist eine Liste die falsche Wahl.
# trim to a range (removes everything outside)
LTRIM mylist 0 99 # keep only first 100 elements
LTRIM mylist -50 -1 # keep only last 50
# remove elements by value
LREM mylist 2 "value" # remove first 2 occurrences of "value"
LREM mylist -2 "value" # remove last 2 occurrences
LREM mylist 0 "value" # remove ALL occurrences
# pop and push in one atomic operation
RPOPLPUSH source dest
# pop from multiple lists (7.0+)
LMPOP 2 mylist1 mylist2 LEFT COUNT 3
# blocking pop from multiple lists (7.0+)
BLMPOP 30 2 mylist1 mylist2 LEFT COUNT 3
# remove a key only if it's a list (type-safe)
DEL mylist # works on any typeListen-Anwendungsfälle
Listen eignen sich am besten für Sequenzen mit Endzugriffsmustern: Queues, Stacks, Feeds, Puffer. LTRIM macht sie ideal für begrenzte Logs/Feeds. Für Rate Limiting ist eine Liste von Zeitstempeln + LTRIM ein einfaches gleitendes Fenster. Für sortierte/priorisierte Queues stattdessen einen Sorted Set verwenden. Listen unterstützen keine Deduplizierung — dafür ein Set.
# 1. Task queue (FIFO)
LPUSH tasks "process_order:123"
BRPOP tasks 30
# 2. Recent activity feed (capped)
LPUSH user:1:feed "post:99" "post:98"
LTRIM user:1:feed 0 49 # latest 50
# 3. Stack (LIFO)
LPUSH stack "item"
LPOP stack
# 4. Circular buffer (limited size)
LPUSH buffer "new"
LTRIM buffer 0 999 # keep 1000 items
# 5. Rate limiter (sliding window)
LPUSH rate:user:1 1700000000
LTRIM rate:user:1 0 99
LLEN rate:user:1 # request count in window
# 6. Chat history (capped)
LPUSH chat:room:1 "alice: hello"
LTRIM chat:room:1 0 999 # keep last 1000 messagesSets
SADD, SMEMBERS & SISMEMBER
Sets speichern eindeutige Werte — perfekt für Tags, Kategorien und Deduplizierung. SISMEMBER ist O(1) — weit schneller als das Prüfen einer Liste. SMEMBERS kann bei großen Sets blockieren; SSCAN für Iteration verwenden. SMISMEMBER (7.4+) prüft Mitgliedschaft im Batch und reduziert Round-Trips. Sets nutzen intset (sortiertes Array), wenn alle Mitglieder Ganzzahlen sind — sehr speichereffizient.
# sets: unordered collection of unique strings
SADD tags "redis" "db" "cache"
SADD tags "redis" # ignored (already exists)
# check membership (O(1))
SISMEMBER tags "redis" # 1 if member, 0 if not
# get all members (avoid on large sets)
SMEMBERS tags # 1) "redis" 2) "db" 3) "cache"
# get the number of members
SCARD tags # 3
# remove a member
SREM tags "cache" # 1
# check multiple memberships at once (7.4+)
SMISMEMBER tags "redis" "db" "missing"
# 1) 1 2) 1 3) 0Set-Operationen (Union/Inter/Diff)
Set-Operationen sind Redis' Superkraft — Union, Schnitt und Differenz in O(N) ohne clientseitige Verarbeitung. Anwendungsfälle: gemeinsame Freunde (SINTER), eindeutige Besucher (SUNION), tagbasierte Filterung (SINTER von Tag-Sets). SINTERCARD (7.0+) liefert nur die Anzahl — schneller, wenn man die Mitglieder nicht braucht. Ergebnisse speichern, um Neuberechnung zu vermeiden.
# set union, intersection, difference
SADD set1 "a" "b" "c"
SADD set2 "b" "c" "d"
# union (all unique members from all sets)
SUNION set1 set2 # a, b, c, d
# intersection (members in ALL sets)
SINTER set1 set2 # b, c
# difference (members in set1 but NOT in set2)
SDIFF set1 set2 # a
# store the result in a new set
SUNIONSTORE result set1 set2
SINTERSTORE result set1 set2
SDIFFSTORE result set1 set2
# count intersection without returning members (7.0+)
SINTERCARD 2 set1 set2 LIMIT 0
# operations on multiple sets at once
SUNION s1 s2 s3 s4SREM, SMOVE & SPOP
SMOVE ist atomar — nützlich für Zustandsübergänge (z. B. einen Nutzer vom 'pending'- ins 'active'-Set verschieben). SPOP entfernt zufällige Mitglieder (praktisch für Verlosung/Sharding). SRANDMEMBER entfernt nicht. BSPOP (7.0+) blockiert wie BLPOP, aber für Sets — nützlich für ereignisgetriebene Muster, bei denen die Reihenfolge egal ist. SREM liefert die tatsächlich entfernte Anzahl.
# remove one or more members
SADD myset "a" "b" "c" "d"
SREM myset "a" "b" # 2 (number removed)
# move a member from one set to another atomically
SMOVE source dest "member"
# pop a random member (removes it)
SPOP myset # removes and returns one
SPOP myset 3 # removes and returns 3 (6.2+)
# get a random member (does NOT remove)
SRANDMEMBER myset # one random member
SRANDMEMBER myset 3 # 3 random (may repeat)
SRANDMEMBER myset -3 # 3 unique random
# blocking set pop (7.0+) - waits until a member exists
BSPOP myset 30 # blocks up to 30 seconds
# delete the entire set
DEL mysetSSCAN-Iteration
SSCAN ist der sichere Weg, große Sets zu iterieren — SMEMBERS blockiert den Server bei riesigen Sets. SSCAN ist cursorbasiert: wiederholt aufrufen, bis der Cursor auf 0 zurückkehrt. COUNT ist ein Hinweis (er kann mehr oder weniger liefern). SSCAN bietet schwache Garantien: Er kann Duplikate liefern oder Mitglieder verpassen, die während der Iteration ergänzt wurden, blockiert aber nie. Die Cursor-Schleife immer im eigenen Code behandeln.
# SSCAN: cursor-based iteration for large sets
SSCAN myset 0 MATCH "pre*" COUNT 100
# returns: [nextCursor, [member1, member2, ...]]
# continue until cursor returns to 0
SSCAN myset <nextCursor> MATCH "pre*" COUNT 100
# iterate all members safely
cursor=0
while true:
cursor, members = SSCAN myset cursor COUNT 100
process(members)
if cursor == 0: break
# scan with type filtering (7.0+ for SCAN, sets always same type)
# COUNT is a hint, not exact (may return more or fewer)
# MATCH pattern supports glob: *, ?, [abc]
SSCAN myset 0 MATCH "user:*" COUNT 1000
# for small sets, SMEMBERS is fine
# for large sets (>10k), always use SSCANSet-Anwendungsfälle
Sets sind die erste Wahl für Eindeutigkeit und Beziehungen. Das SINTER-Muster für gegenseitige Follower/Freunde ist klassisch. Für 'Besucher pro Tag' mit riesiger Kardinalität HyperLogLog erwägen (approximativ, aber fix 12 KB). Für geordnete eindeutige Daten (Leaderboards) einen Sorted Set nutzen. Sets sind ungeordnet — wenn Reihenfolge zählt, eine Liste oder ein Sorted Set.
# 1. Tags / categories
SADD post:1:tags "redis" "db"
SADD post:2:tags "redis" "cache"
SINTER post:1:tags post:2:tags # posts sharing "redis"
# 2. Unique visitors per day
SADD visitors:2025-01-01 "user:1" "user:2"
SCARD visitors:2025-01-01 # visitor count
# 3. Followers / following (mutual friends)
SADD user:1:following "user:2" "user:3"
SADD user:2:following "user:1" "user:3"
SINTER user:1:following user:2:following # mutual follows
# 4. Blacklist / whitelist
SADD blacklist "ip:1.2.3.4"
SISMEMBER blacklist "ip:1.2.3.4" # 1 = blocked
# 5. Lottery / random selection
SADD participants "u1" "u2" "u3" "u4"
SPOP participants 1 # draw a winnerSorted Sets
ZADD, ZSCORE & ZRANK
Sorted Sets (zsets) sind Redis' mächtigste Struktur — eindeutige Mitglieder, geordnet nach Score, mit O(log N)-Operationen. ZADD-Optionen (NX/XX/GT/LT) ermöglichen bedingte Updates: GT aktualisiert nur, wenn der neue Score größer ist (super fürs 'Bestscore'-Tracking). Scores sind doubles; Mitglieder eindeutig. Gleichstände werden lexikografisch gebrochen.
# sorted set: unique members ordered by a float score
ZADD leaderboard 100 "alice" 200 "bob" 150 "carol"
# update a score (re-add with new score)
ZADD leaderboard 250 "alice" # alice's score becomes 250
# add with options (NX: only new, XX: only existing, GT/LT)
ZADD leaderboard NX 300 "new" # only if new
ZADD leaderboard GT 300 "alice" # only if new score > current
ZADD leaderboard LT 50 "alice" # only if new score < current
# get a member's score
ZSCORE leaderboard "alice" # "250"
# get a member's rank (0-based, ascending)
ZRANK leaderboard "alice" # rank from lowest
ZREVRANK leaderboard "alice" # rank from highest (0 = top)
# get the number of members
ZCARD leaderboard # 3
# get multiple scores at once (6.2+)
ZMSCORE leaderboard "alice" "bob" # ["250", "200"]ZRANGE & ZREVRANGE
ZRANGE liefert nach Rang (Index); mit BYSCORE liefert er nach Score-Bereich. Redis 6.2 vereinheitlichte ZRANGEBYSCORE/ZREVRANGE in ZRANGE mit den Optionen BYSCORE/BYLEX/REV. WITHSCORES schließt den Score in die Ausgabe ein. Für Leaderboards gibt ZRANGE 0 9 REV die Top 10. ZRANGESTORE (6.2+) speichert das Ergebnis unter einem neuen Schlüssel für spätere Verarbeitung.
# get members by index range (ascending)
ZRANGE leaderboard 0 -1 # all, ascending
ZRANGE leaderboard 0 2 # first 3 (lowest scores)
ZRANGE leaderboard -3 -1 # last 3 (highest scores)
# descending order
ZREVRANGE leaderboard 0 2 # top 3 (highest scores)
# with scores
ZRANGE leaderboard 0 -1 WITHSCORES
# Redis 6.2+: unified ZRANGE with BYSCORE/REV options
ZRANGE leaderboard 100 200 BYSCORE
ZRANGE leaderboard 200 100 BYSCORE REV
# store a range in a new key (6.2+)
ZRANGESTORE top3 leaderboard 0 2 REV
# get by rank with scores
ZRANGE leaderboard 0 9 REV WITHSCORES # top 10
# limit results (pagination)
ZRANGE leaderboard 0 -1 BYSCORE LIMIT 0 10ZRANGEBYSCORE & ZCOUNT
ZRANGEBYSCORE liefert nach Score-Bereich; das Präfix '(' macht einen Score exklusiv. ZCOUNT liefert die Anzahl in einem Bereich, ohne Mitglieder zu holen. ZINCRBY passt einen Score atomar an und sortiert neu — perfekt für Live-Leaderboards. ZREMRANGEBYRANK hält einen zset begrenzt (z. B. nur die Top 1000 behalten).
# get members by score range
ZRANGEBYSCORE leaderboard 100 200 # scores 100-200
ZRANGEBYSCORE leaderboard 100 +inf # scores >= 100
ZRANGEBYSCORE leaderboard -inf 200 # scores <= 200
ZRANGEBYSCORE leaderboard (100 200 # scores > 100 (exclusive)
# with pagination
ZRANGEBYSCORE leaderboard 100 200 LIMIT 0 10
# count members in a score range
ZCOUNT leaderboard 100 200
# increment a member's score atomically
ZINCRBY leaderboard 50 "alice" # alice += 50
# remove a member
ZREM leaderboard "bob"
# remove by rank range
ZREMRANGEBYRANK leaderboard 0 9 # remove lowest 10
ZREMRANGEBYSCORE leaderboard 0 100 # remove scores <= 100ZUNIONSTORE & ZINTERSTORE
ZUNIONSTORE/ZINTERSTORE kombinieren zsets mit konfigurierbarer Aggregation (SUM/MIN/MAX) und Gewichten — mächtig für gewichtete Bewertung (z. B. Relevanz = text_match*2 + recency*1). Redis 6.2 ergänzte ZUNION/ZINTER/ZDIFF, die Ergebnisse liefern, ohne zu speichern (ein Befehl weniger). Diese sind O(N*M) — bei vielen großen Sets vorsichtig. Die Set-Anzahl muss vor den Set-Namen stehen.
# combine multiple sorted sets
ZADD set1 1 "a" 2 "b"
ZADD set2 2 "a" 3 "c"
# union: sum scores by default (a = 1+2 = 3)
ZUNIONSTORE result 2 set1 set2
ZRANGE result 0 -1 WITHSCORES # a=3, b=2, c=3
# specify aggregation: SUM (default), MIN, MAX
ZUNIONSTORE result 2 set1 set2 AGGREGATE MAX # a=2, b=2, c=3
# apply weights to each set's scores
ZUNIONSTORE result 2 set1 set2 WEIGHTS 2 1 # set1 scores * 2
# intersection (only members in ALL sets)
ZINTERSTORE result 2 set1 set2 # only "a"
# Redis 6.2+: return without storing
ZUNION 2 set1 set2 WITHSCORES
ZINTER 2 set1 set2 WITHSCORES
ZDIFF 2 set1 set2 WITHSCORES
# count intersection (7.0+)
ZINTERCARD 2 set1 set2 LIMIT 0Lexikografische Bereiche (BYLEX)
BYLEX ermöglicht Bereichsabfragen auf Mitgliedern, wenn Scores gleich sind — ein Sorted Set wird zu einem automatisch sortierten String-Index. Anwendungsfälle: Autocomplete (Wörter mit Score 0 speichern, Präfixbereiche abfragen), sortierte Wörterbücher. '[a' heißt inklusiv, '(a' exklusiv, '-' Anfang, '+' Ende. Dies ist nur sinnvoll, wenn alle Scores identisch sind.
# when all scores are equal, sorted sets act as a sorted string set
ZADD myset 0 "apple" 0 "banana" 0 "cherry" 0 "date"
# range by lexicographical order
ZRANGEBYLEX myset "[a" "[c" # apple, banana, cherry
ZRANGEBYLEX myset "(a" "[c" # banana, cherry (a exclusive)
ZRANGEBYLEX myset "-" "[b" # from start to banana
ZRANGEBYLEX myset "[c" "+" # cherry to end
# count in a lex range
ZLEXCOUNT myset "[a" "[c" # 3
# remove by lex range
ZREMRANGEBYLEX myset "[a" "[b"
# Redis 6.2+: use ZRANGE with BYLEX
ZRANGE myset "[a" "[c" BYLEX
# limit results (pagination)
ZRANGEBYLEX myset "[a" "[c" LIMIT 0 10Leaderboard-Muster
Sorted Sets machen Leaderboards trivial: ZADD zum Aktualisieren von Scores, ZREVRANGE für die Top N, ZREVRANK für die Position eines Spielers. ZINCRBY aktualisiert Scores atomar. Für zeitlich gebuckette Leaderboards (täglich/wöchentlich) einen Schlüssel pro Periode mit TTL nutzen. Paginierung über ZREVRANGE mit Offset. Dies ist einer von Redis' natürlichsten und mächtigsten Anwendungsfällen.
# build a leaderboard
ZADD leaderboard 100 "alice" 250 "bob" 150 "carol"
# top 10 players (highest scores)
ZREVRANGE leaderboard 0 9 WITHSCORES
# a player's rank (0 = top)
ZREVRANK leaderboard "alice"
# update a score (atomic)
ZINCRBY leaderboard 50 "alice"
# players within a score range (e.g., silver tier 100-199)
ZRANGEBYSCORE leaderboard 100 199
# percentile rank
total = ZCARD(leaderboard)
rank = ZREVRANK(leaderboard "alice")
# percentile = (total - rank) / total * 100
# pagination (page 3, 10 per page)
ZREVRANGE leaderboard 20 29 WITHSCORES
# time-bucketed leaderboards (weekly)
ZADD leaderboard:2025-W01 100 "alice"
EXPIRE leaderboard:2025-W01 604800 # 1 week TTLHashes
HSET, HGET & HGETALL
Hashes sind ideal zum Speichern von Objekten — ein Schlüssel pro Objekt, Felder pro Eigenschaft. Das schlägt serialisiertes JSON, weil du einzelne Felder atomar aktualisieren kannst (HSET), ohne Read-Modify-Write. HGETALL liefert alle Felder; bei großen Hashes HSCAN bevorzugen. Hashes nutzen bei geringer Größe listpack-Kodierung (unter ~128 Feldern), was sie speichereffizient macht.
# a hash maps fields to values (like a small object)
HSET user:1 name "Alice" age 30 email "[email protected]"
# get a single field
HGET user:1 name # "Alice"
# get all fields and values
HGETALL user:1
# 1) "name" -> "Alice"
# 2) "age" -> "30"
# 3) "email" -> "[email protected]"
# get the number of fields
HLEN user:1 # 3
# get the string length of a field's value
HSTRLEN user:1 name # 5 (length of "Alice")
# set a field only if it doesn't exist
HSETNX user:1 status "new" # 1 if set, 0 if existed
# delete a field
HDEL user:1 email # removes the email fieldHMGET (mehrere Felder holen)
HMGET holt mehrere Felder in einem Round-Trip — viel schneller als separate HGET-Aufrufe. HSET (seit 4.0) akzeptiert mehrere Feld-Wert-Paare, HMSET ist also veraltet. HKEYS/HVALS liefern alle Feldnamen/-werte. HRANDFIELD (6.2+) ist nützlich zum Sampling (z. B. zufällige Feature-Flags). HGETALL blockiert bei großen Hashes — HSCAN für Produktionsiteration verwenden.
# get multiple fields at once
HMGET user:1 name age # 1) "Alice" 2) "30"
HMGET user:1 name missing age # 1) "Alice" 2) nil 3) "30"
# set multiple fields (HSET supports multiple field-value pairs)
HSET user:1 name "Bob" age 25 email "[email protected]"
# HMSET is deprecated (use HSET with multiple fields)
# HMSET still works but returns OK instead of count
# get all field names
HKEYS user:1 # 1) "name" 2) "age" 3) "email"
# get all values
HVALS user:1 # 1) "Alice" 2) "30" 3) "[email protected]"
# check if a field exists
HEXISTS user:1 name # 1 if exists, 0 if not
# get a random field (6.2+)
HRANDFIELD user:1 # one random field name
HRANDFIELD user:1 3 WITHVALUES # 3 random fields + valuesHINCRBY (numerische Felder)
HINCRBY auf Hash-Feldern ist atomar — perfekt für Zähler pro Nutzer (Login-Anzahl, View-Anzahl, Warenkorb-Mengen). HINCRBYFLOAT unterstützt Dezimalen. Hashes löschen sich selbst, wenn das letzte Feld entfernt wird (HDEL). Das macht Hashes zur idealen Struktur für Objekte mit numerischen Zählern — weit effizienter als separate String-Schlüssel pro Zähler.
# increment a numeric field atomically
HSET user:1:stats logins 0
HINCRBY user:1:stats logins 1 # logins = 1
HINCRBY user:1:stats logins 1 # logins = 2
HINCRBY user:1:stats logins -1 # logins = 1
# increment by a specific amount
HINCRBY user:1:stats page_views 10
# floating point increment
HINCRBYFLOAT user:1:stats score 0.5
# all HINCRBY operations are atomic
# perfect for per-user/per-object counters
# use case: shopping cart (product_id -> quantity)
HSET cart:user:1 product:100 2
HINCRBY cart:user:1 product:100 1 # now 3
HINCRBY cart:user:1 product:100 -1 # now 2
HDEL cart:user:1 product:100 # remove itemHSCAN (Hash-Iteration)
HGETALL blockiert den Server bei großen Hashes — HSCAN für Produktionsiteration verwenden. HSCAN ist cursorbasiert: wiederholt aufrufen, bis der Cursor auf 0 zurückkehrt. COUNT ist ein Hinweis. Ergebnisse kommen als flaches [field, value, field, value, ...]-Array — in deinem Code paaren. Bei Hashes mit Millionen Feldern überlegen, in mehrere Schlüssel zu shardn.
# HSCAN: cursor-based iteration (for large hashes)
HSCAN user:1 0 MATCH "na*" COUNT 10
# returns [cursor, [field, value, field, value, ...]]
# iterate all fields safely
cursor=0
while true:
cursor, fields = HSCAN user:1 cursor COUNT 100
process(fields)
if cursor == 0: break
# HGETALL is fine for small hashes (< 100 fields)
# HSCAN is required for large hashes to avoid blocking
# match field names with glob patterns
HSCAN user:1 0 MATCH "user:*" COUNT 1000
# no VALUES-only option; results are [field, value, field, value, ...]
# pair them up in your code
# COUNT is a hint — may return more or fewer than requested
# HSCAN never blocks; safe for production useHash-Anwendungsfälle
Hashes glänzen bei Objekten und gruppierten Zählern. Eine mächtige Speichertechnik: Viele kleine String-Schlüssel in einen Hash gruppieren — die listpack-Kodierung hat weit weniger Overhead als Tausende einzelne Schlüssel (jeweils mit Metadaten). Dieses 'Key Bucketing' kann die Speichernutzung bei kleinen Werten um Faktor 5-10 senken. Feldbezogene TTL (7.4+) ist ein großer Zusatz.
# 1. Store an object (user profile, config)
HSET config:app name "MyApp" version "2.0" debug "off"
# 2. Per-user counters
HINCRBY user:1:stats logins 1
HINCRBY user:1:stats page_views 1
HGET user:1:stats logins
# 3. Shopping cart (product_id -> quantity)
HSET cart:user:1 product:100 2
HINCRBY cart:user:1 product:100 1
HDEL cart:user:1 product:100
# 4. Feature flags
HSET feature_flags user:1 new_ui 1 beta 0
HGET feature_flags user:1 new_ui # 1
# 5. Session store with TTL
HSET session:abc user_id 1 data "..."
EXPIRE session:abc 1800 # 30 min
# 6. Hash field expiration (Redis 7.4+)
HEXPIRE user:1 60 FIELDS 1 session_token
HPTTL user:1 FIELDS 1 session_tokenSchlüsselverwaltung
EXISTS, TYPE & DEL
EXISTS mit mehreren Schlüsseln liefert die Anzahl der existierenden. TYPE liefert den Datenstruktur-Typ — vor dem Operieren immer prüfen, um WRONGTYPE-Fehler zu vermeiden (der Typ eines Schlüssels ist für seine Lebensdauer unveränderlich). DEL ist blockierend und kann den Server bei großen Strukturen aufhalten; für große Schlüssel UNLINK bevorzugen. TYPE liefert 'none' für nicht existierende Schlüssel.
# check if a key exists
SET mykey "hello"
EXISTS mykey # 1
EXISTS missing # 0
EXISTS key1 key2 key3 # count of existing keys (multiple)
# get the type of a value
TYPE mykey # "string"
TYPE mylist # "list"
TYPE missing # "none"
# delete one or more keys
DEL mykey # 1 if deleted, 0 if not
DEL key1 key2 key3 # number of keys deleted
# delete is blocking for large keys — use UNLINK instead
# UNLINK deletes in a background thread
# check type before operating to avoid WRONGTYPE errors
TYPE mykey
# returns: string | list | hash | set | zset | stream | noneUNLINK (async-Delete)
UNLINK (4.0+) ist die nicht-blockierende Alternative zu DEL für große Schlüssel — er entfernt den Schlüssel sofort aus dem Keyspace, gibt aber Speicher in einem Hintergrundthread frei und verhindert so Server-Stalls. Bei Schlüsseln mit Millionen Elementen immer UNLINK verwenden. FLUSHDB ASYNC / FLUSHALL ASYNC tun dasselbe für Massenlöschung. Der Lazyfree-Threadpool übernimmt das eigentliche Freigeben.
# UNLINK: non-blocking delete (large keys)
UNLINK biglist bighash # returns count of deleted keys
# UNLINK removes the key from the keyspace immediately
# but frees the memory in a background thread
# compare:
DEL biglist # blocks until fully freed
UNLINK biglist # returns immediately, frees later
# for small keys, DEL and UNLINK are equivalent
# for large keys (millions of elements), UNLINK is essential
# flush database asynchronously (non-blocking)
FLUSHDB ASYNC
FLUSHALL ASYNC
# check what's being freed in background
INFO memory | grep lazyfreeRENAME & RENAMENX
RENAME verschiebt einen Schlüssel atomar auf einen neuen Namen und überschreibt jeden bestehenden Zielschlüssel (und seinen Wert). RENAMENX (6.2+) benennt nur um, wenn das Ziel nicht existiert, und verhindert so versehentliches Überschreiben. Die TTL bleibt beim Umbenennen erhalten. RENAME ist atomar — kein anderer Client sieht einen Zwischenzustand. Datenbankübergreifendes Umbenennen wird nicht unterstützt; MOVE oder DUMP/RESTORE nutzen.
# rename a key (overwrites destination if it exists)
SET oldkey "value"
RENAME oldkey newkey # OK; oldkey is gone, newkey has "value"
# rename only if destination doesn't exist (6.2+)
RENAMENX oldkey newkey # 1 if renamed, 0 if newkey already exists
# rename preserves the type and TTL
SET tempkey "data" EX 3600
RENAME tempkey permkey # permkey now has TTL of ~3600s
TTL permkey # ~3600
# rename across databases is not supported
# use MOVE + RENAME, or DUMP/RESTORE for cross-db moves
# type is immutable — rename keeps the type
TYPE permkey # "string"
# renaming is atomicKEYS vs. SCAN
KEYS blockiert den Server beim Scannen des gesamten Keyspaces — in Produktion bei großen Datensätzen NIE verwenden. SCAN ist die produktionsfähige Alternative: cursorbasiert, nicht-blockierend, liefert einen Cursor, dem du bis 0 folgst. SCAN kann Duplikate liefern oder Schlüssel verpassen, die während der Iteration ergänzt wurden, blockiert aber nie. COUNT ist ein Hinweis (er kann mehr oder weniger liefern). Die Cursor-Schleife immer im eigenen Code behandeln.
# KEYS: blocks the server while scanning — NEVER in production
KEYS * # all keys (DANGEROUS on large DBs)
KEYS user:* # keys matching pattern
KEYS session:*
# SCAN: cursor-based iteration (non-blocking, production-safe)
SCAN 0 MATCH user:* COUNT 100
# returns: [nextCursor, [key1, key2, ...]]
# continue until cursor returns to 0
SCAN <nextCursor> MATCH user:* COUNT 100
# scan by type (7.0+)
SCAN 0 TYPE hash
SCAN 0 MATCH user:* TYPE string COUNT 100
# SCAN is weakly consistent:
# - may return duplicates
# - may miss keys added during iteration
# - but NEVER blocks the server
# COUNT is a hint, not exactRANDOMKEY & DBSIZE
RANDOMKEY liefert einen zufälligen Schlüssel, ohne ihn zu entfernen — nützlich zum Sampling. DBSIZE liefert die exakte Anzahl der Schlüssel in der aktuellen Datenbank (O(1)). INFO keyspace zeigt Zählungen pro Datenbank mit Ablauf-Stats (keys, expires, avg_ttl). Für einen zufälligen Schlüssel eines bestimmten Typs gibt es keinen eingebauten Befehl — SCAN + TYPE in einer Schleife nutzen.
# get a random key (O(1), does not remove)
RANDOMKEY # "user:1" or nil if db is empty
# get the number of keys in the current database
DBSIZE # 1234
# count keys across all databases (in a cluster)
# note: DBSIZE only counts the current db
SELECT 0; DBSIZE
SELECT 1; DBSIZE
# get keyspace info (keys per db with expiry info)
INFO keyspace
# db0:keys=1000,expires=500,avg_ttl=3600000
# db1:keys=50,expires=10,avg_ttl=60000
# scan with count for approximate size estimation
SCAN 0 COUNT 1 # get cursor + small sample
# find a random key of a specific type
# (no built-in; use SCAN + TYPE in a loop)OBJECT-Befehle
OBJECT ENCODING legt die interne Repräsentation offen (Speicher-Debugging). OBJECT IDLETIME findet kalte Schlüssel (Kandidaten für Eviction). OBJECT FREQ funktioniert nur mit maxmemory-policy LFU. MEMORY USAGE mit SAMPLES 0 zählt exakt (Standard sampelt bei großen Collections). COMMAND DOCS (7.0+) liefert strukturierte Dokumentation. Diese Introspektionswerkzeuge helfen beim Debuggen von Speicherbloat.
# OBJECT subcommands for introspection
OBJECT ENCODING mykey # internal encoding (embstr, raw, int, listpack, etc.)
OBJECT REFCOUNT mykey # reference count
OBJECT IDLETIME mykey # seconds since last access
OBJECT FREQ mykey # access frequency (LFU mode only)
# check memory usage of a key (bytes)
MEMORY USAGE mykey
MEMORY USAGE mykey SAMPLES 0 # exact count (slower for large keys)
# total memory used by the server
INFO memory | grep used_memory_human
# inspect a key's internal structure (debugging, can be slow)
DEBUG OBJECT mykey # raw internal info
# the encoding changes automatically as the structure grows
# e.g., hash: listpack -> hashtable when fields exceed threshold
# help understand a command
COMMAND INFO GET
COMMAND DOCS SET # structured docs (7.0+)Ablauf & Persistenz
EXPIRE & EXPIREAT
EXPIRE setzt eine TTL auf einen bestehenden Schlüssel; SET mit EX/PX/EXAT/PXAT macht es atomar (bevorzugt). Die Optionen NX/GT/LT (7.0+) ermöglichen bedingte TTL-Setzung — nützlich für 'nur Ablauf ergänzen, wenn keiner da' oder 'nur verlängern, nie verkürzen'. TTL liefert -1 für Schlüssel ohne Ablauf, -2 für nicht existierende Schlüssel. Expiration ist lazy (beim Zugriff geprüft) plus periodische Hintergrund-Sweeps.
# set expiration on an existing key (seconds)
SET mykey "value"
EXPIRE mykey 60 # expires in 60 seconds
EXPIRE mykey 60 NX # only set TTL if none exists (7.0+)
EXPIRE mykey 60 GT # only set if new TTL > current (7.0+)
EXPIRE mykey 60 LT # only set if new TTL < current (7.0+)
# set expiration in milliseconds
PEXPIRE mykey 60000
# set expiration at a Unix timestamp
EXPIREAT mykey 1700000000 # seconds
PEXPIREAT mykey 1700000000000 # milliseconds
# set value AND expiration atomically (preferred)
SET token "abc" EX 3600
SET token "abc" PX 3600000
SET token "abc" EXAT 1700000000
# get remaining TTL
TTL mykey # seconds (-1 = no expiry, -2 = no key)
PTTL mykey # millisecondsPERSIST (TTL entfernen)
PERSIST entfernt die TTL und macht einen Schlüssel persistent (der Wert bleibt). GETEX (6.2+) liefert atomar den Wert und setzt oder entfernt die TTL — nützlich, um den Session-Ablauf beim Lesen aufzufrischen (GETEX key EX 3600) oder einen temporären Schlüssel dauerhaft zu machen (GETEX key PERSIST). COPY (6.2+) kopiert einen Schlüssel, optional datenbankübergreifend, ohne die Race von GET+SET.
# remove expiration (make key persistent)
SET session "data" EX 3600
TTL session # 3600
PERSIST session # 1 (success)
TTL session # -1 (no expiry)
# PERSIST returns 1 if the TTL was removed, 0 if key had no TTL or doesn't exist
# copy a key with optional TTL handling (6.2+)
COPY source dest # copy without TTL
COPY source dest REPLACE # overwrite destination
COPY source dest DB 1 # copy to another database
# GETEX: get value and optionally set/remove TTL (6.2+)
GETEX mykey EX 3600 # returns value, sets 3600s TTL
GETEX mykey PERSIST # returns value, removes TTL
# note: PERSIST only removes TTL; the key and value remainSAVE & BGSAVE (RDB)
SAVE blockiert den Server, bis der Snapshot fertig ist — in Produktion nie verwenden. BGSAVE fork-t den Prozess (copy-on-write), der Hauptthread wird also nicht blockiert, aber große Datensätze können während des Forks Speicherspitzen verursachen. Die 'save'-Regeln lösen automatische Snapshots nach Änderungsrate aus. RDB ist kompakt und ideal für Backups, riskiert aber, nach dem letzten Snapshot geschriebene Daten zu verlieren.
# SAVE: synchronous snapshot (BLOCKS the server until done)
SAVE # blocks — use only in maintenance windows
# BGSAVE: background snapshot (non-blocking, forks a child)
BGSAVE # returns immediately, saves in background
LASTSAVE # Unix timestamp of the last successful save
# check if a BGSAVE is in progress
INFO persistence | grep rdb_bgsave_in_progress
# configure automatic snapshots in redis.conf:
# save 3600 1 # save if >= 1 key changed in 3600s
# save 300 100 # save if >= 100 keys changed in 300s
# save 60 10000 # save if >= 10000 keys changed in 60s
# save "" # disable RDB entirely
# RDB file location
CONFIG GET dbfilename # "dump.rdb"
CONFIG GET dir # "/var/lib/redis"
# RDB pros: compact, fast restart, great for backups
# RDB cons: potential data loss between snapshotsBGREWRITEAOF (AOF-Kompaktierung)
AOF hängt jeden Schreibbefehl an ein Log an — weit dauerhafter als RDB (maximal 1 Sekunde Datenverlust mit everysec). 'always' macht bei jedem Schreiben fsync (sehr langsam, nur für kritische Daten). BGREWRITEAOF komprimiert das Log (schreibt es als minimale Befehlsmenge neu). Redis 7 nutzt ein mehrteiliges AOF-Format (Basis-RDB + inkrementelles Log) — appenddirname hält die Teile.
# AOF: logs every write command (durable, replayable)
# enable in redis.conf:
# appendonly yes
# appendfilename "appendonly.aof"
# fsync policies:
# appendfsync always # fsync every write (safest, slowest)
# appendfsync everysec # fsync once per second (default, balanced)
# appendfsync no # let OS decide (fastest, risk of data loss)
# trigger AOF rewrite (compacts the log)
BGREWRITEAOF # non-blocking, rewrites in background
# AOF auto-rewrite thresholds:
# auto-aof-rewrite-percentage 100
# auto-aof-rewrite-min-size 64mb
# check AOF status
INFO persistence | grep aof
# AOF pros: minimal data loss (1 sec max with everysec)
# AOF cons: larger files, slower load on restart
# Redis 7: multi-part AOF (base + incremental files)
CONFIG GET appenddirname # "appendonlydir"Persistenz-Konfiguration
CONFIG SET ändert Einstellungen zur Laufzeit (kein Neustart nötig); CONFIG REWRITE persistiert sie in redis.conf. Das empfohlene Produktionssetup ist RDB + AOF Hybrid: RDB für schnellen Neustart und Backups, AOF für minimalen Datenverlust. Seit Redis 7 beginnt die AOF mit einem RDB-Basis-Snapshot gefolgt von inkrementellen Befehlen — schnelles Laden mit Dauerhaftigkeit kombiniert.
# view current persistence settings
CONFIG GET save
CONFIG GET appendonly
CONFIG GET appendfsync
CONFIG GET dir
CONFIG GET dbfilename
CONFIG GET appendfilename
# enable AOF at runtime
CONFIG SET appendonly yes
# change fsync policy at runtime
CONFIG SET appendfsync everysec
# disable RDB snapshots
CONFIG SET save ""
# persist config changes to redis.conf
CONFIG REWRITE
# hybrid persistence (recommended):
# RDB for fast restart + AOF for durability
# redis.conf:
# save 3600 1
# appendonly yes
# aof-use-rdb-preamble yes # RDB header in AOF (faster load)
# check persistence status
INFO persistenceBackup & Restore
Die RDB-Datei (kompakt, schnell) regelmäßig sichern — sie ist ein konsistenter Snapshot, selbst während Redis läuft (copy-on-write). Bei AOF das ganze appendonly-Verzeichnis sichern (Redis 7 mehrteilig). Wiederherstellen: Redis stoppen, Dateien ersetzen, neu starten. Um einen Fehler nach einem schlechten Befehl zu beheben, die AOF bearbeiten und ihn vor dem Neustart entfernen. redis-cli --rdb macht ein Online-Backup, ohne das Dateisystem direkt anzufassen.
# backup: copy the RDB file while Redis runs
BGSAVE
# wait for LASTSAVE to update, then copy the file
cp /var/lib/redis/dump.rdb /backup/dump-$(date +%F).rdb
# AOF backup: copy the AOF manifest + files (Redis 7)
cp -r /var/lib/redis/appendonlydir /backup/
# restore: stop Redis, replace data files, restart
redis-cli SHUTDOWN
cp /backup/dump.rdb /var/lib/redis/dump.rdb
redis-server /etc/redis/redis.conf
# for point-in-time recovery from AOF:
# edit the AOF file to remove unwanted commands, then restart
# RDB file analysis (offline, safe)
redis-check-rdb /var/lib/redis/dump.rdb
redis-check-aof /var/lib/redis/appendonly.aof
# fix a truncated AOF
redis-check-aof --fix /var/lib/redis/appendonly.aof
# online backup with --rdb (dumps RDB to stdout/file)
redis-cli --rdb /backup/dump.rdbPub/Sub
SUBSCRIBE & UNSUBSCRIBE
SUBSCRIBE blockiert den Client, um Nachrichten aus einem oder mehreren Kanälen zu empfangen. Ein abonnierter Client darf nur SUBSCRIBE/UNSUBSCRIBE/PSUBSCRIBE/PUNSUBSCRIBE/PING/QUIT aufrufen — keine anderen Befehle. PUBSUB introspektiert den Pub/Sub-Zustand (aktive Kanäle, Abonnentenzahlen). Nachrichten sind fire-and-forget: Lauscht kein Abonnent, geht die Nachricht verloren. Für zuverlässige Zustellung Streams nutzen.
# subscribe to channels (in one client, blocks)
SUBSCRIBE news alerts
# the client now listens for messages:
# 1) "subscribe" 2) "news" 3) 1
# 1) "subscribe" 2) "alerts" 3) 2
# unsubscribe from specific channels
UNSUBSCRIBE news
UNSUBSCRIBE news alerts
# unsubscribe from ALL channels
UNSUBSCRIBE
# note: published messages are NOT persisted
# if no subscriber is listening, the message is lost
# for persistent messaging, use Streams instead
# count active subscriptions (in another client)
PUBSUB CHANNELS # list active channels
PUBSUB NUMSUB news # subscriber count for "news"PUBLISH
PUBLISH liefert die Anzahl der Abonnenten, die die Nachricht erhalten haben (0, wenn keine). Nach der Veröffentlichung gibt es keinen Weg, die Nachricht zurückzuholen — lauscht kein Abonnent, ist sie weg. PUBSUB CHANNELS listet aktive Kanäle (mit mindestens einem Abonnenten); PUBSUB NUMSUB liefert Abonnentenzahlen. Für zuverlässiges, wiederholbares Messaging Streams nutzen (XADD/XREAD).
# publish a message to a channel (from another client)
PUBLISH news "Breaking: Redis 7.4 released"
# returns: number of subscribers that received the message
# publish to a channel with no subscribers
PUBLISH empty "hello"
# returns: 0 (message is lost)
# publish to multiple channels (separate PUBLISH calls)
PUBLISH news "msg1"
PUBLISH alerts "msg2"
# pub/sub has no persistence, no replay, no consumer groups
# subscribers must be connected to receive messages
# check how many clients are listening
PUBSUB NUMSUB news
PUBSUB NUMSUB news alerts # multiple channels
# list active channels (with pattern)
PUBSUB CHANNELS # all active channels
PUBSUB CHANNELS news:* # channels matching patternPSUBSCRIBE (Muster-Subscription)
PSUBSCRIBE abonniert Kanäle passend zu Glob-Mustern — mächtig fürs Event-Routing (z. B. user:*:login erwischt alle Nutzer-Login-Events). Eine Nachricht, die sowohl eine direkte Subscription als auch ein Muster trifft, wird zweimal zugestellt. Muster-Abonnenten empfangen 'pmessage'-Events mit Muster, Kanal und Nachricht. PUNSUBSCRIBE bricht Muster-Subscriptions ab.
# subscribe to channels matching a glob pattern
PSUBSCRIBE news.*
PSUBSCRIBE user:*:login
PSUBSCRIBE events:*
# patterns use glob syntax:
# * matches any sequence
# ? matches one character
# [ab] matches 'a' or 'b'
# unsubscribe from patterns
PUNSUBSCRIBE news.*
PUNSUBSCRIBE # unsubscribe from ALL patterns
# a message matching both a direct subscription and a pattern
# is delivered twice (once for each)
# pattern subscribers receive:
# 1) "pmessage" 2) "news.*" 3) "news.tech" 4) "the message"
# use case: event routing
PSUBSCRIBE user:*:login # all user logins
PSUBSCRIBE order:*:created # all order creations
PSUBSCRIBE cache:*:invalidate # cache invalidation eventsSharded Pub/Sub (7.0+)
Sharded Pub/Sub (7.0+) löst ein Cluster-Modus-Problem: normales Pub/Sub broadcastet jedes PUBLISH an alle Cluster-Knoten und verschwendet Bandbreite. Sharded Pub/Sub routet Nachrichten nur an den Shard, dem der Kanalschlüssel gehört — bei großen Clustern weit effizienter. In Cluster-Deployments SSUBSCRIBE/SPUBLISH verwenden. Der Kanalname bestimmt den Shard (wie ein Schlüssel).
# regular Pub/Sub broadcasts to ALL cluster nodes (expensive)
# sharded Pub/Sub routes messages only to the shard owning the channel
# subscribe to a shard channel
SSUBSCRIBE mychannel
# publish to a shard channel
SPUBLISH mychannel "hello"
# sharded pub/sub uses the channel name for shard routing
# so messages only travel within one shard (more efficient)
# use sharded pub/sub in a Redis Cluster to avoid
# broadcasting messages to every node
# regular SUBSCRIBE/PUBLISH still work in cluster mode
# but they broadcast to all shards (cluster-wide overhead)
# check shard channel subscribers (7.0+)
PUBSUB SHARDCHANNELS
PUBSUB SHARDNUMSUB mychannelKeyspace-Notifications
Keyspace-Notifications lassen Clients auf Lebenszyklus-Events von Schlüsseln reagieren (set, delete, expire, evict). Konfigurieren mit notify-keyspace-events. Sie sind fire-and-forget (keine Persistenz) und nicht zuverlässig — startet der Redis-Server neu, gehen ausstehende Events verloren. Für zuverlässige Eventverarbeitung Streams nutzen. Keyspace-Notifications eignen sich für Nebenwirkungen wie Aufräumen oder Cache-Warming.
# enable keyspace notifications (disabled by default)
CONFIG SET notify-keyspace-events "KEA"
# K = keyspace events, E = keyevent events
# g = generic (DEL, EXPIRE, ...), $ = string, l = list
# h = hash, s = set, z = sorted set, x = expired, e = evicted
# A = all except m (m = keymiss)
# subscribe to events on a specific key
SUBSCRIBE __keyspace@0__:mykey
# publishes "set", "del", "expire", etc.
# subscribe to events of a specific type
SUBSCRIBE __keyevent@0__:del
# publishes the key name that was deleted
# example: react when a key expires
SUBSCRIBE __keyspace@0__:session:abc
# receives "expired" when the key TTL ends
# example: react to all expired keys
SUBSCRIBE __keyevent@0__:expired
# check current setting
CONFIG GET notify-keyspace-eventsTransaktionen
MULTI & EXEC
MULTI/EXEC gruppiert Befehle in einen atomaren, sequenziellen Block — kein anderer Client kann sich einmischen. Befehle werden eingereiht (Rückgabe QUEUED) und gemeinsam bei EXEC ausgeführt. Ein Einreihungsfehler (falscher Befehlsname) bricht die ganze Transaktion ab. Ein Laufzeitfehler (falscher Typ auf einem Schlüssel) überspringt nur diesen Befehl — der Rest läuft weiter. Das unterscheidet sich von SQL-Transaktionen.
# MULTI starts a transaction; commands are queued
MULTI
SET counter 1
INCR counter
INCR counter
GET counter
EXEC
# returns: 1) OK 2) 2 3) 3 4) "3"
# all queued commands execute atomically (no interleaving)
# other clients cannot run commands between MULTI and EXEC
# each queued command returns "QUEUED" until EXEC
MULTI
SET x 1
# "QUEUED"
INCR x
# "QUEUED"
EXEC
# 1) OK 2) 2
# the transaction is atomic: all or nothing (at queuing time)DISCARD (Transaktion abbrechen)
DISCARD bricht eine Transaktion ab, leert alle eingereihten Befehle und löst die Verbindung aus dem Transaktionsmodus. Er leert auch alle WATCHed-Schlüssel (siehe WATCH). Nach DISCARD kann der Client wieder normale Befehle senden. DISCARD ist das 'rollback'-Äquivalent — aber beachte: Redis unterstützt kein teilweise Rollback innerhalb von EXEC; Laufzeitfehler überspringen den fehlschlagenden Befehl, committen aber den Rest.
# DISCARD cancels a transaction (clears all queued commands)
MULTI
SET x 1
INCR x
DISCARD
# OK — no commands are executed
# after DISCARD, the connection returns to normal mode
GET x
# (nil) or the previous value — nothing changed
# DISCARD also clears all WATCHed keys
WATCH counter
MULTI
INCR counter
DISCARD
# counter is no longer watched
# you must call MULTI before DISCARD
DISCARD
# ERR DISCARD without MULTIWATCH (optimistisches Locking)
WATCH implementiert optimistisches Locking: Ändert sich ein beobachteter Schlüssel zwischen WATCH und EXEC, wird die Transaktion abgebrochen (EXEC liefert nil). Das ist das Standard-Redis-Muster für Read-Modify-Write-Atomarität (da Redis keine Zeilenlocks hat). Bei nil immer wiederholen. WATCH wird zur EXEC-Zeit geprüft. UNWATCH bricht Beobachtungen ab (passiert auch bei DISCONNECT). Auch eine Änderung eines beobachteten Schlüssels durch denselben Client löst einen Abbruch aus.
# WATCH monitors keys; if any change before EXEC, transaction aborts
WATCH counter
val = GET counter # read current value
MULTI
INCR counter # queue the update
EXEC # nil if counter changed -> retry
# typical pattern: read-modify-write with retry
WATCH key
current = GET key
new_value = compute(current)
MULTI
SET key new_value
EXEC
# if EXEC returns nil, the key changed — loop and retry
# UNWATCH cancels all watches
UNWATCH
# WATCH is checked at EXEC time, not during queuing
# if a watched key is modified (by any client, including yourself),
# EXEC returns nil and the transaction is not executedUNWATCH & WATCH-Randfälle
Nach EXEC (egal ob die Transaktion committet oder wegen WATCH abgebrochen wurde) werden alle Beobachtungen automatisch geleert. Dasselbe gilt für DISCARD. Um eine optimistische Lock-Schleife zu wiederholen, muss WATCH vor dem nächsten MULTI erneut aufgerufen werden. WATCH innerhalb von MULTI ist ein Fehler — WATCH muss immer vor MULTI stehen. UNWATCH dient hauptsächlich dem Abbrechen von Beobachtungen, ohne in eine Transaktion einzutreten.
# UNWATCH cancels all watches
WATCH key1 key2
UNWATCH # both keys are no longer watched
# WATCH inside a MULTI is not allowed (error)
MULTI
WATCH key
# ERR WATCH inside MULTI is not allowed
# after EXEC (success or abort), watches are cleared
WATCH key
MULTI
SET key "new"
EXEC
# key is no longer watched after EXEC
# after DISCARD, watches are cleared
WATCH key
MULTI
DISCARD
# key is no longer watched
# re-WATCH after EXEC to retry the optimistic lock loop
WATCH key
val = GET key
MULTI
SET key newval
EXEC
# if nil, loop: WATCH key again, GET, MULTI, SET, EXECTransaktions-Fehlerbehandlung
Redis hat zwei Fehlertypen in Transaktionen. Einreihungsfehler (falscher Befehlsname/Arity) brechen die ganze Transaktion zur EXEC-Zeit ab (EXECABORT) — nichts läuft. Laufzeitfehler (z. B. INCR auf einem Nicht-Integer) überspringen nur den fehlschlagenden Befehl — der Rest läuft weiter. Es gibt KEIN Rollback. Das ist ein kritischer Unterschied zu SQL-Datenbanken. Daten vor MULTI validieren, um Laufzeitfehler zu vermeiden.
# two types of errors in transactions:
# 1. Queuing errors (bad command syntax) — aborts the WHOLE transaction
MULTI
SET key "value"
INCRBY key "notanumber" # error during queuing (wrong arity/type at parse)
GET key
EXEC
# EXECABORT Transaction discarded because of previous errors.
# NOTHING executes — not even the SET
# 2. Runtime errors (wrong type at execution) — skips ONLY that command
SET key "stringvalue"
MULTI
INCR key # queues fine (syntax OK)
SET otherkey "ok"
EXEC
# 1) (error) ERR value is not an integer
# 2) OK
# the INCR failed but SET otherkey succeeded — no rollback!
# lesson: Redis transactions do NOT have rollback like SQLPipelining
Pipeline-Grundlagen
Pipelining bündelt Befehle, um Netzwerk-Round-Trips zu senken — dramatisch schneller als Einzelbefehle übers Netzwerk. Jeder Round-Trip kostet Netzwerklatenz (~0,1-1 ms); 1000 Einzelbefehle = 100-1000 ms, aber gepipelint = ~1 ms. Die meisten Client-Bibliotheken bieten eine pipeline/multi-Methode. redis-cli kann über stdin pipelinen. Pipelining garantiert KEINE Atomarität — andere Clients können sich einmischen.
# pipelining sends multiple commands in one network round-trip
# (no atomicity guarantee, just reduced latency)
# using redis-cli with stdin (simple pipeline):
printf '%s\n' "SET k1 v1" "SET k2 v2" "GET k1" | redis-cli
# OK
# OK
# "v1"
# using redis-cli --pipe (raw RESP, fastest for bulk loads):
# (see the data-import-export section for details)
# in a client library (e.g., Node.js with ioredis):
const pipe = redis.pipeline()
pipe.set("k1", "v1")
pipe.set("k2", "v2")
pipe.incr("counter")
const results = await pipe.exec()
# vs individual commands:
await redis.set("k1", "v1") # round-trip 1
await redis.set("k2", "v2") # round-trip 2
await redis.incr("counter") # round-trip 3MULTI vs. Pipelining
MULTI/EXEC garantiert Atomarität (kein anderer Client kann sich einmischen) UND wird von den meisten Client-Bibliotheken automatisch gepipelint (also auch weniger Round-Trips). Plain-Pipelining senkt nur die Round-Trips — andere Clients können zwischen deinen gepipelinten Befehlen ausführen. MULTI/EXEC nutzen, wenn Atomarität nötig ist (z. B. Read-Modify-Write mit WATCH); plain-Pipelining für Bulk-Operationen, wo Reihenfolge/Atomarität egal sind.
# MULTI/EXEC: atomic (no interleaving), pipelined automatically
MULTI
SET k1 v1
SET k2 v2
INCR counter
EXEC
# all 3 commands run atomically as one block
# Pipelining: NOT atomic, just batched (other clients can interleave)
# (in client code)
pipe.set("k1", "v1")
pipe.set("k2", "v2")
pipe.incr("counter")
pipe.exec()
# commands may interleave with other clients
# when to use which:
# - need atomicity (all-or-nothing)? -> MULTI/EXEC
# - just want speed (bulk operations)? -> pipelining
# - both? -> MULTI/EXEC (auto-pipelined)
# MULTI/EXEC is automatically pipelined by most clients
# so you get atomicity + batch round-trips in oneRESP-Protokoll
RESP ist Redis' Protokoll — einfach, textbasiert und schnell. *N bezeichnet ein Array aus N Elementen; $N einen Bulk-String aus N Bytes; + ein einfacher String; : eine Ganzzahl; - ein Fehler. redis-cli --pipe-Modus nimmt rohes RESP für Bulk-Loading mit maximaler Geschwindigkeit (viel schneller als Textbefehle via stdin). RESP zu verstehen hilft beim Debuggen und beim Bauen eigener Clients.
# RESP (REdis Serialization Protocol) is the wire format
# redis-cli sends RESP; you can also send it raw with --pipe
# simple command (PING) in RESP:
# *1\r\n$4\r\nPING\r\n
# SET key value in RESP:
# *3\r\n$3\r\nSET\r\n$3\r\nkey\r\n$5\r\nvalue\r\n
# RESP types:
# +OK simple string
# -ERR error
# :42 integer
# $5\r\nhello bulk string
# *2\r\n... array
# raw pipeline with RESP (fastest bulk insert):
# generate a RESP file and pipe it:
cat commands.resp | redis-cli --pipe
# --pipe mode expects raw RESP; checks reply counts
# output: "Last reply received from server: ..."
# "errors: 0, replies: N"Pipeline in Shell-Skripten
Shell-Scripting mit redis-cli ist ein üblicher Weg, um Daten im Bulk zu laden oder Batch-Operationen auszuführen. Der einfachste Ansatz piped Textbefehle via stdin (echo/cat | redis-cli). Für maximale Geschwindigkeit RESP erzeugen und --pipe-Modus nutzen (um Größenordnungen schneller bei großen Lasten). Die bash-Schleifenbeispiele zeigen beide Ansätze — nach Umfang und Performancebedürfnis wählen.
# pipeline multiple commands via stdin
echo -e "SET k1 v1\nSET k2 v2\nGET k1\nGET k2" | redis-cli
# pipeline from a file
cat commands.txt | redis-cli
# pipeline with --pipe-mode (raw RESP, fastest)
# first generate RESP, then pipe:
redis-cli --pipe < commands.resp
# bulk insert example (bash, generate RESP):
for i in $(seq 1 1000); do
printf '*3\r\n$3\r\nSET\r\n$4\r\nkey:\r\n$1\r\n%s\r\n' "$i"
done | redis-cli --pipe
# or simpler (text mode, slightly slower):
for i in $(seq 1 1000); do
echo "SET key:$i value$i"
done | redis-cli
# --pipe-mode reports errors and throughputPipeline-Grenzen & Best-Practices
Pipelining ist der größte einzelne Redis-Performance-Hebel, aber nicht überpipelinen — eingereihte Antworten verbrauchen Speicher auf Client und Server. In Gruppen von 100-1000 Befehlen bündeln. Mit redis-benchmark -P benchmarken, um den Sweet Spot zu finden (Durchsatz flacht ab, Latenz steigt bei sehr großen Pipelines). Für Befehle, die von vorherigen Ergebnissen abhängen, Lua-Skripte nutzen (atomar, ein Round-Trip) statt mehrerer gepipelinter Aufrufe.
# don't pipeline too many commands at once
# (queued replies consume memory on both client and server)
# bad: 1 million commands in one pipeline
# -> huge memory buffer, potential timeout
# good: batch in groups of 100-1000
for batch in chunks(data, 500):
pipe = redis.pipeline()
for item in batch:
pipe.set(item.key, item.value)
pipe.exec()
# benchmark pipelining
redis-benchmark -t set -n 100000 -P 16 # -P = pipeline size
# try -P 1, 10, 100, 1000 to find the sweet spot
# use pipelining for:
# - bulk imports
# - batch reads (MGET is better for simple multi-get)
# - pre-warming cache
# - reducing latency in high-RTT environments
# avoid pipelining for:
# - commands that depend on previous results (use Lua instead)
# - very large batches (split into chunks)Lua-Scripting
EVAL-Grundlagen
EVAL führt Lua-Skripte atomar aus — während ein Skript läuft, führt kein anderer Befehl aus, ideal für mehrstufige atomare Operationen. KEYS und ARGV reichen Daten vom Aufrufer durch; Schlüssel im Skript nie per String-Konkatenation bauen (verletzt Cluster-Regeln — alle Schlüssel müssen in KEYS stehen). redis.call wirft Fehler (hält an), redis.pcall liefert sie zurück. Skripte werden nach ihrem SHA1-Hash für EVALSHA gecacht.
# EVAL: run a Lua script inline
# EVAL "script" numkeys key1 key2 ... arg1 arg2 ...
EVAL "return redis.call('GET', KEYS[1])" 1 mykey
# 1 = number of keys
# mykey = KEYS[1]
# run a simple script (no keys)
EVAL "return 42" 0
EVAL "return {1, 2, 3}" 0
EVAL "return 'hello'" 0
# a check-and-set script:
EVAL "
local cur = redis.call('GET', KEYS[1])
if cur == ARGV[1] then
return redis.call('SET', KEYS[1], ARGV[2])
end
return 0
" 1 mykey "expected" "newvalue"
# redis.call() raises error if command fails (stops script)
# redis.pcall() returns error as a table (can handle)
EVAL "local ok, err = pcall(redis.call, 'GET', 'missing'); return err" 0EVALSHA & SCRIPT LOAD
EVALSHA führt ein zuvor geladenes Skript nach seinem SHA1-Hash aus und vermeidet, den Skriptkörper bei jedem Aufruf erneut zu senden — ein großer Bandbreitengewinn für Apps, die dasselbe Skript wiederholt ausführen. Bei Cache-Miss (nach SCRIPT FLUSH oder Neustart) liefert Redis NOSCRIPT; Clients fangen das ab und fallen auf EVAL + SCRIPT LOAD zurück. Immer Bibliotheken nutzen (redis-py, ioredis), die das transparent handhaben.
# load a script once, get its SHA1
SCRIPT LOAD "return redis.call('GET', KEYS[1])"
# returns: "fa00d1f0..." (the SHA1 hash)
# execute by hash (saves bandwidth on repeated calls)
EVALSHA "fa00d1f0..." 1 mykey
# check if a script is cached
SCRIPT EXISTS "fa00d1f0..." "abcd1234..."
# 1) 1 2) 0 (1 = exists, 0 = not cached)
# flush the script cache
SCRIPT FLUSH
# list all running scripts (during debug)
SCRIPT DEBUG SYNC # blocking debug mode
SCRIPT DEBUG NO # disable debugger
# typical client library pattern:
# 1. SCRIPT LOAD the script on startup
# 2. EVALSHA to run it (falls back to EVAL on NOSCRIPT error)SCRIPT LOAD, FLUSH & EXISTS
SCRIPT LOAD cache-t ein Skript und liefert seinen SHA1. SCRIPT EXISTS prüft, ob Skripte gecacht sind (nützlich nach einem Neustart). SCRIPT FLUSH leert alle gecachten Skripte — nachfolgendes EVALSHA liefert NOSCRIPT. SCRIPT KILL stoppt ein langlebiges Skript, aber nur, wenn es noch keine Schreibvorgänge gemacht hat (um Konsistenz zu wahren); sonst bleibt nur SHUTDOWN NOSAVE. Skripte sind flüchtig — für Persistenz Functions (7.0+) nutzen.
# SCRIPT LOAD: load a script without running it
SCRIPT LOAD "return redis.call('SET', KEYS[1], ARGV[1])"
# returns the SHA1 hash
# SCRIPT EXISTS: check if scripts are cached (after load or restart)
SCRIPT EXISTS "abc123..." "def456..."
# 1) 1 2) 0
# SCRIPT FLUSH: clear the script cache
SCRIPT FLUSH
# all EVALSHA calls will now return NOSCRIPT until scripts are reloaded
# SCRIPT KILL: stop a running script (only if it hasn't written yet)
SCRIPT KILL
# if the script has already executed a write command:
# SHUTDOWN NOSAVE is the only way to stop it (extreme measure)
# scripts are ephemeral — they don't survive a restart
# use Redis Functions (7.0+) for persistent scripts
# check the script cache size
INFO memory | grep script_cacheKEYS und ARGV
KEYS[] trägt Schlüsselnamen (essenziell fürs Cluster-Routing — der Cluster nutzt sie, um zu bestimmen, welcher Shard das Skript behandelt). ARGV[] trägt Werte und Parameter. Schlüsselnamen nie im Skript hartkodieren (z. B. redis.call('GET', 'mykey')) — das bricht das Cluster-Routing, weil der Cluster nicht erkennen kann, auf welchem Shard 'mykey' lebt. Schlüssel immer über KEYS[] übergeben. Das numkeys-Argument sagt Redis, wie viele KEYS zu erwarten sind.
# KEYS[]: key names passed to the script
# ARGV[]: additional arguments (values, options)
# example: atomic increment with cap
EVAL "
local current = tonumber(redis.call('GET', KEYS[1]) or 0)
local max = tonumber(ARGV[1])
if current >= max then
return -1 -- cap reached
end
return redis.call('INCR', KEYS[1])
" 1 counter 100
# KEYS[1] = counter, ARGV[1] = 100
# example: move item between lists atomically
EVAL "
local item = redis.call('RPOP', KEYS[1])
if item then
redis.call('LPUSH', KEYS[2], item)
end
return item
" 2 source_list dest_list
# NEVER hardcode key names in scripts (breaks cluster routing)
# always pass keys via KEYS[] so the cluster can route correctlyAtomare Operationen mit Lua
Lua-Skripte sind der kanonische Weg für atomare Mehrbefehl-Operationen in Redis (keine MULTI/EXEC-Race). Compare-and-set, Semaphore-Beantragung, Queue-Migrationen und Rate Limiting profitieren alle. Skripte blockieren den Server während des Laufens — kurz halten und Schleifen über viele Schlüssel vermeiden (sie können andere Clients aufhalten). Bei sehr langer Arbeit Redis Functions nutzen (Redis 7.0+), die wie Stored Procedures deklariert und versioniert sind.
# atomic compare-and-set (only update if value matches)
EVAL "
local cur = redis.call('GET', KEYS[1])
if cur == ARGV[1] then
return redis.call('SET', KEYS[1], ARGV[2])
end
return 0
" 1 mykey "expected" "newvalue"
# atomic 'decrement if positive' (semaphore / rate limit)
EVAL "
local val = tonumber(redis.call('GET', KEYS[1]) or 0)
if val > 0 then
redis.call('DECR', KEYS[1])
return 1
end
return 0
" 1 semaphore
# atomic list pop + push (move between queues)
EVAL "
local item = redis.call('RPOP', KEYS[1])
if item then
redis.call('LPUSH', KEYS[2], item)
end
return item
" 2 source_queue dest_queue
# atomic rate limiter (fixed window)
EVAL "
local count = redis.call('INCR', KEYS[1])
if count == 1 then
redis.call('EXPIRE', KEYS[1], ARGV[1])
end
return count
" 1 rate:user:1 60Redis Functions (7.0+)
Functions (7.0+) verbessern EVAL-Skripte: Sie sind benannt (nicht nur gehasht), in Bibliotheken organisiert und überstehen Neustarts (EVAL-Skripte sind flüchtig). Das macht sie leichter zu verwalten und zu deployen. FCALL ruft eine Funktion beim Namen auf. Functions sind der moderne Weg, atomare serverseitige Logik zu ergänzen. Wie Skripte müssen sie für die Replikation deterministisch sein. FUNCTION DUMP/RESTORE ermöglicht Backup und Migration.
# FUNCTIONS are named, versioned Lua scripts (better than EVAL)
# register a function library
FUNCTION LOAD '#!lua name=mylib
redis.register_function("my_set",
function(keys, args)
return redis.call("SET", keys[1], args[1])
end
)'
# call a function by name
FCALL my_set 1 mykey "hello"
# list loaded libraries
FUNCTION LIST
FUNCTION LIST WITHCODE # include source
# get the function's code (for backup)
FUNCTION DUMP
# delete a library
FUNCTION DELETE mylib
# restore from a dump (for migration)
FUNCTION RESTORE <payload>
# functions persist across restarts (unlike EVAL scripts)
# they're saved in RDB/AOFVerbindungsverwaltung
CLIENT LIST
CLIENT LIST zeigt jeden verbundenen Client mit Adresse, Alter, Leerlaufzeit, aktuellem Befehl und Flags — unbezahlbar, um Lecks oder hängende Clients zu finden. Das Feld 'idle' hilft, verlassene Verbindungen zu erkennen. 'cmd' zeigt den letzten Befehl (praktisch, um einen Client zu finden, der einen langsamen Befehl läuft). 'flags' kennzeichnet den Client-Typ (N=normal, M=master, S=slave/replica, P=pubsub, b=blocked). Ab 7.0+ nach TYPE filtern.
# list all connected clients
CLIENT LIST
# fields: id, addr, laddr, fd, name, age, idle, flags, db, cmd, ...
# filter by type (7.0+)
CLIENT LIST TYPE normal # normal clients only
CLIENT LIST TYPE replica # replicas
CLIENT LIST TYPE pubsub # pub/sub subscribers
# filter by ID (7.0+)
CLIENT LIST ID 1 2 3
# output includes useful fields:
# addr=10.0.0.1:12345 remote address
# age=3600 seconds since connected
# idle=0 seconds since last command
# cmd=get last command executed
# db=0 current database
# flags=N N=normal, M=master, S=slave, P=pubsub
# count connected clients
CLIENT LIST | wc -lCLIENT SETNAME & GETNAME
CLIENT SETNAME labelt eine Verbindung, sodass du sie in CLIENT LIST erkennst — essenziell zum Debuggen von Verbindungslecks in Multi-Service-Umgebungen. Den Namen in der App direkt nach dem Verbinden setzen (z. B. 'api-server:pid12345:pool1'). Namen erscheinen im 'name'-Feld von CLIENT LIST. So ist es trivial zu finden, welcher Dienst eine hängende oder leckende Verbindung besitzt.
# name your connection (for identification in CLIENT LIST)
CLIENT SETNAME "my-app-worker-1"
# get the current connection's name
CLIENT GETNAME
# in application code, set the name immediately after connecting:
# redis-cli example:
redis-cli CLIENT SETNAME "debug-session"
# names appear in CLIENT LIST output:
CLIENT LIST
# ... name=my-app-worker-1 ...
# names are useful for:
# - identifying which app/pool a connection belongs to
# - finding leaks (connections that should have been closed)
# - debugging stuck clients
# - naming conventions: app:hostname:pid or pool:name
# names are limited to a reasonable length and cannot contain spacesCLIENT KILL
CLIENT KILL trennt einen Client zwangsweise — nützlich, um hängende oder leckende Verbindungen zu entfernen. Töten nach ADDR (ip:port), ID, TYPE oder USER (ACL). MAXAGE (7.0+) tötet Clients, die länger als N Sekunden idle sind. SKIPME yes (Standard) verhindert, dass deine eigene Verbindung getötet wird. Zuerst CLIENT LIST nutzen, um das Ziel zu finden, dann CLIENT KILL zum Trennen. Kills sind sofort (kein graceful shutdown).
# kill a client by address
CLIENT KILL ADDR 10.0.0.1:12345
# kill a client by ID
CLIENT KILL ID 42
# kill by type (7.0+)
CLIENT KILL TYPE normal # kill all normal clients
CLIENT KILL TYPE pubsub # kill all pub/sub clients
# kill by user (ACL, 6.0+)
CLIENT KILL USER appuser
# kill by address with skip-me
CLIENT KILL ADDR 10.0.0.1:0 SKIPME yes # don't kill myself
# kill all clients matching filters (7.0+)
CLIENT KILL TYPE normal MAXAGE 3600 # kill idle > 1h
# kill returns the number of clients killed
# use with caution — kills are immediate, no graceful shutdown
# common use: disconnect a stuck client consuming resources
CLIENT LIST
CLIENT KILL ID <id>CLIENT ID & INFO
CLIENT ID liefert eine eindeutige, nie wiederverwendete Ganzzahl für die Verbindung — nützlich fürs Logging und die Korrelation. CLIENT INFO gibt detaillierte Infos über deine eigene Verbindung. CLIENT NO-EVICT (6.0+) schützt die Schreibvorgänge eines Clients vor Eviction-Auslösung (praktisch für kritische Schreibvorgänge). CLIENT REPLY steuert, ob der Server Antworten sendet (OFF für fire-and-forget-Bulk-Loads, SKIP für einen Befehl).
# get the current client's unique ID (never reused)
CLIENT ID
# get the current client's info (detailed)
CLIENT INFO
# id=42 addr=127.0.0.1:12345 laddr=127.0.0.1:6379 name= db=0 ...
# the ID is a monotonically increasing integer
# it's unique per connection and never reused
# useful for logging and tracking
# CLIENT NO-EVICT (6.0+): this client's writes won't trigger eviction
CLIENT NO-EVICT ON # protect this client from eviction
CLIENT NO-EVICT OFF # normal behavior
# CLIENT REPLY (6.0+): control reply mode
CLIENT REPLY ON # normal replies
CLIENT REPLY OFF # no replies
CLIENT REPLY SKIP # skip reply for next command only
# CLIENT UNPAUSE: resume processing after CLIENT PAUSE
CLIENT UNPAUSECLIENT PAUSE
CLIENT PAUSE blockiert die Befehlsausführung für alle anderen Clients für N Millisekunden — nützlich für sichere Snapshots, Migrationen und Cluster-Failovers. WRITE-Modus (7.0+) pausiert nur Schreibvorgänge, während Lesevorgänge weitergehen (weniger störend). Der pausierende Client selbst wird nicht blockiert. Während der Pause verbrauchen eingereihte Befehle Speicher — Pausen also kurz halten. CLIENT UNPAUSE setzt sofort fort.
# pause all client processing for N milliseconds
CLIENT PAUSE 10000 # pause for 10 seconds
# all other clients' commands are queued, not executed
# pause modes (7.0+):
CLIENT PAUSE 10000 ALL # pause all commands (default)
CLIENT PAUSE 10000 WRITE # pause only writes (reads continue)
# resume processing immediately
CLIENT UNPAUSE
# use cases:
# - safe snapshot/migration (pause writes, take consistent backup)
# - cluster failover (pause to ensure clean handoff)
# - debugging (pause to inspect state)
# during pause:
# - commands from OTHER clients are queued (memory grows)
# - the pausing client can still run commands
# - paused commands execute when the pause ends
# check if a pause is active
CLIENT INFO | grep flags
# 'P' flag = pausedVerbindungslimits & Timeout
maxclients begrenzt gleichzeitige Verbindungen (Standard 10000) — erhöhen, wenn du viele App-Server oder Connection-Pools hast. timeout trennt ungenutzte Clients (0 = nie; sicherheitshalber auf 300 s setzen). tcp-keepalive erkennt tote TCP-Verbindungen (Standard 300 s). Jeder Client verbraucht Speicher für seinen Ausgabepuffer — mit INFO clients überwachen. client-output-buffer-limit verhindert, dass ein langsamer Client den ganzen Server-Speicher frisst (besonders wichtig für Pub/Sub und Replicas).
# max concurrent clients
CONFIG GET maxclients # default 10000
CONFIG SET maxclients 50000 # increase limit
# timeout: disconnect idle clients after N seconds
CONFIG GET timeout # default 0 (never)
CONFIG SET timeout 300 # 5 minutes
# TCP keepalive (detect dead connections)
CONFIG GET tcp-keepalive # default 300
CONFIG SET tcp-keepalive 60
# when maxclients is reached, new connections are rejected
# error: "ERR max number of clients reached"
# check current client count vs limit
INFO clients
# connected_clients:150
# blocked_clients:5
# maxclients:10000
# each connection uses memory (~a few KB for the output buffer)
# monitor for output buffer growth:
INFO clients | grep client_recent_max_output_buffer
# set output buffer limits (prevent one client from using all memory)
CONFIG GET client-output-buffer-limitSerververwaltung
INFO-Sektionen
INFO ist der zentrale Monitoring-Befehl — er meldet Speicher, Clients, Replikation, Persistenz und Stats in einem Rutsch. Sektionen filtern (INFO memory), um die Ausgabe zu verkleinern. Schlüsselmetriken: used_memory_rss (echter Fußabdruck), mem_fragmentation_ratio (ideal ~1,0-1,5), connected_clients, instantaneous_ops_per_sec, keyspace_hits/misses (Cache-Hit-Ratio). TIME liefert die Serverzeit zur Uhrensynchro.
# comprehensive server information
INFO # all sections
INFO server # version, uptime, config
INFO clients # connected clients
INFO memory # memory usage, fragmentation
INFO persistence # RDB/AOF status
INFO stats # ops/sec, hit rate, keyspace
INFO replication # primary/replica state
INFO cpu # CPU usage
INFO keyspace # keys per database
INFO commandstats # command frequency
INFO errorstats # error frequency
# get a specific metric
INFO memory | grep used_memory_human
INFO stats | grep instantaneous_ops_per_sec
INFO replication | grep role
# check Redis version and mode
INFO server | grep redis_version
INFO server | grep redis_mode # standalone, cluster, sentinel
# get server time
TIME # [unix_timestamp, microseconds]CONFIG GET & SET
CONFIG SET ändert Einstellungen zur Laufzeit ohne Redis-Neustart — ideal zum Tunen. CONFIG GET holt aktuelle Werte (Muster wie CONFIG GET *memory* verwenden). Übliche Laufzeit-Justagen: maxmemory + Eviction-Politik, slowlog-Schwellwert, timeout, Kodierungsschwellwerte. Nicht alle Einstellungen sind zur Laufzeit änderbar (z. B. Port, bind-Adresse brauchen einen Neustart). Config-Änderungen immer zuerst im Staging testen.
# view config (runtime changes with CONFIG SET)
CONFIG GET maxmemory
CONFIG GET maxmemory-policy
CONFIG GET save
CONFIG GET appendonly
CONFIG GET requirepass
# change config at runtime (no restart needed)
CONFIG SET maxmemory 4gb
CONFIG SET maxmemory-policy allkeys-lru
CONFIG SET slowlog-log-slower-than 10000 # 10ms in microseconds
CONFIG SET timeout 300
# view all config (large output)
CONFIG GET *
# get a specific pattern
CONFIG GET *max*
CONFIG GET *timeout*
# common runtime tweaks:
CONFIG SET maxclients 20000
CONFIG SET hash-max-listpack-entries 256
CONFIG SET appendfsync everysecCONFIG REWRITE
CONFIG REWRITE persistiert zur Laufzeit gemachte CONFIG-SET-Änderungen zurück in redis.conf — die Datei wird in-place aktualisiert, Kommentare und Struktur bleiben erhalten. Das überbrückt die Lücke zwischen Laufzeitänderungen und Persistenz über Neustarts hinweg. redis.conf vor REWRITE immer sichern (verursacht selten Probleme, aber Sicherheit zuerst). redis.conf versionieren, um Änderungen über die Zeit zu tracken und zu auditieren.
# persist config changes to redis.conf
CONFIG REWRITE
# after CONFIG SET maxmemory 4gb
# CONFIG REWRITE updates redis.conf to include:
# maxmemory 4gb
# the original redis.conf is updated in-place
# comments and structure are preserved
# view the config file path
CONFIG GET *
# typical redis.conf (production):
# bind 127.0.0.1
# protected-mode yes
# port 6379
# maxmemory 4gb
# maxmemory-policy allkeys-lru
# save 3600 1
# appendonly yes
# appendfsync everysec
# tcp-keepalive 300
# timeout 0
# always back up redis.conf before CONFIG REWRITESLOWLOG
SLOWLOG zeichnet Befehle auf, die langsamer als der konfigurierte Schwellwert sind (Standard 10 ms = 10000us) — unbezahlbar, um Latenzübeltäter zu finden. Den Schwellwert auf dein SLO setzen (z. B. 5 ms). Häufige langsame Befehle: KEYS, SMEMBERS auf riesigen Sets, HGETALL auf riesigen Hashes, SORT auf großen Daten. slowlog-max-len begrenzt das Log (Standard 128). Schwellwert 0 loggt alles (nur Debugging — hoher Overhead).
# configure slow log (threshold in microseconds)
CONFIG SET slowlog-log-slower-than 10000 # 10ms (10000 us)
CONFIG SET slowlog-max-len 128 # keep last 128 entries
# view slow commands
SLOWLOG GET # last 10 (default)
SLOWLOG GET 5 # last 5
SLOWLOG GET 0 # all entries
# each entry:
# 1) id unique ID
# 2) timestamp Unix time
# 3) duration microseconds
# 4) command the command and args
# 5) client address:port
# 6) client name if set
# slowlog length
SLOWLOG LEN
# reset (clear all entries)
SLOWLOG RESET
# set threshold to 0 to log ALL commands (debugging)
# set to -1 to disable
CONFIG SET slowlog-log-slower-than 0MONITOR
MONITOR streamt jeden Befehl jedes Clients in Echtzeit — ein mächtiges Debugging-Werkzeug, aber mit RIESIGEM Performance-Einfluss (halbiert den Durchsatz grob). MONITOR in Produktion NIE verwenden, außer absolut nötig und nur kurz. Perfekt fürs Staging: MONITOR verbinden, Problem reproduzieren, exakt sehen, welche Befehle deine App sendet. Für Produktionsmonitoring stattdessen SLOWLOG, LATENCY MONITOR oder INFO commandstats.
# MONITOR: real-time log of ALL commands (debugging only!)
MONITOR
# every command from every client is printed:
# 1700000000.123456 [0 10.0.0.1:12345] "SET" "key" "value"
# 1700000000.123567 [0 10.0.0.1:12345] "GET" "key"
# to stop monitoring, send any non-MONITOR command or disconnect
# press Ctrl+C in redis-cli
# WARNING: MONITOR has a HUGE performance impact
# it roughly halves throughput — use only for debugging
# use cases:
# - debugging what commands an app is sending
# - auditing command patterns
# - finding the source of unexpected writes
# safer alternatives for production:
# - SLOWLOG (only slow commands)
# - LATENCY MONITOR (specific events)
# - COMMANDSTATS in INFO (command frequency)
# MONITOR is best used in a staging/dev environmentLATENCY-Monitoring
LATENCY MONITOR trackt Latenz-Events (einen Schwellwert setzen, z. B. 100 ms). LATENCY DOCTOR analysiert aktuelle Events und schlägt Fixes vor — ein guter Ausgangspunkt für die Diagnose. Übliche Events: 'command' (langsame Befehle), 'fork' (BGSAVE-Fork-Verzögerung), 'expire-cycle' (Ablauf-Sweep), 'aof-write' (AOF-fsync-Verzögerung). LATENCY GRAPH zeigt eine ASCII-Zeitachse. Schwellwert auf dein SLO setzen und regelmäßig überwachen.
# enable latency monitoring (threshold in ms)
CONFIG SET latency-monitor-threshold 100 # 100ms
# view latency events
LATENCY HISTORY event-name
LATENCY LATEST # most recent events
LATENCY HISTORY command
LATENCY HISTORY expire-cycle
# ASCII art graph of an event
LATENCY GRAPH command
# human-readable diagnosis and recommendations
LATENCY DOCTOR
# reset latency data
LATENCY RESET
LATENCY RESET event-name
# common events to monitor:
# command slow commands
# fast-command slow O(1) commands
# expire-cycle expiration cycle taking too long
# fork BGSAVE/BGREWRITEAOF fork taking too long
# aof-write AOF write delays
# unlink async delete delays
# check current threshold
CONFIG GET latency-monitor-thresholdCluster
CLUSTER INFO
CLUSTER INFO gibt eine schnelle Gesundheitszusammenfassung: cluster_state sollte 'ok' sein (alle 16384 Slots abgedeckt), cluster_slots_ok sollte 16384 entsprechen. cluster_known_nodes ist die Knotenzahl gesamt; cluster_size die Anzahl der Primaries. Ist cluster_state 'fail', sind manche Slots unbrauchbar (wahrscheinlich ein Primary und sein Replica beide down). Von jedem Knoten prüfbar — die Info ist clusterweit.
# cluster-wide health
CLUSTER INFO
# key fields:
# cluster_state:ok # ok or fail
# cluster_slots_assigned:16384 # total slots
# cluster_slots_ok:16384 # slots covered
# cluster_known_nodes:6 # total nodes
# cluster_size:3 # number of primaries
# cluster_current_epoch:7
# cluster_my_epoch:1
# cluster_state:ok means all slots are covered
# cluster_state:fail means some slots are unavailable
# check from any node in the cluster
redis-cli -p 7000 CLUSTER INFO
# other cluster commands require being in cluster mode
# (redis-server --cluster-enabled yes)CLUSTER NODES
CLUSTER NODES ist die maßgebliche Topologieansicht — eine Zeile pro Knoten mit ID, Adresse, Rolle (master/slave), dem gefolgten Master (bei Replicas) und Slot-Bereichen. Auf 'fail'- oder 'fail?'-Flags achten, die ungesunde Knoten anzeigen. Die Slot-Bereiche zeigen, welcher Primary welche Hash-Slots besitzt (0-16383). CLUSTER SHARDS (7.0+) gruppiert Knoten nach Shard (Primary + seine Replicas).
# view the full cluster topology
CLUSTER NODES
# each line is a node:
# <id> <addr:port@cport> <flags> <master> <ping-sent> <pong-recv> <epoch> <link> <slots>
# flags include:
# M = master (primary)
# S = slave (replica)
# mymaster = the node this replica follows
# fail? = suspected down
# fail = confirmed down
# handshake = new node joining
# nofailover = failover disabled
# example output:
# 1a2b... 127.0.0.1:7000@17000 myself,master - 0 0 1 connected 0-5460
# 3c4d... 127.0.0.1:7001@17001 master - 0 0 2 connected 5461-10922
# 5e6f... 127.0.0.1:7002@17002 master - 0 0 3 connected 10923-16383
# 7g8h... 127.0.0.1:7003@17003 slave 1a2b... 0 0 4 connected
# count nodes by type
CLUSTER NODES | grep -c master
CLUSTER NODES | grep -c slave
# Redis 7.0+: shard view
CLUSTER SHARDSCLUSTER KEYSLOT & COUNTKEYSINSLOT
CLUSTER KEYSLOT zeigt, auf welchen Slot ein Schlüssel mappt (CRC16 % 16384). Hash-Tags ({...}) zwingen verwandte Schlüssel in denselben Slot — essenziell für Mehrschlüssel-Operationen (MGET, Transaktionen, Lua-Skripte) im Cluster. redis-cli -c (Cluster-Modus) nutzen, um MOVED-Redirects automatisch zu folgen. CLUSTER GETKEYSINSLOT holt Schlüssel in einem Slot (genutzt beim Resharding).
# get the hash slot for a key
CLUSTER KEYSLOT mykey # e.g., 1234
# CRC16(key) % 16384
# count keys in a specific slot (on the owning node)
CLUSTER COUNTKEYSINSLOT 1234
# get keys in a slot (must be run on the slot's owning node)
CLUSTER GETKEYSINSLOT 1234 10 # up to 10 keys
# in a cluster, keys must be on the same slot for multi-key ops
# use hash tags to force keys to the same slot:
SET {user:1}:profile "alice"
SET {user:1}:cart "items"
# both map to the same slot (the part inside {})
# CLUSTER KEYSLOT {user:1}:profile
# CLUSTER KEYSLOT {user:1}:cart
# same result -> same slot -> same shard
# if you access a key on the wrong node, you get a MOVED redirect:
# (error) MOVED 1234 127.0.0.1:7000
# redis-cli -c follows redirects automaticallyHash-Tags
Hash-Tags ({...}) zwingen Schlüssel in denselben Slot und ermöglichen Mehrschlüssel-Operationen im Cluster. Aber überlegt einsetzen — ein Tag zu überstrapazieren (z. B. {users}:1, {users}:2) erzeugt einen Hotspot auf einem Shard. Hash-Tags um Zugriffsmuster herum entwerfen: Schlüssel gruppieren, die gemeinsam gelesen werden (Daten eines Nutzers, Items einer Bestellung), aber unverwandte Schlüssel getrennt halten. Das ist die zentrale Cluster-Datenmodellierungs-Herausforderung.
# hash tags: the substring inside {} determines the slot
# {user:1}:profile and {user:1}:cart share a slot
# enabling multi-key operations in a cluster:
MSET {user:1}:name "Alice" {user:1}:age 30 # OK (same slot)
MSET user:1:name "Alice" user:2:age 30 # CROSSSLOT error
# transactions across keys (must be same slot)
WATCH {order:1}:items
MULTI
HINCRBY {order:1}:items product:1 1
HINCRBY {order:1}:total 10
EXEC
# Lua scripts accessing multiple keys (all keys must share a slot)
EVAL "..." 2 {user:1}:a {user:1}:b
# design hash tags carefully:
# - too broad -> hotspots (one shard overloaded)
# e.g., {users}:1, {users}:2 -> all on one shard (bad!)
# - too narrow -> can't do multi-key ops
# e.g., user:1:a, user:1:b -> different slots (can't MGET)
# good: {user:1}:* groups one user's data on one shard
# bad: {all-users}:* puts everyone on one shardCLUSTER FAILOVER
Cluster-Failover ist automatisch, wenn ein Primary länger als cluster-node-timeout (Standard 15 s) unerreichbar ist. Manuelles Failover ist für Wartung (Upgrades ohne Ausfallzeit): FAILOVER ist sanft (wartet auf Replikationssync), FORCE überspringt den Sync (schneller, leichtes Datenverlustrisiko), TAKEOVER umgeht den Konsens (nur Notfall, Split-Brain-Risiko). Nach dem Failover wird der alte Primary bei Rückkehr Replica. In Produktion immer mit Replicas laufen lassen.
# when a primary fails, its replica is promoted automatically
# manual failover (for maintenance), run on the REPLICA:
redis-cli -p 7001 CLUSTER FAILOVER # graceful (waits for sync)
redis-cli -p 7001 CLUSTER FAILOVER FORCE # without primary agreement (faster)
redis-cli -p 7001 CLUSTER FAILOVER TAKEOVER # force, may split brain (emergency)
# graceful failover steps:
# 1. replica stops syncing from master
# 2. master stops accepting writes
# 3. replica catches up on replication offset
# 4. replica is promoted to master
# 5. cluster is updated with new master info
# 6. old master becomes a replica when it returns
# CLUSTER RESET resets a node (HARD removes all data)
CLUSTER RESET HARD
CLUSTER RESET SOFT
# check failover status
CLUSTER INFO | grep cluster_state
# rolling upgrade pattern:
# for each replica: CLUSTER FAILOVER (becomes master), upgrade old masterredis-cli --cluster Tool
Das redis-cli --cluster-Tool übernimmt komplexe Cluster-Operationen: Erzeugung, Resharding, Rebalancing, Knoten hinzufügen/entfernen, Health-Checks und Reparaturen. --cluster check ist dein Anlaufpunkt, um die Cluster-Gesundheit nach Änderungen zu verifizieren. --cluster fix repariert kleinere Probleme automatisch (verwaiste Slots usw.). --cluster call führt einen Befehl auf allen Knoten aus. Diese statt manueller CLUSTER-Befehle für Betriebstasks nutzen.
# create a cluster (6 nodes: 3 primaries + 3 replicas)
redis-cli --cluster create \
host1:7000 host2:7000 host3:7000 \
host1:7001 host2:7001 host3:7001 \
--cluster-replicas 1
# check cluster health
redis-cli --cluster check host1:7000
# repair issues
redis-cli --cluster fix host1:7000
# reshard (move slots between nodes)
redis-cli --cluster reshard host1:7000
# prompts for: how many slots, target node, source nodes
# rebalance slots across all nodes
redis-cli --cluster rebalance host1:7000
# add a new node
redis-cli --cluster add-node newhost:7000 host1:7000
# add a replica
redis-cli --cluster add-node newhost:7001 host1:7000 \
--cluster-slave --cluster-master-id <nodeId>
# remove a node (migrates its slots first)
redis-cli --cluster del-node host1:7000 <nodeId>
# call a command on all nodes
redis-cli --cluster call host1:7000 INFO serverSentinel (HA)
Sentinel-Setup
Sentinel liefert HA ohne Sharding: Er überwacht einen Primary, befördert bei Ausfall ein Replica und konfiguriert Clients um. Quorum (die letzte Zahl) ist, wie viele Sentinels sich einig sein müssen, dass ein Primary down ist — auf (N/2)+1 setzen bei N Sentinels. 3 Sentinels auf getrennten Maschinen deployen für Fehlertoleranz. down-after-milliseconds sollte > Netzwerk-Jitter sein; zu niedrig verursacht falsche Failovers.
# Sentinel monitors a primary + replicas, handles failover
# sentinel.conf (port 26379):
sentinel monitor mymaster 192.168.1.10 6379 2
# name, host, port, quorum (number of sentinels to agree on failure)
sentinel down-after-milliseconds mymaster 30000 # 30s to declare down
sentinel failover-timeout mymaster 180000 # 3min failover timeout
sentinel parallel-syncs mymaster 1 # replicas to resync in parallel
# start a sentinel:
redis-sentinel /etc/redis/sentinel.conf
# or:
redis-server /etc/redis/sentinel.conf --sentinel
# deploy at least 3 sentinels (odd number) for quorum
# sentinels communicate with each other and the Redis nodes
# connect to a sentinel to find the current primary:
redis-cli -p 26379 SENTINEL get-master-addr-by-name mymaster
# sentinel auto-discovers other sentinels and replicasSENTINEL masters & replicas
SENTINEL masters listet alle überwachten Primaries; SENTINEL master <name> gibt Details (inklusive num-slaves und num-other-sentinels). SENTINEL replicas zeigt die Replicas; SENTINEL sentinels zeigt die Peer-Sentinels. ckquorum verifiziert, dass genug Sentinels für ein Quorum da sind — im Monitoring ausführen. Alle großen Redis-Client-Bibliotheken unterstützen Sentinel nativ (sie fragen Sentinels ab, um den aktuellen Primary zu finden).
# query sentinel state
redis-cli -p 26379 SENTINEL masters # all monitored primaries
redis-cli -p 26379 SENTINEL master mymaster # details of one primary
# fields: name, ip, port, runid, role, ...
# num-slaves, num-other-sentinels
# quorum, down-after-milliseconds
# failover-timeout, parallel-syncs
# list replicas of a master
redis-cli -p 26379 SENTINEL replicas mymaster
# list other sentinels monitoring the same master
redis-cli -p 26379 SENTINEL sentinels mymaster
# count monitoring sentinels (should be >= quorum)
redis-cli -p 26379 SENTINEL sentinels mymaster | grep -c name
# check the number of OK sentinels
SENTINEL ckquorum mymaster
# "OK 3 usable Sentinels. Quorum and failover authorization can be reached"
# or "NOQUORUM" warning (not enough sentinels)SENTINEL get-master-addr-by-name
SENTINEL get-master-addr-by-name liefert IP und Port des aktuellen Primaries — Clients rufen das auf, um den Primary zu entdecken, und verbinden sich dann mit ihm. Beim Failover liefern Sentinels die Adresse des neuen Primaries. Clients sollten +switch-master-Events abonnieren, um sofort von Failovers zu erfahren. Dieses Discovery-Muster ist in den Sentinel-Modi aller großen Redis-Client-Bibliotheken eingebaut.
# find the current primary address
redis-cli -p 26379 SENTINEL get-master-addr-by-name mymaster
# 1) "192.168.1.10"
# 2) "6379"
# clients use this to discover the current primary
# on failover, the sentinel returns the new primary's address
# clients should connect to sentinels, NOT directly to the primary
# libraries: redis-py, jedis, ioredis all support sentinel mode
# example client connection (pseudo-code):
# 1. connect to a sentinel
# 2. SENTINEL get-master-addr-by-name mymaster
# 3. connect to the returned primary
# 4. on connection error, repeat from step 1
# monitor for failover events
redis-cli -p 26379 SUBSCRIBE +switch-master
# publishes: mymaster 192.168.1.10 6379 192.168.1.11 6379
# other events:
redis-cli -p 26379 SUBSCRIBE +failover-state
redis-cli -p 26379 SUBSCRIBE +sdown
redis-cli -p 26379 SUBSCRIBE +odownSENTINEL failover
SENTINEL failover löst ein manuelles Failover aus (für rollierende Upgrades/Wartung). Automatisches Failover tritt ein, wenn ein Primary länger als down-after-milliseconds down ist. Failover ist automatisch, verursacht aber eine kurze Schreibpause (Sekunden). Der gewählte Sentinel-Leader wählt das aktuellste Replica zur Beförderung. Kehrt der alte Primary zurück, wird er Replica — Schreibvorgänge, die er während der Netzwerk-Partition akzeptierte, sind VERLOREN (Split-Brain-Risiko).
# force a manual failover (for maintenance)
SENTINEL failover mymaster
# triggers failover: promotes a replica to primary
# the failover process:
# 1. sentinels mark primary SDOWN (subjectively down)
# 2. quorum agrees -> ODOWN (objectively down)
# 3. a sentinel is elected leader
# 4. leader picks the best replica (most up-to-date)
# 5. promotes the replica: REPLICAOF NO ONE
# 6. reconfigures other replicas to follow the new primary
# 7. updates sentinel configs with the new primary address
# 8. clients reconnect via sentinel discovery
# during failover, writes fail briefly (seconds)
# reads from replicas continue (if the app uses them)
# the old primary, when it returns, is reconfigured as a replica
# of the new primary (its writes during partition are lost)
# monitor failover events:
redis-cli -p 26379 SUBSCRIBE +switch-master
redis-cli -p 26379 SUBSCRIBE +failover-*Sentinel-Quorum & Monitoring
Quorum ist die Anzahl der Sentinels, die sich einig sein müssen, dass ein Primary down ist, bevor ein Failover ausgelöst wird — auf die Mehrheit setzen (N/2+1) bei N Sentinels. ckquorum verifiziert, dass genug da sind. down-after-milliseconds sollte > Netzwerk-Jitter sein (30 s sind sicher). failover-timeout begrenzt die Failover-Dauer. parallel-syncs steuert, wie viele Replicas gleichzeitig resynchronisieren (1 = sicher, aber langsam). Sentinels aktualisieren ihre Konfiguration bei Topologieänderungen automatisch.
# quorum: number of sentinels that must agree a master is down
# set in sentinel monitor command:
sentinel monitor mymaster 192.168.1.10 6379 2
# ^ quorum = 2
# for 3 sentinels: quorum = 2 (majority)
# for 5 sentinels: quorum = 3 (majority)
# check quorum status
SENTINEL ckquorum mymaster
# "OK 3 usable Sentinels" or "NOQUORUM"
# tune down-after-milliseconds (time before declaring down)
sentinel down-after-milliseconds mymaster 30000 # 30s default
# tune failover-timeout (max time for failover to complete)
sentinel failover-timeout mymaster 180000 # 3min default
# parallel-syncs: how many replicas resync simultaneously
sentinel parallel-syncs mymaster 1 # 1 at a time (safe, slow)
# view sentinel configuration
SENTINEL masters
SENTINEL master mymaster
# reset a master's state (clears discovered replicas/sentinels)
SENTINEL reset mymaster
# Sentinel automatically updates its config file when topology changesMonitoring
MONITOR-Befehl
MONITOR streamt jeden Befehl jedes Clients in Echtzeit. Das Ausgabeformat ist: Zeitstempel [db client_addr] "command" "args". Unbezahlbar, um zu debuggen, welche Befehle eine App tatsächlich sendet. Aber er halbiert grob den Durchsatz — nur in Staging/Dev oder für kurze Produktionsdebugging nutzen. Mit grep nach Mustern filtern. Für Produktionsmonitoring stattdessen SLOWLOG, INFO commandstats oder LATENCY MONITOR.
# MONITOR: real-time log of ALL commands (debugging only!)
MONITOR
# every command from every client is printed:
# 1700000000.123456 [0 10.0.0.1:12345] "SET" "key" "value"
# 1700000000.123567 [0 10.0.0.1:12345] "GET" "key"
# format: <unix_time> [<db> <addr>] "<cmd>" "<arg>" ...
# the [0 ...] shows which database and client
# to stop monitoring: Ctrl+C or send any command
# filter for specific patterns (in another terminal):
redis-cli MONITOR | grep "SET"
redis-cli MONITOR | grep "10.0.0.1"
redis-cli MONITOR | grep -E "(SET|DEL)"
# WARNING: MONITOR roughly halves throughput
# use only for debugging, never in production
# safer alternatives:
# - SLOWLOG (only slow commands)
# - INFO commandstats (command frequency)
# - LATENCY MONITOR (latency events)LATENCY-Monitoring
LATENCY MONITOR trackt Latenzspitzen pro Event-Typ. Einen Schwellwert setzen (z. B. 100 ms) und Redis zeichnet Events auf, die ihn überschreiten. LATENCY DOCTOR analysiert aktuelle Events und schlägt Fixes vor — ein guter Ausgangspunkt für die Diagnose. LATENCY GRAPH zeigt eine ASCII-Zeitachse. Häufige Übeltäter: 'fork' (BGSAVE bei großen Datensätzen), 'expire-cycle' (Massen-Ablauf), 'aof-fsync-always' (AOF-fsync). Schwellwert auf dein SLO setzen und regelmäßig überwachen.
# enable latency monitoring (threshold in ms)
CONFIG SET latency-monitor-threshold 100 # 100ms
# view recent latency events
LATENCY LATEST
# event, timestamp, last latency, max latency
# history of an event
LATENCY HISTORY command
LATENCY HISTORY expire-cycle
LATENCY HISTORY fork
# ASCII art graph
LATENCY GRAPH command
# human-readable diagnosis and recommendations
LATENCY DOCTOR
# reset latency data
LATENCY RESET
LATENCY RESET command
# common events:
# command slow commands (over threshold)
# fast-command slow O(1)/O(log N) commands
# expire-cycle key expiration sweep too slow
# fork BGSAVE/BGREWRITEAOF fork delay
# aof-fsync-always AOF fsync delay
# unlink async delete delay
# check threshold
CONFIG GET latency-monitor-thresholdMEMORY DOCTOR & STATS
MEMORY USAGE meldet Bytes für einen Schlüssel (SAMPLES 0 für volle Genauigkeit). MEMORY STATS gibt detaillierte Allokator-Statistiken. MEMORY DOCTOR liefert automatisierte Diagnose (achtet auf Fragmentierung, große Schlüssel usw.). mem_fragmentation_ratio beobachten: >1,5 verschwendet Speicher (Fragmentierung), <1 heißt, Redis swapped (katastrophal für die Latenz). MEMORY PURGE versucht, Speicher ans OS zurückzugeben. Aktive Defragmentierung (4.0+) holt fragmentierten Speicher automatisch zurück.
# MEMORY USAGE: bytes used by a single key
MEMORY USAGE mykey
MEMORY USAGE bigset SAMPLES 0 # exact (default samples for large keys)
# MEMORY STATS: detailed allocator stats
MEMORY STATS
# MEMORY DOCTOR: automated memory diagnosis
MEMORY DOCTOR
# MEMORY MALLOC-STATS: low-level allocator stats (jememalloc)
MEMORY MALLOC-STATS
# check total memory used
INFO memory | grep used_memory_human
# key metrics to watch:
# used_memory logical bytes used
# used_memory_rss RSS from OS (real footprint)
# used_memory_peak peak usage
# mem_fragmentation_ratio >1.5 = fragmentation, <1 = swapping (bad!)
# MEMORY PURGE: attempt to free memory back to OS
MEMORY PURGE
# active defragmentation (4.0+)
CONFIG SET activedefrag yesDEBUG-Befehle
DEBUG-Befehle sind für Diagnostik und Tests — vorsichtig verwenden. DEBUG SLEEP testet, wie deine App mit Latenz umgeht (blockiert den Server). DEBUG OBJECT legt die interne Kodierung und den Refcount eines Schlüssels offen. DEBUG RELOAD speichert, leert und lädt den Datensatz neu (praktisch zum Testen der Persistenz). Mächtig, aber gefährlich — in Produktion per ACL einschränken (die Kategorie -@admin oder -@dangerous). DEBUG nie auf einem Produktions-Primary ausführen, ohne die Auswirkung zu verstehen.
# DEBUG SLEEP: block the server for N seconds (testing only!)
DEBUG SLEEP 2 # blocks for 2 seconds (testing latency)
# DEBUG OBJECT: raw internal info about a key
DEBUG OBJECT mykey
# Value at:0x7f... refcount:1 encoding:embstr serializedlength:12 ...
# DEBUG SET-ACTIVE-EXPIRE: toggle expiration sweeps
DEBUG SET-ACTIVE-EXPIRE 0 # disable expiration sweeps (debugging)
DEBUG SET-ACTIVE-EXPIRE 1 # re-enable
# DEBUG JMAP: memory map (jemalloc)
DEBUG JMAP
# DEBUG CHANGE-REPL-ID: change replication ID (advanced)
DEBUG CHANGE-REPL-ID
# DEBUG RELOAD: save RDB, flush, reload from RDB (testing)
DEBUG RELOAD
# DEBUG LOADAOF: reload from AOF (testing)
DEBUG LOADAOF
# WARNING: DEBUG commands can be dangerous
# use ACL to restrict them in production:
# ACL SETUSER default -@adminredis-cli --latency
redis-cli --latency misst kontinuierlich die Round-Trip-Zeit — essenziell, um die Netzwerkperformance als Basislinie festzuhalten. --latency-history loggt rollierende Stats alle 15 s (mit -i ändern). --latency-dist zeigt ein Histogramm (visualisiert Jitter und Endlatenz). Im Cluster-Modus die Latenz zu jedem Knoten getrennt prüfen. Basislinie festlegen, dann auf Spitzen achten. Latenz >1 ms auf localhost deutet auf ein Problem hin (CPU, Speicherdruck oder langsame Befehle).
# continuous latency measurement (round-trip time)
redis-cli --latency
# output: min: 0, max: 1, avg: 0.27 (3421 samples)
# latency history (rolling, every N seconds)
redis-cli --latency-history
# default interval: 15 seconds
# output: min: 0, max: 2, avg: 0.31 (1500 samples) -- 15.01 seconds
# custom interval (1 second)
redis-cli --latency-history -i 1
# latency distribution (histogram)
redis-cli --latency-dist
# shows a visual histogram of latency distribution
# latency to a remote host
redis-cli -h remote-host --latency
# use cases:
# - baseline your network latency
# - detect network issues (jitter, spikes)
# - compare latency before/after config changes
# - monitor latency over time with --latency-history
# for cluster mode, check latency to each node:
redis-cli -h node1 -p 7000 --latency &
redis-cli -h node2 -p 7000 --latency &redis-cli --stat
redis-cli --stat ist wie 'top' für Redis — er zeigt eine sich auffrischende Zusammenfassung von Schlüsseln, Speicher, Clients, blockierten Clients, Requests/s und Verbindungen. Das (+N) neben den Requests zeigt das Delta seit der letzten Stichprobe. Für schnelle Health-Checks nutzen und Anomalien zu erkennen (wachsender Speicher, leckende Clients, aufflackernde Requestrate). Die 'child'-Spalte zeigt, ob ein BGSAVE-/BGREWRITEAOF-Kind läuft.
# --stat: continuous server stats (like top for Redis)
redis-cli --stat
# output (refreshes every second):
# ------- data ------ --------------------- load -------------------- - child -
# keys mem clients blocked requests connections
# 1000 1.50M 50 0 12345 (+12) 1000
# --stat shows:
# keys total keys in the db
# mem memory usage
# clients connected clients
# blocked blocked clients (BLPOP, etc.)
# requests total requests (+N since last sample)
# connections total connections since start
# child child process info (BGSAVE/BGREWRITEAOF)
# custom interval (every 5 seconds)
redis-cli --stat -i 5
# monitor a remote server
redis-cli -h host --stat
# use cases:
# - quick health check (are clients/memory/keys growing?)
# - spot traffic spikes (requests/second)
# - monitor during load tests
# - detect connection leaks (clients increasing steadily)
# combine with --no-raw for machine-readable outputSicherheit
AUTH (Legacy-Passwort)
AUTH ist die Legacy-Ein-Passwort-Authentifizierung (vor Redis 6). In Redis 6+ ACL-Nutzer nutzen (AUTH username password). Das Flag -a legt das Passwort in der Shell-History offen — die Umgebungsvariable REDISCLI_AUTH bevorzugen. Immer starke Passwörter (64+ zufällige Zeichen). In Produktion AUTH mit TLS, Netzwerkbeschränkungen (bind/firewall) und ACL-basiertem Least Privilege für Defense in Depth kombinieren.
# set a password (simple, legacy)
CONFIG SET requirepass "strongpassword"
# authenticate (legacy, before Redis 6)
AUTH "strongpassword"
# OK
# authenticate as a specific user (Redis 6+ ACL)
AUTH appuser "secretpassword"
# OK
# connect with password via CLI
redis-cli -a "strongpassword"
redis-cli -a "strongpassword" --no-auth-warning # suppress warning
# safer: use environment variable
export REDISCLI_AUTH="strongpassword"
redis-cli # reads REDISCLI_AUTH automatically
# remove password
CONFIG SET requirepass ""
# AUTH returns ERR if the password is wrong
# after AUTH, all commands work normallyACL SETUSER
Redis-6+-ACLs ersetzen das Ein-Passwort-Modell — Nutzer mit eingeschränkten Rechten erzeugen. Die Syntax: on (aktiviert), >passwort, ~muster (Schlüsselmuster), +befehl/-befehl, +@kategorie/-@kategorie (z. B. +@read, -@dangerous). Für jede App immer einen Least-Privilege-Nutzer erzeugen. Der Standard-Nutzer existiert immer — ein starkes Passwort setzen oder ihn einschränken. ACLs in eine Datei speichern (ACL SAVE) für Persistenz.
# Redis 6+: ACL system with users and permissions
# create a user with limited access
ACL SETUSER appuser on >secretpassword ~app:* +get +set +del -@dangerous
# on = enabled
# >password = set password
# ~pattern = key patterns this user can access
# +command = allowed commands
# -command = denied commands
# +@category / -@category = allow/deny command categories
# categories: @read, @write, @admin, @dangerous, @keyspace, @connection, etc.
# create a read-only user
ACL SETUSER readonly on >pass ~* +@read -@dangerous
# create an admin user
ACL SETUSER admin on >adminpass ~* +@all
# create a user for a specific app (restricted keys)
ACL SETUSER app1 on >pass ~app1:* +@read +@write +@connection -@dangerous
# the default user (always exists)
ACL SETUSER default on >defaultpass ~* +@all -@dangerousACL LIST & GETUSER
ACL LIST zeigt alle Nutzer im kompakten Regel-Format. ACL GETUSER gibt detaillierte Berechtigungen für einen Nutzer (inklusive gehashter Passwörter, erlaubter/verbotener Befehle, Schlüsselmuster). ACL WHOAMI liefert den aktuellen Nutzer. ACL LOG (7.0+) zeichnet abgewiesene Befehle und Auth-Fehlschläge auf — nützlich fürs Sicherheits-Auditing. ACL SAVE/LOAD verwalten die ACL-Datei für Persistenz über Neustarts hinweg.
# list all users (compact rules)
ACL LIST
# 1) "user default on nopass ~* +@all"
# 2) "user appuser on #abc123... ~app:* +get +set +del -@dangerous"
# view a user's detailed permissions
ACL GETUSER appuser
# flags, passwords, commands, keys, channels, selectors
# view current user
ACL WHOAMI
# "appuser"
# view all users (just names, 7.0+)
ACL USERS
# delete a user
ACL DELUSER appuser
# save ACLs to a file (persists across restarts)
ACL SAVE
# reload ACLs from file
ACL LOAD
# aclfile in redis.conf:
# aclfile /etc/redis/users.acl
# view current user's rules
ACL LOG # security audit log (7.0+)
ACL LOG RESET # clear the audit logACL WHOAMI & DELUSER
ACL WHOAMI identifiziert den aktuellen Nutzer. ACL DELUSER entfernt einen Nutzer (und trennt seine aktiven Verbindungen). Einen Nutzer auf 'off' zu setzen deaktiviert ihn temporär, ohne seine Regeln zu löschen — nützlich, um Zugang auszusetzen. ACL LOG zeichnet Sicherheits-Events auf (abgewiesene Befehle, gescheiterte Auth) — auf verdächtige Aktivität überwachen. Passwörter regelmäßig mit ACL SETUSER >newpass rotieren.
# get the current authenticated user
ACL WHOAMI
# "appuser"
# switch user (re-authenticate)
AUTH adminuser "adminpass"
ACL WHOAMI
# "adminuser"
# delete a user (disconnects their clients)
ACL DELUSER tempuser
# temporarily disable a user (keeps the rules, blocks login)
ACL SETUSER appuser off
# the user cannot authenticate, but their rules are preserved
# re-enable:
ACL SETUSER appuser on
# rotate a user's password
ACL SETUSER appuser >newpassword
# remove a user's password
ACL SETUSER appuser <secretpassword # remove this password
# or remove all passwords:
ACL SETUSER appuser resetpass
# view the audit log (denied commands, auth failures)
ACL LOG
ACL LOG COUNT 5 # last 5 entries
ACL LOG RESET # clear the logrename-command (Befehle deaktivieren)
rename-command (in redis.conf) deaktiviert oder benennt gefährliche Befehle um — "" zum Deaktivieren oder ein String zum Umbenennen. Er verlangt einen Neustart (nicht zur Laufzeit änderbar). In Redis 6+ ACLs bevorzugen (-flushall, -@dangerous), die zur Laufzeit änderbar und nutzerbezogen sind. Befehle, die man einschränken sollte: FLUSHALL/FLUSHDB (Datenverlust), KEYS (blockiert den Server), CONFIG (Sicherheit), DEBUG (kann crashen), SHUTDOWN (stoppt den Server).
# rename or disable dangerous commands (in redis.conf)
rename-command FLUSHALL ""
rename-command FLUSHDB ""
rename-command CONFIG "CONFIG_9f8a7b"
rename-command KEYS ""
rename-command DEBUG ""
rename-command SHUTDOWN "SHUTDOWN_7x9y"
# "" completely disables the command (returns error)
# a string renames it (must use the new name)
# Redis 6+: prefer ACLs instead of rename-command
# ACL SETUSER default -flushall -config -keys -@dangerous
# view available commands (after rename/restrictions)
COMMAND
# note: rename-command requires a restart (not changeable at runtime)
# ACLs are runtime-changeable and more flexible
# dangerous commands to restrict:
# FLUSHALL, FLUSHDB - delete all data
# KEYS - blocks server
# CONFIG - can change security settings
# DEBUG - can crash the server
# SHUTDOWN - stops the server
# MONITOR - performance impactTLS/SSL-Verschlüsselung
TLS verschlüsselt Daten bei der Übertragung — in Produktion essenziell, besonders über unvertraute Netzwerke. Redis 6+ unterstützt TLS nativ. mTLS (tls-auth-clients yes) verlangt von Clients ein Zertifikat und liefert gegenseitige Authentifizierung ohne Passwörter. Für Cluster/Sentinel TLS auch für die Knotenkommunikation aktivieren. Port 0 deaktiviert Klartext; während der Migration beide Ports temporär laufen lassen. In Produktion immer ordentliche CA-signierte Zertifikate verwenden.
# enable TLS in redis.conf (Redis 6+)
port 0 # disable plain-text port
tls-port 6379
tls-cert-file /etc/redis/redis.crt
tls-key-file /etc/redis/redis.key
tls-ca-cert-file /etc/redis/ca.crt
# connect with TLS
redis-cli --tls --cert client.crt --key client.key \
--cacert ca.crt -h host -p 6379
# mutual TLS (mTLS) for client authentication
tls-auth-clients yes # require client certs
tls-auth-clients no # don't require (default)
tls-auth-clients optional # verify if provided
# TLS for cluster and replication
tls-cluster yes # TLS between cluster nodes
tls-replication yes # TLS between primary/replica
# mix TLS and plain text (transition period)
# port 6380
# tls-port 6379
# generate self-signed certs for testing:
# openssl req -x509 -newkey rsa:4096 -keyout redis.key \
# -out redis.crt -days 365 -nodesDatenimport & -export
redis-cli --rdb (Backup)
redis-cli --rdb macht ein Online-Backup — er streamt die RDB in eine Datei, ohne das Server-Dateisystem direkt anzufassen. Er ist nicht-blockierend (nutzt BGSAVEs Hintergrund-Fork) und produktionsfähig. Kombiniert mit SSH lässt sich ein entferntes Redis auf eine lokale Datei sichern. Backups mit redis-check-rdb verifizieren. Regelmäßige Backups via cron einplanen. Wiederherstellungsverfahren immer testen — ein ungetestetes Backup ist kein Backup.
# dump the RDB snapshot to a file (online backup)
redis-cli --rdb /backup/dump.rdb
# Output: RDB file written to /backup/dump.rdb
# dump RDB to a remote host's file (via SSH):
ssh remote-host "redis-cli --rdb /tmp/dump.rdb"
# the --rdb flag:
# - connects to Redis and requests a BGSAVE
# - streams the RDB to the specified file
# - non-blocking (uses the background fork)
# - safe to run on a production server
# verify the RDB file
redis-check-rdb /backup/dump.rdb
# restore: stop Redis, replace dump.rdb, restart
redis-cli SHUTDOWN
cp /backup/dump.rdb /var/lib/redis/dump.rdb
redis-server /etc/redis/redis.conf
# schedule regular backups:
# 0 2 * * * redis-cli --rdb /backup/dump-$(date +\%F).rdbredis-cli --pipe (Massen-Insert)
redis-cli --pipe ist der schnellste Weg, Daten im Bulk in Redis zu laden — er streamt rohes RESP und wartet erst am Ende auf Antworten. RESP mit printf oder einem Skript erzeugen. --pipe meldet Fehler und Gesamtantworten. Für einfachere/kleinere Lasten funktioniert das Piping von Textbefehlen (echo | redis-cli), ist aber langsamer. Immer benchmarken: --pipe kann Millionen Schlüssel in Minuten laden. Bei großen Lasten den Speicher im Auge behalten.
# --pipe: bulk load raw RESP data (fastest method)
# generate RESP and pipe it:
# example: bulk SET commands (bash)
for i in $(seq 1 100000); do
printf '*3\r\n$3\r\nSET\r\n$%d\r\nkey:%d\r\n$%d\r\nvalue%d\r\n' \
$((4 + ${#i})) $i $((5 + ${#i})) $i
done | redis-cli --pipe
# simpler text mode (slower but easier):
for i in $(seq 1 100000); do
echo "SET key:$i value$i"
done | redis-cli
# --pipe mode output:
# All data transferred. Waiting for the last reply...
# Last reply received from server.
# errors: 0, replies: 100000
# prepare RESP from a CSV/data file:
# (each line: key,value)
while IFS=, read -r key value; do
printf '*3\r\n$3\r\nSET\r\n$%d\r\n%s\r\n$%d\r\n%s\r\n' \
${#key} "$key" ${#value} "$value"
done < data.csv | redis-cli --pipeDUMP & RESTORE
DUMP serialisiert den Wert eines Schlüssels in einen Binär-Blob (enthält Typ und Wert, aber keine TTL — TTL bei RESTORE in Millisekunden angeben). RESTORE deserialisiert ihn in einen Schlüssel und funktioniert über verschiedene Redis-Instanzen hinweg (super für Migrationen). Das serialisierte Format ist versionsabhängig — ein Blob aus Redis 4.x lädt evtl. nicht in 7.x; Kompatibilität immer verifizieren. Für Kopien innerhalb einer Instanz den nativen COPY-Befehl (6.2+) statt DUMP+RESTORE bevorzugen.
# DUMP: serialize a key's value (binary blob)
DUMP mykey
# returns a serialized blob (binary, includes type + value + TTL info)
# RESTORE: deserialize into a key
RESTORE newkey 0 <serialized_blob>
# 0 = no TTL (milliseconds); set a TTL otherwise
RESTORE newkey 3600000 <blob> # 1 hour TTL
RESTORE newkey 0 <blob> REPLACE # overwrite if exists
# copy a key (6.2+ does this natively with COPY)
# manual copy via DUMP + RESTORE:
SET source "value"
blob = DUMP source
RESTORE dest 0 blob
# DUMP/RESTORE preserve the type but NOT the TTL
# (TTL must be specified in RESTORE)
# DUMP/RESTORE work across different Redis instances
# (migrate data between servers)
# note: serialized format is version-specific
# a blob from Redis 4.x may not load in 7.x — verify compatibility
# use COPY (6.2+) instead for in-instance copies:
COPY source dest # copy without TTL
COPY source dest REPLACE # overwrite destination
COPY source dest DB 1 # copy to another database
COPY source dest REPLACE DB 1 # bothMIGRATE (zwischen Servern bewegen)
MIGRATE bewegt (oder kopiert) einen Schlüssel atomar zwischen Redis-Instanzen — der Schlüssel ist nie an beiden Orten zugleich (atomar). Er ist der Baustein des Cluster-Reshardings. COPY behält den Quellschlüssel; Standard löscht ihn. REPLACE überschreibt einen bestehenden Zielschlüssel. Für mehrere Schlüssel als Schlüssel einen leeren String übergeben und sie mit KEYS listen. Das Timeout hoch genug für große Werte setzen. MIGRATE blockiert beide Enden während des Transfers.
# MIGRATE: atomically move a key from one Redis to another
# syntax: MIGRATE host port key|"" dest-db timeout [COPY] [REPLACE]
# [AUTH password] [KEYS key1 key2 ...]
# move a single key (default: deletes from source after copy)
MIGRATE 192.168.1.20 6379 mykey 0 5000
# host, port, key, dest-db, timeout-ms
# copy without deleting from source
MIGRATE 192.168.1.20 6379 mykey 0 5000 COPY
# overwrite if the key exists on destination
MIGRATE 192.168.1.20 6379 mykey 0 5000 REPLACE
# migrate multiple keys (pass "" as the key, then KEYS ...)
MIGRATE 192.168.1.20 6379 "" 0 5000 KEYS key1 key2 key3
# authenticate with the destination
MIGRATE 192.168.1.20 6379 mykey 0 5000 AUTH destpassword
# MIGRATE is atomic: the key appears on exactly one instance at any moment
# timeout is in milliseconds — large keys need longer timeouts
# returns NOKEY if the key doesn't exist on sourceCOPY (Kopie in der Instanz)
COPY (6.2+) dupliziert einen Schlüssel innerhalb derselben Instanz atomar — viel einfacher als DUMP+RESTORE. Er kopiert die TTL standardmäßig NICHT (danach EXPIRE setzen). COPY funktioniert mit der DB-Option datenbankübergreifend. REPLACE überschreibt ein bestehendes Ziel. Für instanzübergreifende Kopien MIGRATE nutzen (atomar über das Netzwerk). COPY ist der moderne Ersatz für das DUMP+RESTORE-Muster zur Duplizierung innerhalb der Instanz.
# COPY: duplicate a key within the same instance (6.2+)
COPY source dest # copy value (no TTL by default)
COPY source dest REPLACE # overwrite destination if it exists
COPY source dest DB 1 # copy to another database
COPY source dest REPLACE DB 1 # both options
# before COPY existed, you needed DUMP + RESTORE:
SET src "hello"
blob = DUMP src
RESTORE dst 0 blob
# COPY preserves the type (string, list, hash, ...)
SET mystr "hello"
COPY mystr mystr_copy
TYPE mystr_copy # "string"
# COPY does NOT copy TTL by default — use after EXPIRE if needed
SET temp "data" EX 3600
COPY temp temp_copy
TTL temp_copy # -1 (no TTL)
EXPIRE temp_copy 3600 # set TTL manually
# COPY is atomic and never blocks (unlike DUMP on huge keys)redis-check-rdb & redis-check-aof
redis-check-rdb und redis-check-aof verifizieren die Integrität der Persistenzdateien — vor jedem Restore auf Backups ausführen. redis-check-aof --fix erholt sich von einer abgeschnittenen AOF, indem es den unvollständigen Schwanz entfernt (fragt nach Bestätigung). Redis 7 nutzt eine mehrteilige AOF (Basis + Inkremente) — die Manifest-Datei prüfen. Diese Tools sind außer --fix read-only, also jederzeit sicher ausführbar. Backups gewissenhaft validieren — ein unverifiziertes Backup ist kein Backup.
# verify the integrity of an RDB file (offline, safe)
redis-check-rdb /var/lib/redis/dump.rdb
# outputs: [offset] Checksum OK | CRC error | file truncated
# verify an AOF file
redis-check-aof /var/lib/redis/appendonly.aof
# outputs: AOF analyzed: size=... ok_up_to=... ok_up_to_line=...
# fix a truncated AOF (interactive prompt)
redis-check-aof --fix /var/lib/redis/appendonly.aof
# Redis 7 multi-part AOF: check the manifest
redis-check-aof --manifest /var/lib/redis/appendonlydir/appendonly.aof.manifest
# truncate an RDB to a specific offset (recovery)
redis-check-rdb --fix /var/lib/redis/dump.rdb
# use cases:
# - verify a backup before restore
# - diagnose corruption after a crash
# - recover from a truncated AOF (removes the incomplete tail)
# - validate files copied across servers
# always run these checks BEFORE replacing production data filesPerformance-Tests
redis-benchmark-Grundlagen
redis-benchmark ist Redis' eingebautes Lasttest-Werkzeug — er simuliert gleichzeitige Clients und meldet Durchsatz (Requests/s) und Latenzperzentile. -t wählt Tests (PING, SET, GET, INCR usw.); -n setzt die Request-Anzahl; -d die Payload-Größe. Immer auf produktionsäquivalenter Hardware benchmarken, um die Performance als Basislinie festzuhalten. Die 50 Standard-Parallelclients sind ein Startpunkt — -c an die echte Workload anpassen. Benchmarks vor und nach Config-Änderungen ausführen, um die Auswirkung zu messen.
# redis-benchmark: built-in performance benchmarking tool
# runs commands against a Redis server and reports throughput/latency
# default benchmark (50 parallel clients, 100000 requests)
redis-benchmark
# default commands: PING, SET, GET, INCR, LPUSH, RPUSH, LPOP, RPOP,
# SADD, HSET, SPOP, ZADD, ZPOPMIN, LRANGE_100, LRANGE_300, ...
# run a specific command only
redis-benchmark -t set,get -n 100000
# -t = test (comma-separated commands)
# -n = number of requests
# test a specific command with custom data
redis-benchmark -t set -n 100000 -d 100
# -d = data size in bytes (default 3)
# output example:
# ====== SET ======
# 100000 requests completed in 0.85 seconds
# 50 parallel clients
# 3 bytes payload
# keep alive: 1
# 98.90% <= 1 milliseconds
# 100.00% <= 1 milliseconds
# 117647.05 requests per second
# run against a remote server with auth
redis-benchmark -h host -p 6379 -a password -t set,get -n 100000Pipeline- & Nebenläufigkeits-Tuning
Die zwei größten Durchsatzhebel sind -c (Nebenläufigkeit) und -P (Pipeline-Größe). -c erhöht die parallelen Clients (mehr laufende Requests); -P bündelt Befehle pro Round-Trip (weniger Netzwerk-Overhead). Kombiniert pushen sie den Durchsatz um Faktor 10-20. Single-Client-Benchmarks (-c 1) messen pure Latenz; Multi-Client-Benchmarks messen Durchsatz. Größere Payloads (-d) verschieben den Flaschenhals auf die Netzwerkbandbreite. -c/-P immer an das Verhalten deiner echten Client-Bibliothek anpassen.
# -c = number of parallel connections (clients)
redis-benchmark -t set -n 100000 -c 50 # default: 50 clients
redis-benchmark -t set -n 100000 -c 200 # 200 concurrent clients
redis-benchmark -t set -n 100000 -c 1 # single client (latency focus)
# -P = pipeline size (commands per round-trip)
redis-benchmark -t set -n 100000 -P 1 # no pipelining (baseline)
redis-benchmark -t set -n 100000 -P 16 # pipeline 16 commands
redis-benchmark -t set -n 100000 -P 100 # pipeline 100 commands
# combine -c and -P for max throughput
redis-benchmark -t set -n 100000 -c 50 -P 16
# typical results (localhost, small values):
# -c 1 -P 1 -> ~100k req/s (latency-bound)
# -c 50 -P 1 -> ~600k req/s (concurrency)
# -c 50 -P 16 -> ~2M req/s (pipelining)
# test with a larger payload (network-bound)
redis-benchmark -t set -n 100000 -d 1024 # 1KB values
redis-benchmark -t set -n 100000 -d 65536 # 64KB valuesLatenzperzentile & CSV-Ausgabe
Immer die Latenzperzentile ansehen (P50, P99, P99.9), nicht nur Durchschnitte — Durchschnitte verstecken Endlatenzspitzen, die die Nutzererfahrung schädigen. Ein P99 5x schlechter als P50 deutet auf Jitter hin (GC, Netzwerk oder langsame Befehle). --csv liefert maschinenlesbare Ergebnisse, um Trends über die Zeit zu tracken. Benchmarks vor und nach Config-Änderungen speichern, um die Auswirkung objektiv zu messen. P99-Latenz und Requests/s gemeinsam tracken — das eine auf Kosten des anderen zu optimieren ist eine übliche Falle.
# --csv: CSV output (easy to parse / log)
redis-benchmark -t set,get -n 100000 --csv
# output: "test","rps","avg_latency_ms","min_latency_ms",...
# "SET","117647.05","0.284","0.144"
# "GET","125000.00","0.272","0.136"
# --precision: set decimal places for latency
redis-benchmark -t set -n 100000 --precision 4
# latency percentiles (Redis 6+):
# the default output shows "X% <= Y milliseconds" lines
# ====== SET ======
# 50.00% <= 0.239 milliseconds
# 99.00% <= 0.511 milliseconds
# 99.90% <= 1.023 milliseconds
# 100.00% <= 1.519 milliseconds
# focus on tail latency (P99, P99.9) — average hides outliers
# P99 > 5x P50 indicates jitter or GC pauses
# save results to a file for comparison
redis-benchmark -t set,get -n 100000 --csv > bench-$(date +%F).csv
# compare two runs (before/after a config change)
diff bench-2025-01-01.csv bench-2025-01-02.csvCluster- & Lua-Benchmarking
--cluster-Modus verteilt Schlüssel über Cluster-Slots — essenziell für realistische Cluster-Benchmarks (Single-Node-Benchmarks verpassen den Cross-Slot-Routing-Overhead). -r setzt die zufällige Keyspace-Größe (einen großen Wert nutzen, damit nicht alle Ops einen Schlüssel treffen, was die Zahlen durch In-Memory-Caching aufbläht). --eval benchmarket Lua-Skripte. --threads (Redis 6+) nutzt mehrere Benchmark-Threads — nützlich, wenn ein einzelner Thread nicht genug Last erzeugen kann, um den Server zu sättigen. Für realistische Zahlen immer -r verwenden.
# benchmark a Redis Cluster (redis-benchmark supports cluster mode)
redis-benchmark --cluster -h node1 -p 7000 -t set,get -n 100000
# automatically distributes keys across cluster slots
# cluster mode with multiple nodes
redis-benchmark --cluster -h node1 -p 7000 -h node2 -p 7000 \
-t set,get -n 100000 -c 50
# benchmark a Lua script (--eval)
redis-benchmark -n 100000 eval "return redis.call('SET', KEYS[1], ARGV[1])" 0 mykey hello
# note: key and args are positional after the script
# benchmark with random keys (--random-data + keyspace length)
redis-benchmark -t set -n 100000 -r 1000000
# -r 1000000 = random keys from a 1M keyspace (SET key:RAND_INT value)
# avoids hitting the same key (tests real-world distribution)
# use a random payload (not the same bytes each time)
redis-benchmark -t set -n 100000 -r 1000000 -d 100 --random-data
# only run the benchmark for a fixed time (seconds)
redis-benchmark -t set --threads 4 -n 100000
# --threads (6+) uses multiple threads (default 1, doesn't help single-core)--idle & Warmup
--idle misst pure Verbindungs-/Netzwerk-Overhead nur mit PINGs — die Basislinie, die man nicht schlagen kann. Den Server vor dem Messen immer aufwärmen (kalte Caches unterschätzen die Performance): zuerst einen Wegwerf-Benchmark laufen lassen, dann den gemessenen. --loop läuft fortlaufend (nützlich für Dauerspannungstests). --seed macht den zufälligen Keyspace reproduzierbar — essenziell für A/B-Vergleiche. --dbnum wählt die Datenbank (eine separate db nutzen, um Produktionsdaten bei Benchmarks nicht zu verschmutzen).
# --idle: only send PINGs (no commands) — measure pure connection overhead
redis-benchmark -t ping -n 100000 --idle
# useful for measuring connection / network baseline latency
# --dbnum: select a specific database
redis-benchmark -t set -n 100000 --dbnum 1
# --clients: same as -c (alias)
redis-benchmark -t set -n 100000 --clients 100
# warm up the server before measuring (avoid cold-start bias)
redis-benchmark -t set -n 10000 # warmup run (discard results)
redis-benchmark -t set -n 100000 # measured run
# --loop: run the benchmark forever (Ctrl+C to stop)
redis-benchmark -t set -n 100000 --loop
# --seed: reproducible random keys (same -r sequence every run)
redis-benchmark -t set -n 100000 -r 1000000 --seed 42
# benchmark with a specific client socket buffer
redis-benchmark -t set -n 100000 --numdatadb 1Benchmark-Interpretation & Fallstricke
Benchmark-Fallstricke blähen Zahlen unrealistisch auf: (1) localhost-only-Benchmarks verpassen die Netzwerklatenz; (2) ohne -r treffen alle Ops einen Schlüssel (durch Caching aufgebläht); (3) winzige Payloads belasten Speicher/Netzwerk nicht; (4) Persistenz-Overhead ignorieren (AOF-fsync kann den Durchsatz um Faktor 2-5 senken); (5) ein einzelner Benchmark-Thread kann einen Multi-Core-Server nicht sättigen. Ein realistischer Benchmark nutzt -r (zufällige Schlüssel), -d (realistische Payload), --threads (multithreaded Client) und testet mit produktionsäquivalenter Persistenz und Netzwerk. Beim Teilen von Zahlen immer die Benchmark-Parameter offenlegen.
# COMMON PITFALL #1: benchmarking localhost only
# localhost numbers don't reflect real network latency
# always test over your production network path
# COMMON PITFALL #2: all keys the same (no -r)
# redis-benchmark -t set -n 100000
# -> all SETs hit "key:0" — inflated by in-memory caching
# FIX: use -r to randomize keys
redis-benchmark -t set -n 100000 -r 1000000
# COMMON PITFALL #3: tiny payloads only
# 3-byte values don't reflect real memory/network pressure
# test with realistic sizes
redis-benchmark -t set -n 100000 -d 256 -r 1000000
# COMMON PITFALL #4: ignoring persistence overhead
# benchmark with AOF on vs off to see the durability cost:
redis-benchmark -t set -n 100000 # with current persistence settings
# (then) CONFIG SET appendonly no
redis-benchmark -t set -n 100000 # without AOF — compare
# COMMON PITFALL #5: single-threaded benchmark client
# one benchmark thread may not generate enough load
redis-benchmark -t set -n 100000 --threads 4 -c 100
# GOOD BENCHMARK (realistic):
redis-benchmark -t set,get -n 1000000 -c 50 -P 16 -r 1000000 -d 100 --threads 4 --csvVerwandte Redis CLI-Snippets
Copy-paste ready code for common tasks.
Verbindung: URLs, TLS, AUTH & SELECT
Verbindung zu Standalone-, TLS-, authentifizierten oder Nicht-Standard-DB-Indizes.
Interaktiver Modus, HELP & Inspektion
Im REPL navigieren, Befehle entdecken und den Server introspektieren.
MULTI / EXEC / WATCH (Transaktionen)
Befehle atomar einreihen und optimistisches Sperren mit WATCH nutzen.
Pub/Sub: SUBSCRIBE, PUBLISH & PSUBSCRIBE
Fan-out-Messaging mit Kanälen und Musterabonnements.
MONITOR, SLOWLOG & Latenz-Debugging
Jeden Befehl in Echtzeit beobachten und langsame Abfragen finden.
EVAL, Lua & Function-Statistiken (Serverseitiges Scripting)
Atomare serverseitige Lua-Skripte ausführen; Funktionen laden und aufrufen.
RDB / AOF-Persistenz & Backup
Snapshots auslösen, AOF-Rewrite verwalten und ein sicheres Backup erstellen.
ACL-Benutzer & Cluster-Operationen
ACL-Benutzer, redis-check-Tools und Cluster-Resharding verwalten.
Was this helpful?