Skip to content

Redis Spickzettel

In-Memory-Datenstruktur-Speicher, genutzt als Datenbank, Cache und Message Broker.

01

Erste Schritte

Mit Redis verbinden

redis-cli ist der Standard-Befehlszeilen-Client. PING testet die Konnektivität (liefert PONG). In Produktion immer den AUTH-Befehl oder das Flag -a verwenden. Passwörter in geteilten Umgebungen nicht auf die Befehlszeile legen — stattdessen die Umgebungsvariable REDISCLI_AUTH nutzen. Modernes Redis (6+) unterstützt ACL-basierte Nutzer mit eingeschränkten Rechten.

redis
# connect to a local server (default port 6379)
redis-cli

# connect with a specific host and port
redis-cli -h host.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

# test the connection
PING          # returns PONG
PING "hello"  # returns "hello"

Datenbankwahl & Grundlagen

Redis-Datenbanken sind logische Namensräume (nummeriert 0-15), keine isolierten Schemas — sie teilen sich denselben Speicher. Die meisten Anwendungen nutzen nur db 0. FLUSHDB leert die aktuelle db; FLUSHALL leert alles. Mehrere Datenbanken sind unüblich; separate Redis-Instanzen oder Schlüsselpräfixe bevorzugen, da sie sich einen Thread teilen und nicht individuell konfigurierbar sind.

redis
# 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

# get basic server info
INFO server
INFO memory
INFO replication

Schlüssel & allgemeine Operationen

KEYS blockiert den Server beim Scannen — in Produktion bei großen Datensätzen nie verwenden; stattdessen SCAN (cursorbasiert, nicht-blockierend). Schlüssel mit Doppelpunkten strukturieren (user:1:profile) für Lesbarkeit. EX setzt Ablauf in Sekunden; PX in Millisekunden. TYPE liefert die Datenstruktur (string, list, hash, set, zset, stream).

redis
# set and get a key
SET user:1 "Alice"
GET user:1

# check if a key exists
EXISTS user:1          # 1 if exists, 0 if not

# delete keys
DEL user:1
DEL key1 key2 key3     # returns number deleted

# set a key with expiration (seconds)
SET session:abc "data" EX 3600

# find keys matching a pattern (avoid in production)
KEYS user:*
SCAN 0 MATCH user:* COUNT 100   # safer iteration

# rename a key
RENAME oldkey newkey

# get the type of a value stored at a key
TYPE user:1

Ablauf & TTL

TTL liefert -2 für nicht existierende Schlüssel und -1 für Schlüssel ohne Ablauf. Expiration ist lazy — Redis prüft nur beim Zugriff auf den Schlüssel oder während periodischer Hintergrund-Sweeps. SET mit EX ist atomar (keine Race zwischen SET und EXPIRE). Abgelaufene Schlüssel lösen standardmäßig keine Events aus; Keyspace-Notifications aktivieren, wenn du sie brauchst.

redis
# set expiration on an existing key
EXPIRE user:1 60        # 60 seconds
EXPIREAT user:1 1700000000  # Unix timestamp

# set expiration in milliseconds
PEXPIRE user:1 60000

# view remaining time to live (seconds)
TTL user:1              # -2 if no key, -1 if no expiry

# view TTL in milliseconds
PTTL user:1

# remove expiration (make key persistent)
PERSIST user:1

# set value AND expiration atomically
SET token "abc" EX 3600

SCAN & sichere Iteration

SCAN ist die produktionsfähige Alternative zu KEYS — er liefert einen Cursor, dem du bis 0 folgst. COUNT ist ein Hinweis, nicht exakt (er kann mehr oder weniger liefern). SCAN bietet schwache Garantien: Er kann Duplikate liefern oder Schlüssel verpassen, die während der Iteration ergänzt wurden, blockiert aber nie. Für Collection-Typen HSCAN/SSCAN/ZSCAN nutzen. Die Cursor-Schleife immer im eigenen Code behandeln.

redis
# SCAN: cursor-based iteration (non-blocking)
SCAN 0 MATCH user:* COUNT 100
# returns: [nextCursor, [key1, key2, ...]]
SCAN <nextCursor> MATCH user:* COUNT 100
# continue until cursor returns to 0

# scan a specific type
SCAN 0 TYPE hash

# HSCAN: iterate hash fields
HSCAN myhash 0 MATCH field* COUNT 100

# SSCAN: iterate set members
SSCAN myset 0 MATCH member* COUNT 100

# ZSCAN: iterate sorted set members
ZSCAN myzset 0 MATCH member* COUNT 100
02

Datentypen-Übersicht

Kern-Datenstrukturen

Die richtige Datenstruktur zu wählen ist die Kernkompetenz in Redis. Strings für Zähler/Caches, Hashes für Objekte, Listen für Queues, Sets für Eindeutigkeit/Tags, Sorted Sets für Leaderboards/Rangierungen, Streams für Event-Logs. Jede Operation auf einer Datenstruktur ist atomar — gleichzeitige Clients können den Zustand nicht korrumpieren. Die Struktur wählen, die zum Zugriffsmuster passt.

redis
# Redis is a data structure server, not just a key-value store
# Each key holds a typed data structure:

# String: binary-safe blob (up to 512MB)
SET key "value"
SET counter 100

# List: ordered, linked-list of strings
LPUSH mylist "a" "b"
RPUSH mylist "c"

# Hash: field-value map (like a small object)
HSET user:1 name "Alice" age 30

# Set: unordered collection of unique strings
SADD tags "redis" "db"

# Sorted Set (ZSet): set scored by a float
ZADD leaderboard 100 "alice" 200 "bob"

# Stream: append-only log with IDs
XADD mystream * field value

# Bitmap, HyperLogLog, Geo: built on strings/zsets

Den richtigen Typ wählen

Den Typ nach Zugriffsmuster wählen: Eindeutigkeit nötig? Set. Ordnung nach Score? Sorted Set. Ein Feld eines Objekts aktualisieren? Hash (nicht ein serialisierter String). Ungefähre eindeutige Zählungen bei Skala? HyperLogLog (12 KB für Milliarden von Items). Die richtige Typwahl = einfacherer Code, atomare Operationen und dramatische Speicherersparnis.

redis
# Use case -> data type mapping:
# Cache a string  -> String
SET api:response "json_blob"

# Store an object -> Hash (one key, multiple fields)
HSET user:1 name "Alice" email "[email protected]" age 30

# Queue / stack   -> List
LPUSH tasks "job1"   # push to head
RPOP tasks           # pop from tail (FIFO queue)

# Unique tags      -> Set
SADD post:1:tags "redis" "db" "cache"

# Leaderboard      -> Sorted Set
ZADD scores 100 "alice" 250 "bob"
ZREVRANGE scores 0 9     # top 10

# Event log        -> Stream
XADD events * type click user 1

# Count unique     -> HyperLogLog (approximate, fixed memory)
PFADD visitors "user1" "user2"

Speicherkodierung

Redis nutzt kompakte Kodierungen (listpack, intset) für kleine Strukturen — 5-10x Speicherersparnis — und wechselt automatisch zu Hash-Tabellen/Skiplists, wenn sie wachsen. OBJECT ENCODING legt die aktuelle Kodierung offen. MEMORY USAGE meldet Bytes. Der Schwellwert lässt sich tunen (z. B. hash-max-listpack-entries), aber die Defaults sind gut gewählt. Kodierungen zu verstehen hilft bei der Kapazitätsplanung.

redis
# Redis optimizes storage based on size
# Inspect the internal encoding of a key
OBJECT ENCODING mykey

# String encodings:
#   "embstr"  - short strings (< 44 bytes)
#   "raw"     - long strings
#   "int"     - integer values

# Hash/List/Set/ZSet encodings:
#   "listpack" / "intset" - small (compact, memory-efficient)
#   "hashtable" / "list" / "skiplist" - large (faster, more memory)

# check memory usage of a key
MEMORY USAGE mykey

# sample memory usage stats
MEMORY STATS

# the encoding changes automatically as the structure grows

OBJECT & Speicherbefehle

OBJECT IDLETIME ist nützlich, um kalte Cache-Schlüssel zu finden (selten gelesen). OBJECT FREQ funktioniert nur mit maxmemory-policy LFU. MEMORY USAGE mit SAMPLES 0 zählt exakt (Standard sampelt bei großen Collections). COMMAND DOCS (Redis 7+) liefert strukturierte Dokumentation. Diese Introspektionswerkzeuge helfen beim Debuggen von Speicherbloat und beim Tunen von Eviction-Politiken.

redis
# OBJECT subcommands for introspection
OBJECT ENCODING mykey     # internal encoding
OBJECT REFCOUNT mykey     # reference count
OBJECT IDLETIME mykey     # seconds since last access
OBJECT FREQ mykey         # access frequency (LFU mode)

# check memory usage (bytes) of a key
MEMORY USAGE mykey
MEMORY USAGE mykey SAMPLES 0   # exact count

# total memory used by the server
INFO memory | grep used_memory_human

# help understand a command
COMMAND INFO GET
COMMAND DOCS SET

# COMMAND lists all commands (huge output)
COMMAND

Typfehler & Typprüfung

Der Typ eines Schlüssels ist für seine Lebensdauer fest — derselbe Schlüssel lässt sich nicht für einen anderen Typ wiederverwenden, ohne ihn vorher zu löschen. WRONGTYPE-Fehler schützen vor versehentlicher Typverwechslung. TYPE immer prüfen, wenn du mit Schlüsseln unbekannter Herkunft arbeitest. Diese strenge Typisierung ist der Grund, warum Redis-Befehle typpräfixiert sind (HSET vs. SET vs. SADD).

redis
# each key has ONE type; using the wrong command fails
SET mykey "hello"
LPUSH mykey "x"        # WRONGTYPE error

# WRONGTYPE Operation against a key holding the wrong kind of value

# check the type before operating
TYPE mykey             # "string"
if [ "$(TYPE mykey)" = "string" ]; then ...

# TYPE returns: string|list|hash|set|zset|stream|none

# rename preserves the type
RENAME mykey newkey
TYPE newkey            # still "string"

# type is immutable; delete + recreate to change types
DEL mykey
LPUSH mykey "x"        # now a list
03

Strings

Einfache String-Operationen

Strings sind binärsicher (können beliebige Bytes bis 512 MB halten, inklusive Bilder oder JSON). SET mit NX ist die klassische Redis-Lock-Primitive (setzen, falls nicht vorhanden). GETSET ist atomar und nützlich, um Konfigurationen zu tauschen. SETRANGE kann einen String vergrößern. Für strukturierte Daten Hashes statt serialisierter JSON-Strings bevorzugen — sie erlauben Feld-Updates.

redis
# set and get
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 mykey "new" EX 60 NX  # with expiry, only if new

# get and set atomically (returns old value)
GETSET counter 0        # returns old value, sets new

# append to a string
APPEND mykey " world"   # "hello world"

# get substring
GETRANGE mykey 0 4      # "hello"
SETRANGE mykey 6 "redis"# "hello redis"

# get string length
STRLEN mykey            # 11

Numerische Zähler

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. Zähler harmonieren am besten mit EXPIRE für zeitlich gebuckette Stats.

redis
# increment a numeric string atomically
INCR counter            # counter = counter + 1
INCRBY counter 10       # counter = counter + 10

# decrement
DECR counter            # counter = counter - 1
DECRBY counter 5        # counter = counter - 5

# floating point operations
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

Mehrschlüssel-Operationen

MSET/MGET bündeln Operationen in einen Round-Trip — essenziell für die Performance (Redis' Single-Thread-Modell macht den Overhead pro Befehl spürbar). MSETNX ist atomar: entweder alle Schlüssel werden gesetzt oder keiner (alles oder nichts). GETDEL (6.2+) liefert atomar zurück und löscht — nützlich für Einmal-Lese-Nachrichtenmuster. Befehle nach Möglichkeit bündeln, um Netzwerklatenz zu senken.

redis
# set multiple keys at once (atomic)
MSET k1 "v1" k2 "v2" k3 "v3"

# get multiple keys at once
MGET k1 k2 k3           # ["v1", "v2", "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

# atomic get-and-delete (useful for queues)
GETDEL mykey            # returns value AND deletes key

Bitmaps (stringbasiert)

Bitmaps speichern boolesche Flags für bis zu 4 Mrd. Nutzer in ~512 MB — extrem platzsparend für große Populationen. BITOP AND/OR/XOR/NOT kombiniert Bitmaps (z. B. Nutzer, die an mehreren Tagen aktiv waren). BITCOUNT zählt aktive Nutzer. Anwendungsfälle: tägliche aktive Nutzer, Feature-Flags, Anwesenheits-Tracking. Position = Nutzer-ID.

redis
# 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:daily:2025-01-01 5 1
SETBIT users:daily:2025-01-02 5 1
BITOP AND active-both users:daily:2025-01-01 users:daily:2025-01-02
BITCOUNT active-both        # users active on both days

# find the first set bit
BITPOS user:1:active 1      # position of first 1-bit

Bitfield-Operationen

BITFIELD packt mehrere kleine Zähler in einen String — z. B. 1000 Tageszähler als u8 in 1 KB. OVERFLOW SAT sättigt am Maximum (gut für Stats), FAIL liefert nil bei Überlauf (gut für Obergrenzen), WRAP umrundet (Standard, meist unerwünscht). Deutlich speichereffizienter als separate Schlüssel für viele kleine Zähler.

redis
# BITFIELD: multiple counters in one string (compact)
# store up to 2^63 counters, each 1-64 bits, in a single key

# set a 8-bit unsigned counter at offset 0
BITFIELD mycount SET u8 0 100

# increment a counter (with overflow control)
BITFIELD mycount INCRBY u8 0 10   # returns 110
BITFIELD mycount INCRBY u8 0 10   # returns 120

# overflow control: WRAP (default), SAT, FAIL
BITFIELD mycount OVERFLOW SAT INCRBY u8 0 200  # saturates at 255
BITFIELD mycount OVERFLOW FAIL INCRBY u8 0 999 # returns nil (overflow)

# read multiple counters in one call
BITFIELD mycount GET u8 0 GET u8 8 GET u8 16
04

Hashes

Hash-Grundlagen

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.

redis
# 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 multiple fields
HMGET user:1 name age       # ["Alice", "30"]

# get all fields and values
HGETALL user:1
# name  -> Alice
# age   -> 30
# email -> [email protected]

# get all field names or values
HKEYS user:1                # [name, age, email]
HVALS user:1                # [Alice, 30, [email protected]]

# get the number of fields
HLEN user:1                 # 3

Hash-Feldoperationen

HSETNX liefert feldbezogenes 'setzen, falls nicht vorhanden' (praktisch für einmalige Initialisierung). HINCRBY auf Hash-Feldern ist atomar — perfekt für Zähler pro Nutzer (Login-Anzahl, View-Anzahl). Hashes löschen sich selbst, wenn das letzte Feld entfernt wird (HDEL). HMSET ist veraltet, seit HSET mehrere Felder akzeptiert; immer HSET verwenden.

redis
# 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 field

# check if a field exists
HEXISTS user:1 name          # 1 if exists, 0 if not

# increment a numeric field atomically
HINCRBY user:1 age 1         # age = 31
HINCRBY user:1 age -5        # age = 26
HINCRBYFLOAT user:1 score 0.5

# get the string length of a field's value
HSTRLEN user:1 name          # 5 (length of "Alice")

# set multiple fields (same as HSET with multiple)
HMSET user:1 a 1 b 2         # deprecated, use HSET

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. HRANDFIELD (6.2+) ist nützlich zum Sampling (z. B. zufällige Feature-Flags). Bei Hashes mit Millionen Feldern überlegen, sie per Sharding in mehrere Schlüssel aufzuteilen.

redis
# HSCAN: cursor-based iteration (for large hashes)
HSCAN user:1 0 MATCH "na*" COUNT 10
# returns [cursor, [field, value, field, value, ...]]

# iterate all fields
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

# get a random field
HRANDFIELD user:1            # one random field name
HRANDFIELD user:1 3          # 3 random field names
HRANDFIELD user:1 3 WITHVALUES  # fields + values

Hash-Ablauf (Redis 7.4+)

Feldbezogene TTL (7.4+) ist ein großes Feature für Hashes — vorher brauchte man separate Schlüssel oder Workarounds, um einzelne Felder ablaufen zu lassen. Nützlich für Objekte mit gemischten Lebenszeiten (ein Nutzerprofil, bei dem das Session-Token abläuft, der Name aber bleibt). Ältere Redis-Versionen verlangen, ablaufende Felder als separate Schlüssel mit eigenem EXPIRE zu speichern.

redis
# before 7.4, expiration was only at the key level
EXPIRE user:1 3600    # the whole hash expires

# Redis 7.4+: field-level TTL (HEXPIRE)
HEXPIRE user:1 60 FIELDS 1 session_token
# expires only the session_token field in 60 seconds

# get TTL of a specific field
HPTTL user:1 FIELDS 1 session_token

# persist a specific field (remove its TTL)
HPERSIST user:1 FIELDS 1 session_token

# get all fields and their expiration times
HEXPIRETIME user:1 FIELDS 1 session_token

Hash-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.

redis
# 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. Group small key-value pairs into one hash (memory savings)
# instead of SET k1 v1; SET k2 v2 -> HSET bucket k1 v1 k2 v2
05

Listen

Listen-Grundlagen (Push/Pop)

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.

redis
# lists are ordered sequences of strings (linked lists)
# push to head (left) or tail (right)
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
LPOP mylist 2             # ["a", ...]

# 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

Listen-Indexierung & Bereiche

LRANGE 0 -1 liefert die ganze Liste. 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). LINDEX ist O(N) für mittlere Elemente — Listen sind für Endzugriffe optimiert. Für wahlfreien Zugriff per Index eine andere Struktur verwenden.

redis
# get element by index (0-based, O(N) traversal)
LINDEX mylist 0           # first element
LINDEX mylist -1          # last element

# get a range of elements
LRANGE mylist 0 -1        # all elements
LRANGE mylist 0 2         # first 3 elements
LRANGE mylist -3 -1       # last 3 elements

# set an element by index
LSET mylist 1 "new"

# get length
LLEN mylist

# trim to a range (removes everything outside)
LTRIM mylist 0 99         # keep only first 100 elements

# remove elements by value
LREM mylist 2 "value"     # remove first 2 occurrences of "value"
LREM mylist -2 "value"    # remove last 2 occurrences

Liste als Queue

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.

redis
# 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
LPUSH source "item"
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 100

Liste einfügen & entfernen

LINSERT ist O(N) — bei großen Listen sparsam verwenden. LPOS findet Elementpositionen, ohne sie zu entfernen. 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 — einen Sorted Set oder ein anderes Datenmodell erwägen.

redis
# insert before or after a pivot element
LINSERT mylist BEFORE "pivot" "new"
LINSERT mylist AFTER "pivot" "new"

# remove elements by value
LREM mylist 1 "value"     # remove first occurrence from head
LREM mylist -1 "value"    # remove first occurrence from tail
LREM mylist 0 "value"     # remove ALL occurrences

# pop and push in one atomic operation
RPOPLPUSH source dest

# get and remove from both ends (6.2+)
LPOP mylist 2             # pop 2 from head
LMPOP 2 mylist LEFT COUNT 3  # (7.0+) pop from one of multiple lists

# find the position of an element (6.0+)
LPOS mylist "value"
LPOS mylist "value" RANK 2   # find 2nd occurrence

Listen-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 einen Sorted Set verwenden. Listen unterstützen keine Deduplizierung — dafür ein Set.

redis
# 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 <timestamp>
LTRIM rate:user:1 0 99
LLEN rate:user:1           # request count in window
06

Sets

Set-Grundlagen

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. SRANDMEMBER entfernt nicht; SPOP schon. Sets nutzen intset (sortiertes Array), wenn alle Mitglieder Ganzzahlen sind — sehr speichereffizient.

redis
# sets: unordered collection of unique strings
SADD tags "redis" "db" "cache"
SADD tags "redis"          # ignored (already exists)

# remove a member
SREM tags "cache"

# check membership
SISMEMBER tags "redis"     # 1 if member, 0 if not

# get the number of members
SCARD tags                 # 2

# get all members (avoid on large sets)
SMEMBERS tags              # ["redis", "db"]

# get a random member
SRANDMEMBER tags           # one random member
SRANDMEMBER tags 3         # 3 random (may repeat)
SRANDMEMBER tags -3        # 3 unique random

# pop a random member (removes it)
SPOP tags                  # removes and returns one

Set-Operationen

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.

redis
# 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

Set-Iteration & Verschieben

SMOVE ist atomar — nützlich für Zustandsübergänge (z. B. einen Nutzer vom 'pending'- ins 'active'-Set verschieben). SSCAN ist der sichere Weg, große Sets zu iterieren. SMISMEMBER (7.4+) prüft Mitgliedschaft im Batch und reduziert Round-Trips. BSPOP (7.0+) blockiert wie BLPOP, aber für Sets — nützlich für ereignisgetriebene Muster, bei denen die Reihenfolge egal ist.

redis
# SSCAN: cursor-based iteration for large sets
SSCAN myset 0 MATCH "pre*" COUNT 100
# returns [cursor, [member1, member2, ...]]

# move a member from one set to another atomically
SMOVE source dest "member"

# pop multiple random members (6.2+)
SPOP myset 3               # removes and returns 3 members

# blocking set pop (7.0+) - waits until a member exists
BSPOP myset 30             # blocks up to 30 seconds

# check multiple memberships at once (7.4+)
SMISMEMBER myset "a" "b" "c"
# returns [1, 0, 1]

Set-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.

redis
# 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
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"

# 5. Lottery / random selection
SADD participants "u1" "u2" "u3" "u4"
SPOP participants 1        # draw a winner

Sets vs. andere Typen

Die Typwahl ist die zentrale Redis-Designentscheidung. Set für Eindeutigkeit + schnelle Mitgliedschaft (ohne Ordnung). Sorted Set für Rangierungen/Ordnung (kostet mehr Speicher). Liste für Sequenzen mit Duplikaten. Hash für Feld-Wert-Objekte. Unsicher? Zugriffsmuster skizzieren: Lesevorgänge, Schreibvorgänge, Ordnungs- und Eindeutigkeitsanforderungen — der richtige Typ wird offensichtlich.

redis
# Set: unordered, unique, O(1) membership check
SADD myset "a" "b"
SISMEMBER myset "a"       # O(1)

# Sorted Set: unique + ordered by score
ZADD myzset 1 "a" 2 "b"
ZRANK myzset "a"          # 0 (rank)

# List: ordered, allows duplicates, O(N) search
LPUSH mylist "a" "a"
LPOS mylist "a"           # 0 (first match)

# Hash: field-value pairs, no ordering
HSET myhash a 1 b 2

# Choose:
# - need uniqueness only?           -> Set
# - need uniqueness + ordering?     -> Sorted Set
# - need ordering + allow dups?     -> List
# - need key-value mapping?         -> Hash
07

Sorted Sets

Sorted-Set-Grundlagen

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.

redis
# 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: conditional)
ZADD leaderboard NX 300 "new"
ZADD leaderboard GT 300 "alice"  # only if new score is greater

# 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

Bereichsabfragen

ZRANGE liefert nach Rang (Index); ZRANGEBYSCORE nach Score. Das Präfix '(' macht einen Score exklusiv. Redis 6.2 vereinheitlichte diese in ZRANGE mit den Optionen BYSCORE/BYLEX/REV. WITHSCORES schließt den Score in die Ausgabe ein. Für Leaderboards gibt ZREVRANGE 0 9 die Top 10. ZRANGESTORE (6.2+) speichert das Ergebnis unter einem neuen Schlüssel.

redis
# 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)

# get members by score range
ZRANGEBYSCORE leaderboard 100 200    # scores 100-200
ZRANGEBYSCORE leaderboard 100 +inf   # scores >= 100
ZRANGEBYSCORE leaderboard (100 200   # scores > 100 (exclusive)

# descending order
ZREVRANGE leaderboard 0 2            # top 3 (highest scores)
ZREVRANGEBYSCORE leaderboard 200 100 # 200 down to 100

# 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

Score-Operationen & Ränge

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). ZCOUNT liefert die Anzahl in einem Bereich, ohne Mitglieder zu holen. ZMSCORE (6.2+) holt Scores im Batch und reduziert Round-Trips bei Mehrmitglieder-Lookups.

redis
# increment a member's score
ZINCRBY leaderboard 50 "alice"     # alice += 50

# get the score
ZSCORE leaderboard "alice"

# remove a member
ZREM leaderboard "bob"

# remove members by rank range
ZREMRANGEBYRANK leaderboard 0 9    # remove lowest 10
ZREMRANGEBYSCORE leaderboard 0 100 # remove scores <= 100

# count members in a score range
ZCOUNT leaderboard 100 200

# get the rank
ZRANK leaderboard "alice"          # ascending rank
ZREVRANK leaderboard "alice"       # descending rank (0 = highest)

# get multiple members' scores at once
ZMSCORE leaderboard "alice" "bob"  # ["250", "200"]

Lexikografische 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. Funktioniert nur, wenn alle Scores identisch sind.

redis
# 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

Sorted-Set-Aggregationen

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.

redis
# ZUNIONSTORE / ZINTERSTORE: 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
08

Pub/Sub

Pub/Sub-Grundlagen

Pub/Sub ist fire-and-forget: Nachrichten gehen an aktuell verbundene Abonnenten, ohne Persistenz. Lauscht kein Abonnent, geht die Nachricht verloren. Das macht es ungeeignet für zuverlässige Zustellung — dafür Streams nutzen. Pub/Sub ist ideal für Echtzeit-Benachrichtigungen, Chat und Fan-out, wo gelegentlicher Verlust akzeptabel ist. Abonnenten müssen verbunden sein, um zu empfangen.

redis
# subscribe to channels (in one client)
SUBSCRIBE news alerts

# publish a message to a channel (from another client)
PUBLISH news "Breaking: Redis 7.4 released"

# pattern subscription (glob-style)
PSUBSCRIBE news.*

# unsubscribe
UNSUBSCRIBE news
PUNSUBSCRIBE news.*

# note: published messages are NOT persisted
# if no subscriber is listening, the message is lost
# for persistent messaging, use Streams instead

Sharded 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).

redis
# 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)

Pub/Sub-Muster & Anwendungsfälle

Pub/Sub ist perfekt für Fan-out-Muster: ein Publisher, viele Abonnenten (Chaträume, Live-Dashboards, Cache-Invalidierung). PSUBSCRIBE mit Glob-Mustern (user:*:login) ermöglicht flexibles Routing. Die Haupteinschränkung ist fehlende Persistenz — verliert ein Abonnent die Verbindung, verpasst er Nachrichten. Für zuverlässige Zustellung Pub/Sub mit einem Stream als Backup paaren oder einfach Streams nutzen.

redis
# 1. Real-time chat
# client subscribes to their room
SUBSCRIBE chat:room:42
# server publishes messages
PUBLISH chat:room:42 "Alice: hello"

# 2. Cache invalidation
# subscribe to invalidation channel
SUBSCRIBE cache:invalidate
# when data changes, publish
PUBLISH cache:invalidate "user:123"

# 3. Event notifications (with PSUBSCRIBE patterns)
PSUBSCRIBE user:*:login
# matches user:1:login, user:2:login, etc.

# 4. Live dashboards
SUBSCRIBE metrics:*
# push real-time updates to dashboards

# 5. Multiplayer game state
PUBLISH game:room:1 "player_moved:5:10"

Keyspace-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.

redis
# 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

Pub/Sub vs. Streams

Pub/Sub ist für flüchtiges Echtzeit-Messaging; Streams für dauerhaftes, wiederholbares Messaging. Ein üblicher Hybrid: Pub/Sub für Live-Benachrichtigungen (schnell, verlustbehaftet) + Streams als Quelle der Wahrheit (dauerhaft, wiederholbar). Neue Abonnenten lesen den Stream, um aufzuholen, und abonnieren dann Pub/Sub für Live-Updates. Für die meisten Produktionssysteme, die Verlässlichkeit brauchen, sind Streams der bessere Standard.

redis
# Pub/Sub: fire-and-forget, no persistence
PUBLISH channel "msg"   # lost if no subscribers

# Streams: persistent, replayable, consumer groups
XADD mystream * msg "hello"   # stored forever (or capped)

# Pub/Sub pros: simple, low latency, fan-out
# Pub/Sub cons: no persistence, no replay, no consumer groups

# Streams pros: persistent, replayable, consumer groups, ACK
# Streams cons: more complex, requires cleanup (XADD MAXLEN)

# when to use each:
# - real-time notifications (loss OK)     -> Pub/Sub
# - chat with presence                    -> Pub/Sub + Streams
# - reliable task queue                   -> Streams
# - event sourcing / audit log            -> Streams
# - fan-out to transient subscribers      -> Pub/Sub
09

Transaktionen & Pipelining

MULTI/EXEC-Transaktionen

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.

redis
# MULTI starts a transaction; commands are queued
MULTI
SET counter 1
INCR counter
INCR counter
GET counter
EXEC
# returns: [OK, 2, 3, "3"]

# discard a transaction (cancels all queued commands)
MULTI
SET x 1
DISCARD

# errors during queuing (syntax) abort the whole transaction
# errors during EXEC (e.g., wrong type) skip only that command

WATCH (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, nicht während der Einreihung. UNWATCH bricht Beobachtungen ab (passiert auch bei DISCONNECT).

redis
# WATCH monitors keys; if any change before EXEC, the 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

Pipelining (Batch-Round-Trips)

Pipelining bündelt Befehle, um Netzwerk-Round-Trips zu senken — dramatisch schneller als Einzelbefehle übers Netzwerk. Anders als MULTI/EXEC sind gepipelinte Befehle NICHT atomar (andere Clients können sich einmischen). Pipelining für Bulk-Operationen nutzen, wo Atomarität egal ist (Bulk-Inserts, Lesevorgänge), und MULTI/EXEC, wenn Atomarität nötig ist. Die meisten Clients pipelinen innerhalb von MULTI/EXEC automatisch.

redis
# pipelining sends multiple commands in one network round-trip
# (no atomicity guarantee, just reduced latency)

# in a client library (e.g., Node.js / redis):
const pipe = client.multi()
pipe.set("k1", "v1")
pipe.set("k2", "v2")
pipe.incr("counter")
const results = await pipe.exec()

# vs MULTI/EXEC: pipelining does NOT guarantee atomicity
# other clients can interleave between pipelined commands

# raw protocol example (RESP):
# *1\r\n$4\r\nPING\r\n*1\r\n$4\r\nPING\r\n
# (send multiple commands at once, read multiple replies)

Lua-Skripte (atomar)

Lua-Skripte sind der Redis-Weg für komplexe atomare Operationen — das Skript läuft als einzelne atomare Einheit (keine Einmischung). EVALSHA führt ein geladenes Skript per Hash erneut aus (spart das erneute Senden). Skripte kurz halten (sie blockieren den Server). Skripte haben Determinismus-Anforderungen (keine random-/time-Aufrufe) für die Replikation. Redis 7+ nutzt FUNCTIONS als strukturierte Alternative.

redis
# Lua scripts run atomically — no other command runs during execution
# EVAL: run a script
EVAL "return redis.call('GET', KEYS[1])" 1 mykey

# 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"

# load a script once, then run by SHA hash (efficient)
SCRIPT LOAD "return redis.call('GET', KEYS[1])"
# returns a SHA1 hash
EVALSHA <sha1> 1 mykey

# check if a script is loaded
SCRIPT EXISTS <sha1>

Functions (Redis 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.

redis
# 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

# get the function's code
FUNCTION DUMP mylib

# delete a library
FUNCTION DELETE mylib

# functions persist across restarts (unlike EVAL scripts)
10

Persistenz

RDB-Snapshots

RDB-Snapshots sind kompakte Binärdateien, ideal für Backups und Disaster Recovery. 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 riskiert, nach dem letzten Snapshot geschriebene Daten zu verlieren — mit AOF für Dauerhaftigkeit paaren.

redis
# RDB: point-in-time snapshot of the dataset (compact binary)
# trigger a snapshot manually:
SAVE              # blocks until done (use with care)
BGSAVE            # forks a background process (non-blocking)
LASTSAVE          # Unix timestamp of the last successful save

# 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 (default: dump.rdb in the working dir)
CONFIG GET dbfilename
CONFIG GET dir

# RDB pros: compact, fast restart, great for backups
# RDB cons: potential data loss between snapshots

AOF (Append-Only File)

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). AOF-Dateien sind größer und langsamer zu laden als RDB. Redis 7 nutzt ein mehrteiliges AOF-Format (Basis + inkrementell).

redis
# 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

# AOF auto-rewrite thresholds:
#   auto-aof-rewrite-percentage 100
#   auto-aof-rewrite-min-size 64mb

# AOF pros: minimal data loss (1 sec max with everysec)
# AOF cons: larger files, slower load on restart

RDB + AOF Hybrid

RDB + AOF gemeinsam laufen zu lassen ergibt RDBs schnellen Neustart und AOFs Dauerhaftigkeit. Seit Redis 7 ist die AOF eine mehrteilige Datei: ein RDB-Basis-Snapshot + inkrementelles Befehlslog — schnelles Laden mit minimalem Datenverlust kombiniert. aof-use-rdb-preamble (Standard ja) stellt einen RDB-Snapshot an den Anfang der AOF für schnellere Wiederherstellung. Das ist die empfohlene Produktionskonfiguration.

redis
# use BOTH RDB and AOF for the best of both worlds
# redis.conf:
#   save 900 1          # RDB snapshots
#   appendonly yes      # AOF enabled
#   aof-use-rdb-preamble yes  # RDB header in AOF (faster load)

# on restart, Redis loads AOF (more complete)
# the AOF file can start with an RDB snapshot (faster load)
# followed by incremental AOF commands

# disaster recovery: keep both RDB and AOF backups
# RDB for fast restores, AOF for minimal data loss

# check what's enabled
CONFIG GET save
CONFIG GET appendonly

# monitor persistence operations
INFO persistence

Backup & 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. Backups immer mit redis-check-rdb/aof testen.

redis
# backup: copy the RDB file while Redis runs
cp /var/lib/redis/dump.rdb /backup/dump-$(date +%F).rdb

# or trigger a BGSAVE first for a consistent snapshot
BGSAVE
# wait for LASTSAVE to update, then copy the file

# AOF backup: copy the AOF manifest + files
cp /var/lib/redis/appendonly.aof.* /backup/

# restore: stop Redis, replace the data files, start
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)
redis-check-rdb /var/lib/redis/dump.rdb
redis-check-aof /var/lib/redis/appendonly.aof

Persistenz-Trade-offs

Die Persistenzwahl hängt von deinen Dauerhaftigkeitsbedürfnissen ab. Reiner Cache: Persistenz für maximale Geschwindigkeit deaktivieren. Kritische Daten: RDB+AOF (empfohlen). Ein übliches Muster: Persistenz auf dem Primary deaktivieren (für Performance) und auf einem Replica persistieren (verlagert die Platten-I/O). Everysec-AOF ist der Sweet Spot — maximal 1 Sekunde Datenverlust mit minimalem Performance-Einfluss. Wiederherstellung immer testen.

redis
# choosing a persistence strategy:

# 1. RDB only (cache, re-buildable data)
#    save 3600 1
#    appendonly no
#    -> fast restart, some data loss on crash

# 2. AOF only (durability-critical, everysec)
#    save ""
#    appendonly yes
#    appendfsync everysec
#    -> up to 1s data loss, larger files

# 3. RDB + AOF (recommended production default)
#    save 3600 1
#    appendonly yes
#    aof-use-rdb-preamble yes
#    -> durability + fast restart

# 4. No persistence (pure cache, ephemeral)
#    save ""
#    appendonly no
#    -> maximum speed, all data lost on restart

# 5. Replica-only persistence (offload from primary)
#    primary: no persistence (max performance)
#    replica: RDB + AOF (persist here instead)
11

Clustering

Redis-Cluster-Grundlagen

Redis Cluster shardet Daten über Knoten mit 16.384 Hash-Slots. CRC16(key) % 16384 bestimmt den Slot. Mehrschlüssel-Operationen (MGET, Transaktionen) verlangen Schlüssel im selben Slot — Hash-Tags ({user:1}) nutzen, um verwandte Schlüssel zusammenzuzwingen. Jeder Primary kann Replicas für HA haben. Der Cluster handhabt Failover automatisch, wenn ein Primary ausfällt.

redis
# Redis Cluster shards data across multiple nodes (16,384 slots)
# each key maps to a slot: CRC16(key) % 16384

# 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 status
redis-cli -p 7000 CLUSTER INFO
redis-cli -p 7000 CLUSTER NODES

# count slots assigned
CLUSTER COUNTKEYSINSLOT 1234

# get the slot for a key
CLUSTER KEYSLOT mykey   # e.g., 1234

# multi-key operations require keys in the SAME slot
# 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 {})

Hash-Tags & Mehrschlüssel-Ops

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.

redis
# hash tags: the substring inside {} determines the slot
# {user:1}:profile and {user:1}:cart share a slot
# enabling multi-key operations:

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)
# - too narrow -> can't do multi-key ops

Cluster-Resharding

Resharding verschiebt Slots zwischen Knoten ohne Ausfallzeit — Redis migriert Schlüssel einzeln, während Requests bedient werden. Knoten ergänzen, dann rebalancen, um Last zu verteilen. Das CLI-Tool --cluster übernimmt die komplexe Orchestrierung. Nach Änderungen immer --cluster check ausführen. Resharding ist langsam (Migration Schlüssel für Schlüssel), also Kapazität vorab planen statt unter Last zu reshardn.

redis
# move slots from one node to another (resharding)
redis-cli --cluster reshard host1:7000
# prompts for: how many slots, target node, source nodes

# add a new node to the cluster
redis-cli --cluster add-node newhost:7000 host1:7000

# add a new replica to an existing primary
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>

# rebalance slots across all nodes
redis-cli --cluster rebalance host1:7000

# check cluster health
redis-cli --cluster check host1:7000
redis-cli --cluster fix host1:7000   # repair issues

Cluster-Failover

Cluster-Failover ist automatisch: Ist ein Primary länger als cluster-node-timeout (Standard 15 s) unerreichbar, wird sein Replica befördert. Manuelles Failover ist für Wartung (Upgrades ohne Ausfallzeit). TAKEOVER riskiert Split-Brain — nur im Notfall. Ohne Replicas macht ein ausfallender Primary seine Slots unbrauchbar (Cluster down). In Produktion immer mit Replicas laufen lassen. CLUSTER NODES zeigt die Topologie.

redis
# when a primary fails, its replica is promoted automatically
# manual failover (for maintenance):
redis-cli -p 7001 CLUSTER FAILOVER         # replica -> primary
redis-cli -p 7001 CLUSTER FAILOVER FORCE   # without primary agreement
redis-cli -p 7001 CLUSTER FAILOVER TAKEOVER # force, may split brain

# view the cluster topology
CLUSTER NODES
CLUSTER SHARDS    # (7.0+)

# a node flagged as FAIL after timeout is removed
# cluster- node-timeout 15000   (15 seconds in redis.conf)

# if a cluster has no replica for a failing primary,
# that slot range becomes unavailable until the primary returns
# (or you manually fix it)

# CLUSTER RESET resets a node (HARD removes all data)

Cluster vs. Sentinel vs. Single

Einzelinstanz für die Entwicklung. Sentinel für HA, wenn die Daten auf eine Maschine passen (ein Primary + Replicas + Sentinels für Monitoring/Failover). Cluster für horizontale Skalierung, wenn Daten eine Maschine übersteigen oder der Schreibdurchsatz sehr hoch ist. Cluster ergänzt Komplexität (Hash-Tags, Mehrschlüssel-Grenzen). Managed Services (Redis Cloud, ElastiCache, MemoryDB) übernehmen den Betriebsaufwand — bevorzugen, außer du hast starke Gründe fürs Self-Hosting.

redis
# Single Redis: one instance, no HA, no scaling
#    simplest, fine for dev/small cache

# Sentinel: 1 primary + replicas + sentinel monitors
#    HA (automatic failover), no sharding
#    good when dataset fits on one machine
#    sentinel.conf: sentinel monitor mymaster host 6379 2

# Cluster: sharded across N primaries + replicas
#    HA + horizontal scaling
#    good for large datasets / high throughput
#    more complex (multi-key limitations)

# choose:
# - dev / tiny cache              -> single
# - production, data fits in RAM  -> sentinel (HA)
# - data > single machine RAM     -> cluster (sharding)
# - very high write throughput    -> cluster (shard writes)

# managed Redis (Redis Cloud, ElastiCache) handles
# sentinel/cluster ops for you
12

Sentinel (Hochverfügbarkeit)

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.

redis
# 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-Befehle

Clients verbinden sich mit Sentinels, um den aktuellen Primary zu finden, und verbinden sich dann mit ihm. Beim Failover fragen Clients die Sentinels erneut, um den neuen Primary zu finden. SENTINEL failover löst ein manuelles Failover aus (für rollierende Upgrades). 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.

redis
# query sentinel state
redis-cli -p 26379 SENTINEL masters          # all monitored primaries
redis-cli -p 26379 SENTINEL master mymaster  # details of one primary
redis-cli -p 26379 SENTINEL replicas mymaster
redis-cli -p 26379 SENTINEL sentinels mymaster

# find the current primary address
SENTINEL get-master-addr-by-name mymaster

# force a failover (manual, for maintenance)
SENTINEL failover mymaster

# reset a master's state (clears replicas/sentinels discovered)
SENTINEL reset mymaster

# check the number of OK sentinels
SENTINEL ckquorum mymaster
# "OK 3 usable Sentinels" or "NOQUORUM" warning

# clients should connect to sentinels, NOT directly to the primary
# libraries: redis-py, jedis, ioredis all support sentinel mode

Failover-Prozess

Failover ist automatisch, verursacht aber eine kurze Schreibpause (Sekunden). SDOWN ist die Meinung eines Sentinels; ODOWN ist Quorumskonsens. 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). +switch-master abonnieren für Alarme.

redis
# when a primary is down longer than down-after-milliseconds:
# 1. sentinels mark it 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-*

Lese-Replicas & Skalierung

Replicas entlasten den Primary bei Lesevorgängen — nützlich für leseintensive Workloads (Analytics, Reporting). Replikation ist asynchron, Replica-Daten können also hinken (normalerweise Millisekunden, kann unter Last wachsen). READONLY nutzen, um von Replicas zu lesen. Schreibbare Replicas (4.0+) akzeptieren nicht replizierte Schreibvorgänge — nützlich für Temp-Daten oder Caches pro Replica, aber Schreibvorgänge gehen beim Failover verloren. Replica-Lag überwachen.

redis
# replicas can serve reads (eventually consistent)
REPLICAOF 192.168.1.10 6379    # become a replica of this primary
REPLICAOF NO ONE               # promote to primary (manual)

# check replication status
INFO replication
# role:slave, master_host, master_link_status:up, ...

# replica lag (bytes and seconds lagging behind primary)
# master_repl_offset vs slave_repl_offset

# clients can route reads to replicas for read scaling
# but beware: replica data may be stale (replication lag)

# Redis Sentinel + clients: configure read preference
#   READONLY command enables reads on a replica

# writable replicas (Redis 4.0+): accept writes that are
# local-only (not replicated) — useful for ephemeral data
#   replica-read-only no   (in redis.conf)

Replikations-Interna

Replikation ist asynchron und einseitig (Primary zu Replica). Die Erstsynchronisation sendet ein volles RDB, dann den Befehlsrückstand; PSYNC ermöglicht teilweise Resync nach kurzen Verbindungsabbrüchen (nutzt den Replikationsrückstand — repl-backlog-size tunen). Eine Änderung der Replikations-ID (bei Primary-Neustart oder Failover) erzwingt einen vollen Resync. Kettenreplikation (Replica eines Replica) entlastet den Primary bei großem Fan-out.

redis
# replication is asynchronous: primary -> replica (one-way)
# initial sync: full RDB transfer + buffered commands
# subsequent: streaming command log

# trigger a full resync (force replica to reload everything)
redis-cli -p 6380 REPLICAOF NO ONE
redis-cli -p 6380 REPLICAOF 192.168.1.10 6379

# partial resync (PSYNC): if the replica disconnects briefly,
# it can resume from the replication backlog (no full resync)
#   repl-backlog-size 1mb    (tune for longer disconnects)

# monitor replication in real-time
redis-cli -p 6379 INFO replication
# master_repl_offset, slave_read_repl_offset, backlog_size

# chain replication: a replica of a replica (tree topology)
# reduces load on the primary for many replicas
REPLICAOF replica-host 6380   # chain off another replica

# replication ID changes on every primary restart -> full resync
13

Streams

Stream-Grundlagen (XADD/XREAD)

Streams sind Redis' dauerhafte Messaging-Struktur — append-only, wiederholbar, mit Consumer-Groups. IDs sind zeitstempelbasiert (mit * automatisch erzeugt). XREAD mit $ tail-t den Stream (nur neue Einträge); mit 0 liest er von Anfang an. MAXLEN begrenzt den Stream (~ für ungefähr ist viel schneller). Streams lösen Pub/Subs Persistenzlosigkeit und sind der empfohlene Weg, zuverlässige Queues zu bauen.

redis
# streams are append-only logs with IDs (durable, replayable)
# XADD: add an entry (auto-generate ID with *)
XADD mystream * sensor temp 25.5
# returns an ID like "1700000000000-0" (timestamp-sequence)

# add with a specific ID (must be greater than the last)
XADD mystream 1700000001000-0 sensor temp 26.0

# read entries
XREAD COUNT 10 STREAMS mystream 0        # from the beginning
XREAD COUNT 10 STREAMS mystream $        # new entries only (tail)

# block for new entries (like BLPOP for lists)
XREAD BLOCK 30000 STREAMS mystream $     # blocks up to 30s

# get the length
XLEN mystream                            # number of entries

# capped stream (keep only last N entries)
XADD mystream MAXLEN 1000 * field value
XADD mystream MAXLEN ~ 1000 * field value  # ~ = approx (faster)

Consumer-Groups

Consumer-Groups ermöglichen parallele Verarbeitung: Jeder Eintrag geht an genau einen Konsumenten der Gruppe. '>' liest neue Einträge; '0' liest die pending-(unackten-)Einträge dieses Konsumenten. XACK markiert einen Eintrag als verarbeitet. Ausstehende Einträge (zugestellt, aber nicht geackt) bilden ein Verarbeitungslog — mit XPENDING hängengebliebene Nachrichten finden und mit XCLAIM nach einem Timeout einem anderen Konsumenten zuweisen.

redis
# create a consumer group at a specific position
XGROUP CREATE mystream mygroup $        # only new entries
XGROUP CREATE mystream mygroup 0        # all existing entries
XGROUP CREATE mystream mygroup 0 MKSTREAM  # create stream if missing

# read entries as a consumer (assigns pending entries)
XREADGROUP GROUP mygroup consumer1 COUNT 10 STREAMS mystream >
# '>' = never-delivered entries

# read pending entries (for this consumer, not yet acked)
XREADGROUP GROUP mygroup consumer1 STREAMS mystream 0

# acknowledge processing (removes from pending)
XACK mystream mygroup <id1> <id2>

# view pending entries (pending entries list)
XPENDING mystream mygroup
# returns: count, min-id, max-id, consumers

# view a consumer's pending entries
XPENDING mystream mygroup - + 10 consumer1

Stream-Verarbeitung & Wiederherstellung

XAUTOCLAIM ist der Schlüssel zur zuverlässigen Verarbeitung: Er weist Einträge, die zu lange pending sind (Konsument gecrasht oder stockend), einem gesunden Konsumenten zu. min-idle-time verhindert das Entwenden von Einträgen, die noch verarbeitet werden. XTRIM begrenzt die Streamgröße (essenziell für den Speicher). XRANGE liest einen Bereich nach ID. XINFO offenbart Stream-/Gruppen-/Konsumenten-Zustand fürs Monitoring. Das ist eine vollständige, dauerhafte Message Queue.

redis
# XCLAIM: reassign a pending entry to another consumer
# (after the original consumer died or is too slow)
XCLAIM mystream mygroup consumer2 60000 <entry-id>
# 60000 = min idle time (ms) before claiming

# XAUTOCLAIM (6.2+): auto-claim stale pending entries
XAUTOCLAIM mystream mygroup consumer2 60000 0 COUNT 10
# claims entries idle > 60s, returns them to consumer2

# view stream info
XINFO STREAM mystream FULL
XINFO GROUPS mystream
XINFO CONSUMERS mystream mygroup

# delete an entry (rarely needed)
XDEL mystream <id>

# trim the stream (free memory)
XTRIM mystream MAXLEN 10000
XTRIM mystream MINID 1700000000000   # remove older than this ID

# range queries
XRANGE mystream - +                   # all entries
XRANGE mystream 1700000000000 - 1700000009999 -

Stream-Anwendungsfälle

Streams glänzen bei zuverlässigen Queues, Event Sourcing und Zeitreihendaten. Das Consumer-Group-Muster (XADD + XREADGROUP + XACK) ist ein vollständiger Ersatz für listenbasierte Queues, mit eingebautem Retry (pending entries) und Wiederherstellung (XAUTOCLAIM). Für Zeitreihen hält MAXLEN den Speicher begrenzt. Streams sind Redis' funktionsreichste Struktur — nutzen, wo immer Dauerhaftigkeit und geordnete Verarbeitung nötig sind.

redis
# 1. Reliable task queue (replaces lists + BRPOPLPUSH)
XADD tasks * type email payload '{"to":"[email protected]"}'
XREADGROUP GROUP workers worker1 COUNT 1 STREAMS tasks >
# process and XACK on success

# 2. Event sourcing / audit log
XADD events * user 1 action login ip 1.2.3.4
# replay with XRANGE for reconstruction

# 3. Real-time analytics (time-windowed)
XADD metrics * cpu 75 mem 60
XRANGE metrics - +           # query by time range

# 4. Chat history (capped)
XADD chat:room:1 MAXLEN ~ 1000 * user alice msg "hello"
XREAD COUNT 20 STREAMS chat:room:1 0

# 5. IoT sensor data (with TTL via trimming)
XADD sensors:temp MAXLEN ~ 86400 * value 22.5  # keep last day

Streams vs. andere Queues

Streams sind die Redis-native Queue — einfacher als Kafka/RabbitMQ und ausreichend für die meisten Workloads, die in den RAM passen. Ihnen fehlt Kafkas Partition-Parallelität (ein Stream = ein Shard), aber Consumer-Groups liefern Worker-Parallelität. Bei sehr hohem Durchsatz oder plattenbasierter Dauerhaftigkeit gewinnt Kafka. Bei komplexem Routing RabbitMQ. Für die meisten Apps, die bereits Redis nutzen, sind Streams der richtige Standard für zuverlässiges Messaging.

redis
# Redis Streams vs Lists (for queues):
# Lists: LPUSH/BRPOP, simple, NO retry/recovery
# Streams: consumer groups, ACK, pending, XAUTOCLAIM

# Redis Streams vs Kafka:
# Streams: in-memory (RAM-bounded), simpler, single-node or cluster
# Kafka: disk-based, partitioned, higher throughput at scale

# Redis Streams vs RabbitMQ:
# Streams: simpler, fewer features, in-memory
# RabbitMQ: rich routing, exchanges, acknowledgments, disk

# Streams capacity: limited by RAM (use MAXLEN/MINID to trim)
# Streams persistence: RDB/AOF (like any Redis data)

# choose Streams when:
# - you need a queue but already use Redis
# - dataset fits in RAM
# - you want simplicity over Kafka's scale
# - you need consumer groups with retry
14

HyperLogLog, Bitmaps & Geo

HyperLogLog (Kardinalität)

HyperLogLog (HLL) zählt eindeutige Elemente mit ~0,81 % Fehler bei fixen 12 KB — Milliarden Items mit konstantem Speicher zählen. Perfekt für Analytics wie tägliche/wöchentliche/monatliche eindeutige Besucher. PFMERGE kombiniert HLLs (z. B. Monatlicheindeutige aus täglichen). Der Trade-off ist Approximation — ein Set, wenn du exakte Zählungen oder Mitgliedschaftstests brauchst (SISMEMBER), HLL, wenn du nur die Anzahl brauchst.

redis
# HyperLogLog: approximate unique count with fixed 12KB memory
# perfect for counting unique visitors, IPs, etc. at scale

# add elements (returns 1 if the cardinality changed)
PFADD visitors:2025-01-01 "user:1" "user:2" "user:3"

# get the approximate unique count
PFCOUNT visitors:2025-01-01        # ~3

# merge multiple HLLs (e.g., monthly uniques from daily)
PFMERGE visitors:2025-01 visitors:2025-01-01 visitors:2025-01-02

# accuracy: ~0.81% standard error
# memory: always ~12KB regardless of element count (up to 2^64)

# vs a Set for unique counting:
# SADD + SCARD: exact, but O(N) memory (grows with count)
# PFADD + PFCOUNT: approximate, fixed 12KB memory
# 1 million uniques: Set ~10MB, HLL always 12KB

Bitmaps im Detail

Bitmaps speichern ein Bit pro Nutzer — 1 Million Nutzer = 125 KB, 4 Mrd. = 512 MB. BITOP AND/OR/XOR/NOT kombiniert Bitmaps (Retention, Churn-Analyse). BITPOS findet das erste gesetzte Bit. Anwendungsfälle: tägliche aktive Nutzer, Feature-Flags, Anwesenheit, A/B-Testgruppen. Einschränkung: verlangt dichte Ganzzahl-Nutzer-IDs (Lücken verschwenden Platz). Bei spärlichen Daten lieber ein Set oder HyperLogLog.

redis
# bitmaps: boolean operations on a string's bits
# ideal for per-user flags over a large user base (user ID = bit position)

# mark user 7 as "active today"
SETBIT active:2025-01-01 7 1

# check if user 7 was active
GETBIT active:2025-01-01 7          # 1

# count active users
BITCOUNT active:2025-01-01

# users active on BOTH days (AND)
BITOP AND active:both active:2025-01-01 active:2025-01-02
BITCOUNT active:both

# users active on EITHER day (OR)
BITOP OR active:either active:2025-01-01 active:2025-01-02

# users active on day 1 but NOT day 2 (XOR or AND NOT)
BITOP XOR diff active:2025-01-01 active:2025-01-02

# find the first active user
BITPOS active:2025-01-01 1         # position of first 1-bit

# memory: 1 million users = 125KB (1 bit per user)

Geodaten (GEO)

GEO-Befehle speichern geografische Punkte und unterstützen Radius-/Box-Abfragen — aufgebaut auf Sorted Sets (Score = Geohash). GEOSEARCH (6.2+, ersetzt GEORADIUS) findet nahe Punkte mit reichen Optionen (WITHCOORD, WITHDIST, ASC/DESC). Distanz wird auf einer Kugel berechnet. Präzision ist gut für die meisten Apps. Für komplexes GIS (Polygone, Routing) eine dedizierte räumliche Datenbank nutzen. GEO ist perfekt für 'Finde in der Nähe'-Features.

redis
# GEO: built on sorted sets, stores (lng, lat, name) points
# add locations (longitude, latitude, name)
GEOADD places -73.99 40.73 "Park" -73.98 40.75 "Museum" -74.00 40.70 "Cafe"

# get coordinates of a member
GEOPOS places "Park"               # [["-73.99","40.73"]]

# distance between two members (meters by default)
GEODIST places "Park" "Museum"     # "1623.5"
GEODIST places "Park" "Museum" km  # "1.623"

# find members within a radius (meters)
GEOSEARCH places FROMMEMBER "Park" BYRADIUS 1000 m ASC
# members within 1km of Park, sorted by distance

# find members within a bounding box
GEOSEARCH places FROMLONLAT -73.99 40.73 BYBOX 2 2 km

# GEOSEARCH also returns distance and coordinates
GEOSEARCH places FROMMEMBER "Park" BYRADIUS 500 m WITHCOORD WITHDIST

Geodaten-Operationen

GEO ist auf Sorted Sets implementiert — der Geohash der Koordinaten ist der Score. Das heißt, manche Operationen gehen mit Z*-Befehlen (ZREM, ZRANGE). GEOSEARCH liefert reiche Ergebnisse (Distanz, Koordinaten, Geohash). COUNT begrenzt Ergebnisse (mit ASC für nächste-N nutzen). GEOSEARCHSTORE speichert Ergebnisse für weitere Verarbeitung. Die Geohash-Präzision verschlechtert sich nahe der Pole — für die meisten realen Apps fein.

redis
# add multiple points at once
GEOADD cities -122.41 37.78 "San Francisco" -74.00 40.71 "New York"

# get the geohash of a member
GEOHASH places "Park"              # ["dr5reg..."]

# remove a member (uses ZREM internally)
ZREM places "Cafe"

# count members in an area (using ZCOUNT on the underlying zset)
ZCOUNT places -180 180             # all members

# GEOSEARCH with a center point and limiting results
GEOSEARCH places FROMLONLAT -73.99 40.73 \
  BYRADIUS 2000 m ASC COUNT 5      # nearest 5 within 2km

# GEOSEARCHSTORE: store results in a new key (6.2+)
GEOSEARCHSTORE nearby FROMLONLAT -73.99 40.73 BYRADIUS 1000 m

# the underlying structure is a sorted set, so:
ZRANGE places 0 -1                 # list all members
ZSCORE places "Park"               # geohash score

Spezialtypen wählen

Redis bietet viele spezialisierte Strukturen jenseits der fünf Kernstücke. HyperLogLog für approximative Kardinalität, Bitmaps für dichte boolesche Flags, GEO für Nähe. Module ergänzen Bloom-Filter (Mitgliedschaftstest mit Falsch-Positiven), Top-K (Heavy Hitters) und RedisTimeSeries (optimierte Zeitreihen). Die Struktur an Datenform und Genauigkeitsbedürfnis anpassen — die richtige Wahl kann Größenordnungen an Speicher sparen.

redis
# Cardinality counting (unique elements):
#   exact, need membership test  -> Set (SADD/SISMEMBER/SCARD)
#   approximate, huge scale      -> HyperLogLog (PFADD/PFCOUNT)
#   per-time-bucket uniques      -> HLL per day, PFMERGE for ranges

# Boolean flags over a dense ID space:
#   small number of flags        -> Set of active IDs
#   millions of users            -> Bitmap (SETBIT/BITCOUNT)
#   multiple counters compactly  -> BITFIELD

# Geographic points:
#   "find nearby" queries        -> GEO (GEOADD/GEOSEARCH)
#   complex GIS                  -> use PostGIS/external

# Time-series data:
#   simple, capped               -> Stream (XADD MAXLEN)
#   dedicated TS module          -> RedisTimeSeries (module)

# Probabilistic structures (modules):
#   Bloom filter                 -> RedisBloom (BF.ADD/BF.EXISTS)
#   Top-K                        -> RedisBloom (TOPK)
15

Sicherheit

Authentifizierung & ACLs

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. ACLs in eine Datei speichern für Persistenz. Den Standard-Nutzer in Produktion nie verwenden — deaktivieren oder ein starkes Passwort setzen.

redis
# set a password (simple, legacy)
CONFIG SET requirepass "strongpassword"
AUTH "strongpassword"

# Redis 6+: ACL system with users and permissions
# add a user with limited access
ACL SETUSER appuser on >secretpassword ~app:* +get +set +del -@dangerous

# list users
ACL LIST
ACL WHOAMI                # current user

# view a user's permissions
ACL GETUSER appuser

# delete a user
ACL DELUSER appuser

# save ACLs to a file (persists across restarts)
ACL SAVE
ACL LOAD                  # reload from file

# aclfile in redis.conf:
#   aclfile /etc/redis/users.acl

TLS/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 können beide Ports temporär laufen.

redis
# enable TLS in redis.conf (Redis 6+)
# generate certs first (or use a real CA):
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-cluster yes              # TLS between cluster nodes
tls-replication yes          # TLS between primary/replica
tls-auth-clients yes         # require client certs

# mix TLS and plain text (transition period)
# port 6380
# tls-port 6379

Netzwerksicherheit

Redis hat keine native Netzwerkzugriffskontrolle — bind + protected-mode + eine Firewall nutzen. Redis NIE ins Internet stellen (unzählige Vorfälle durch offenes Redis ohne Auth). protected-mode blockiert externe Verbindungen, wenn kein Passwort gesetzt ist. rename-command deaktiviert gefährliche Befehle (FLUSHALL, CONFIG, KEYS), aber ACLs (6.0+) sind der moderne Ansatz. Redis in ein privates Subnetz; Zugang via VPN oder Bastion.

redis
# bind to specific interfaces (never 0.0.0.0 in prod)
bind 127.0.0.1 10.0.0.5
protected-mode yes            # blocks external access if no password

# require authentication
requirepass "strong-random-password"

# rename dangerous commands (or disable them)
rename-command FLUSHALL ""
rename-command FLUSHDB ""
rename-command CONFIG "CONFIG_9f8a7b"
rename-command KEYS ""

# Redis 6+: better to use ACLs instead of rename-command
# ACL SETUSER default -flushall -config -keys

# disable debug commands
# ACL SETUSER default -@dangerous

# use a firewall / security group to restrict access
# Redis should NEVER be directly internet-accessible
# (the 2018+ ransom attacks scanned for open Redis instances)

Audit & Logging

SLOWLOG zeichnet langsame Befehle fürs Performance-Auditing auf — den Schwellwert auf dein SLO setzen (z. B. 10 ms). MONITOR loggt jeden Befehl (riesiger Performance-Einfluss — nur Debug). LATENCY MONITOR hilft, Latenzspitzen zu finden. CLIENT LIST zeigt verbundene Clients (auf Lecks achten). loglevel in Produktion auf 'notice' setzen (debug ist zu geschwätzig). Logs an ein zentrales System liefern zur Analyse.

redis
# log slow commands (slowlog)
CONFIG SET slowlog-log-slower-than 10000   # 10ms in microseconds
CONFIG SET slowlog-max-len 128             # keep 128 entries
SLOWLOG GET 10                             # last 10 slow commands
SLOWLOG RESET

# log to a file (redis.conf)
logfile /var/log/redis/redis.log
loglevel notice    # debug|verbose|notice|warning

# monitor all commands (debugging only — huge perf impact)
MONITOR

# latency monitoring
CONFIG SET latency-monitor-threshold 100   # 100ms
LATENCY HISTORY event-name
LATENCY DOCTOR                              # analysis report

# client list (who's connected)
CLIENT LIST
CLIENT GETNAME
CLIENT SETNAME "my-app"

Sicherheits-Best-Practices

Redis-Sicherheit ist geschichtet: Netzwerk (bind/firewall), Authentifizierung (Passwort/ACL), Transport (TLS), Befehlsbeschränkung (ACL/rename) und Audit (slowlog/monitor). Die Regel Nummer 1: Redis niemals direkt ins Internet stellen — er hat kein eingebautes Rate Limiting oder Brute-Force-Schutz. RDB-/AOF-Dateien auf Plattenebene verschlüsseln (sie enthalten deine Daten im Klartext). Redis für Sicherheitspatches aktuell halten.

redis
# 1. NEVER expose Redis to the public internet
bind 127.0.0.1
protected-mode yes

# 2. Use strong passwords or ACLs
requirepass "<64-char-random-string>"
# or ACLs with least privilege

# 3. Enable TLS for transit encryption
tls-port 6379

# 4. Restrict dangerous commands
ACL SETUSER default -@dangerous -flushall -keys

# 5. Use a firewall / security group
# allow only app servers on the Redis port

# 6. Rotate credentials regularly
ACL SETUSER appuser on >newpassword ~app:* +@read +@write

# 7. Audit access
LOGICALDB MONITOR  # or use an audit module

# 8. Encrypt sensitive data at rest (disk encryption)
# RDB/AOF files can contain sensitive data

# 9. Keep Redis updated (security patches)
# 10. Isolate environments (separate dev/staging/prod)
16

Performance & Optimierung

Performance-Grundlagen

Redis ist single-threaded für die Befehlsausführung — ein langsamer Befehl blockiert ALLE Clients. KEYS, SMEMBERS oder DEL auf großen Strukturen nie in Produktion verwenden. Stattdessen SCAN-Familie, HSCAN und UNLINK (async-Delete). Befehle pipelinen, um Round-Trips zu senken. Die Big-O jedes Befehls kennen: O(1) und O(log N) sind sicher; O(N)-Befehle sollten begrenzt werden (LRANGE mit kleinen Bereichen).

redis
# Redis is single-threaded (mostly) — avoid blocking commands
# DANGEROUS on large datasets (block the server):
KEYS *              # use SCAN instead
SMEMBERS bigset     # use SSCAN
HGETALL bighash     # use HSCAN
DEL hugekey         # use UNLINK (async delete)
FLUSHDB             # use FLUSHDB ASYNC

# use UNLINK instead of DEL for large keys (non-blocking)
UNLINK bigkey       # deletes in a background thread

# favor pipelining and batch commands
MGET k1 k2 k3       # one round-trip, not three GETs
LPUSH list a b c    # one command, not three

# prefer structurally efficient commands
# O(1): GET, SET, HGET, SISMEMBER, ZSCORE
# O(log N): ZADD, ZRANGE
# O(N): LRANGE, SMEMBERS, KEYS, SORT

Pipelining & Batch-Operationen

Pipelining ist der größte Redis-Performance-Hebel — Befehle in einen Netzwerk-Round-Trip bündeln kann 10-100x Beschleunigung bringen. Jeder Round-Trip kostet Netzwerklatenz (~0,1-1 ms); 1000 Einzelbefehle = 100-1000 ms, aber gepipelint = ~1 ms. Nicht überpipelinen (eingereihte Antworten verbrauchen Speicher). Mit redis-benchmark -P benchmarken, um den Sweet Spot zu finden. Transaktionen pipelinen automatisch.

redis
# pipelining: send many commands without waiting for replies
# (reduces round-trip time — huge speedup over network)

# example (Node.js with ioredis):
const pipeline = redis.pipeline()
for (let i = 0; i < 1000; i++) {
  pipeline.set(`key:${i}`, "value")
}
await pipeline.exec()        # one round-trip for 1000 commands

# transactions (MULTI/EXEC) are automatically pipelined
redis.multi().set("k", "v").incr("c").exec()

# MSET/MGET batch in one command
MSET k1 v1 k2 v2 k3 v3
MGET k1 k2 k3

# benchmark pipelining
redis-benchmark -t set -n 100000 -P 16   # -P = pipeline size

# don't pipeline too many at once (memory for queued replies)
# batch in groups of 100-1000

Speicheroptimierung

Speicher ist Redis' primäre Beschränkung. Die richtige Struktur nutzen: Hashes für Objekte (listpack-Kodierung ist 5-10x kleiner als separate Schlüssel). Kodierungsschwellwerte tunen, um Strukturen kompakt zu halten. 'Key Bucketing' (kleine Schlüssel in einen Hash gruppieren) senkt den Overhead pro Schlüssel dramatisch. maxmemory + eine Eviction-Politik setzen, um OOM zu verhindern. used_memory und den Fragmentierungsgrad überwachen.

redis
# use the right data structure (memory vs speed trade-offs)
# store small objects as hashes (listpack encoding is compact)
HSET user:1 name "Alice" age 30   # better than 3 string keys

# tune encoding thresholds (redis.conf)
hash-max-listpack-entries 128     # hash -> hashtable above this
hash-max-listpack-value 64        # field value size limit
list-max-listpack-size -2         # listpack max size
set-max-intset-entries 512        # intset -> hashtable above this
zset-max-listpack-entries 128

# use hashes for many small keys (key bucketing)
# instead of SET user:1:clicks 5; SET user:2:clicks 3
# use HSET clicks user:1 5 user:2 3

# monitor memory
INFO memory | grep used_memory_human
MEMORY STATS

# set maxmemory and an eviction policy
maxmemory 4gb
maxmemory-policy allkeys-lru

Eviction-Politiken

Die Eviction-Politik steuert das Verhalten bei vollem Speicher. Für einen reinen Cache: allkeys-lru oder allkeys-lfu (LFU besser bei schiefen Zugriffsmustern). Für eine Datenbank: noeviction (Schreibvorgänge scheitern, statt Daten zu verlieren). Für gemischte Nutzung: volatile-lru (nur Schlüssel mit TTL verdrängen, persistente behalten). LFU (4.0+) trackt Zugriffsfrequenz und schlägt LRU oft. evicted_keys überwachen, um maxmemory richtig zu bemessen.

redis
# when maxmemory is reached, Redis evicts keys per the policy
# maxmemory-policy options:

# no eviction (writes fail with OOM error)
maxmemory-policy noeviction

# LRU (Least Recently Used) — approximate LRU
allkeys-lru         # evict any key (cache use case)
volatile-lru        # only evict keys with TTL set

# LFU (Least Frequently Used) — better for skewed access
allkeys-lfu
volatile-lfu

# random eviction
allkeys-random
volatile-random

# TTL-based (evict soonest-expiring)
volatile-ttl

# for a cache: allkeys-lru or allkeys-lfu (best hit rate)
# for a database: noeviction (never lose data silently)
# mixed (some persistent, some cache): volatile-lru

Benchmarking

redis-benchmark misst Durchsatz und Latenz unter Last. -c (Nebenläufigkeit) simuliert Clients; -P (Pipelining) testet gebündelte Performance. --latency zeigt die Round-Trip-Zeit in Echtzeit. Für genaue Ergebnisse den Benchmark von einer Maschine nahe Redis ausführen (das Netzwerk dominiert). Redis 6+ unterstützt --threads für multithreaded Benchmarking. Typische Single-Node-Performance: 100K+ ops/s auf Standard-Hardware.

redis
# redis-benchmark: built-in performance testing
redis-benchmark -t set,get -n 100000 -c 50
# -t: test commands, -n: number of requests, -c: concurrent clients

# test with pipelining
redis-benchmark -t set -n 100000 -c 50 -P 16

# test a specific command with a specific key
redis-benchmark -t get -n 100000 -r 100000 -q
# -r: random keys (INSERT random keys for testing)

# latency check (100 requests, shows distribution)
redis-cli --latency
redis-cli --latency-history    # rolling update
redis-cli --latency-dist       # histogram

# in-memory test (no network overhead)
redis-benchmark -t set -n 100000 -q --threads 4

# monitor while benchmarking
redis-cli INFO stats | grep instantaneous_ops_per_sec
17

Administration

Server-Info & Monitoring

INFO ist der zentrale Monitoring-Befehl — die Sektionen memory, clients, persistence und stats regelmäßig prüfen. MEMORY DOCTOR und LATENCY DOCTOR liefern automatisierte Analyse. SLOWLOG erwischt langsame Befehle. CLIENT LIST zeigt alle Verbindungen (auf Lecks achten — jede verbraucht Speicher). Externes Monitoring einrichten (Prometheus + redis_exporter, Datadog) für historische Graphen und Alarme bei Speicher, Verbindungen und Replikationsverzug.

redis
# 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 keyspace         # keys per database

# real-time stats
LATENCY DOCTOR        # latency analysis
MEMORY DOCTOR         # memory analysis

# live monitoring (subscribe to a special channel)
SUBSCRIBE __redis__:invalidate

# slow query log
SLOWLOG GET 10
SLOWLOG LEN

# client connections
CLIENT LIST
CLIENT KILL ID <id>   # disconnect a client

Client-Verwaltung

CLIENT LIST identifiziert Verbindungen nach Adresse, Name und aktuellem Befehl — unbezahlbar, um Lecks oder hängende Clients zu finden. CLIENT SETNAME labelt Verbindungen zur leichten Identifikation (in der App beim Verbinden setzen). CLIENT PAUSE blockiert Clients kurz für sichere Migrationen/Snapshots. Ein Timeout setzen, um ungenutzte Verbindungen aufzuräumen. maxclients verhindert Verbindungs-Erschöpfung (jeder Client verbraucht etwas Speicher).

redis
# list all connected clients
CLIENT LIST
# id, addr, name, age, idle, flags, db, cmd

# name your connections (for identification)
CLIENT SETNAME "my-app-worker-1"

# get the current client's info
CLIENT INFO

# get the current client's ID
CLIENT ID

# kill a client
CLIENT KILL ADDR 1.2.3.4:12345
CLIENT KILL ID 42
CLIENT KILL TYPE normal    # kill all normal clients

# pause clients (for maintenance, 10 seconds)
CLIENT PAUSE 10000

# set a timeout for idle clients
CONFIG SET timeout 300    # 5 minutes

# max clients
CONFIG SET maxclients 10000

Konfiguration

CONFIG SET ändert Einstellungen zur Laufzeit (kein Neustart nötig); CONFIG REWRITE persistiert sie in redis.conf. Config-Änderungen immer im Staging testen. Wichtige Produktionseinstellungen: maxmemory + Eviction-Politik (OOM verhindern), save + appendonly (Persistenz), tcp-keepalive (tote Clients erkennen), timeout (ungenutzte Verbindungen aufräumen). redis.conf versionieren. CONFIG GET * zeigt alles — nützlich fürs Auditing.

redis
# view config (runtime changes with CONFIG SET)
CONFIG GET maxmemory
CONFIG GET maxmemory-policy
CONFIG GET save
CONFIG GET appendonly

# change config at runtime
CONFIG SET maxmemory 4gb
CONFIG SET maxmemory-policy allkeys-lru
CONFIG SET slowlog-log-slower-than 10000

# persist config changes to redis.conf
CONFIG REWRITE

# view all config (large output)
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

Debugging & Fehlerbehebung

OBJECT ENCODING legt die interne Repräsentation offen (Speicher-Debugging). OBJECT IDLETIME findet kalte Schlüssel (Kandidaten für Eviction). MEMORY USAGE pro Schlüssel identifiziert Speicherfresser. DEBUG SLEEP testet, wie deine App mit Latenz umgeht. LATENCY trackt Events (expired, eviction, fast keys). Aktive Defragmentierung (4.0+) holt fragmentierten Speicher online automatisch zurück. DEBUG-Befehle in Produktion sparsam einsetzen.

redis
# check if a key exists and its type
EXISTS mykey
TYPE mykey
OBJECT ENCODING mykey
OBJECT IDLETIME mykey     # seconds since last access

# memory usage per key
MEMORY USAGE mykey

# find keys blocking the server (DEBUG SLEEP for testing)
DEBUG SLEEP 2             # blocks for 2 seconds (testing only)

# check the latency
LATENCY HISTORY event
LATENCY GRAPH event

# object frequency (LFU mode)
OBJECT FREQ mykey

# inspect a key's internal structure (debugging)
DEBUG OBJECT mykey        # raw internal info

# last saved RDB timestamp
LASTSAVE

# active defragmentation (4.0+)
CONFIG SET activedefrag yes
MEMORY MALLOC-STATS

Upgrades & Wartung

Für Upgrades ohne Ausfallzeit Replikation nutzen: zuerst Replicas upgraden, failovern, dann den alten Primary upgraden. Bei Clustern rollierende Neustarts, einen Knoten nach dem anderen (Replica-Primaries zuerst). Vor dem Upgrade immer sichern (BGSAVE + RDB kopieren). Release-Notes für Breaking Changes lesen. Im Staging testen. Redis hält Abwärtskompatibilität über Minor-Versionen, Major-Versionen können Migrationsschritte haben.

redis
# upgrade a standalone Redis:
# 1. save the dataset
SAVE
# 2. stop Redis
redis-cli SHUTDOWN
# 3. replace the binary
# 4. start the new version
redis-server /etc/redis/redis.conf

# upgrade a primary/replica pair (zero downtime):
# 1. upgrade the REPLICA first
SHUTDOWN
# 2. start new version on replica
# 3. promote replica to primary (SENTINEL FAILOVER)
# 4. upgrade the old primary (now a replica)
# 5. failback if desired

# upgrade a cluster:
# 1. upgrade one node at a time (rolling)
# 2. for each node: CLUSTER FAILOVER (if primary), upgrade, restart

# always back up before upgrading
# check the release notes for breaking changes
# test the upgrade in staging first

# rolling restart of a cluster (script)
for node in $nodes; do
  redis-cli -h $node CLUSTER FAILOVER
  redis-cli -h $node SHUTDOWN
  ssh $node "systemctl start redis"
done
18

Häufige Muster

Caching-Muster (Cache-Aside)

Cache-aside ist das häufigste Redis-Muster: aus dem Cache lesen, bei Miss in die DB fallen, Cache füllen. Eine TTL setzen, um Veraltung zu begrenzen. Beim Schreiben entweder write-through (Cache beim DB-Schreiben aktualisieren) oder invalidieren (Cache-Schlüssel löschen). Invalidierung ist sicherer (keine Race beim Wiederbefüllen), aber write-through hält den Cache warm. Cache-Stampede-Schutz: ein Lock oder 'dogpile'-Muster, um zu verhindern, dass viele Requests bei Miss gleichzeitig die DB treffen.

redis
# cache-aside: app checks cache, falls back to DB, fills cache
# pseudo-code:
function get_user(id):
  # 1. check cache
  data = GET("user:" + id)
  if data:
    return JSON.parse(data)

  # 2. cache miss -> query database
  data = db.query("SELECT * FROM users WHERE id = ?", id)

  # 3. fill cache (with TTL to avoid stale data)
  SET("user:" + id, JSON.stringify(data), "EX", 3600)

  return data

# write-through: update cache when DB changes
function update_user(id, data):
  db.update(id, data)
  SET("user:" + id, JSON.stringify(data), "EX", 3600)

# cache invalidation:
DEL("user:" + id)   # when the DB record is deleted

Verteilte Locks

Verteilte Locks mit SET NX EX sind einfach, brauchen aber Sorgfalt: immer eine TTL setzen (verhindert Deadlocks, wenn der Halter crasht) und ein einzigartiges Token nutzen, um nur dein eigenes Lock freizugeben (atomares Check-and-Delete via Lua). Für mehr Sicherheit über Ausfallszenarien hinweg nutzt der Redlock-Algorithmus mehrere unabhängige Redis-Instanzen. Locks sind nicht perfekt sicher (Uhrendrift, GC-Pausen) — für starke Korrektheitsgarantien ein Konsenssystem erwägen (etcd, ZooKeeper). Redis-Locks reichen für die meiste praktische Koordination.

redis
# SET NX with expiry = simple distributed lock
SET lock:resource "token-abc" NX EX 10
# returns OK if acquired, nil if already held

# release: only delete if the value matches (avoid releasing others' locks)
# (requires a Lua script for atomicity)
EVAL "
  if redis.call('GET', KEYS[1]) == ARGV[1] then
    return redis.call('DEL', KEYS[1])
  end
  return 0
" 1 lock:resource "token-abc"

# Redlock algorithm (multi-instance, higher safety):
# 1. get the time
# 2. SET NX on N (usually 5) independent Redis instances
# 3. if acquired on majority (3/5) within validity window -> locked
# 4. otherwise, release on all instances and retry

# lock options:
#   EX 10        # expire after 10 seconds (safety)
#   NX           # only if not exists
#   "token"      # unique value per lock holder (for safe release)

Rate Limiting

Festes Fenster (INCR+EXPIRE) ist am einfachsten, erlaubt aber 2x Spitzen an Fenstergrenzen. Gleitendes Fenster (Sorted Set von Zeitstempeln) ist genauer, verbraucht aber mehr Speicher. Token-Bucket erlaubt Spitzen bis zu einem Maximum. Alle lassen sich mit Lua-Skripten atomar machen (wichtig für Korrektheit unter Nebenläufigkeit). Für Rate Limiting pro Nutzer bei Skala reicht der Fixed-Window-Ansatz meist und ist sehr speichereffizient.

redis
# fixed window rate limiter (simple)
# INCR + EXPIRE on first request
count = INCR("rate:user:1")
if count == 1:
  EXPIRE("rate:user:1", 60)   # 60-second window
if count > 100:
  return "Rate limited"

# sliding window rate limiter (sorted set)
now = current_time_millis()
ZADD("rate:user:1", now, now)         # add current request
ZREMRANGEBYSCORE("rate:user:1", 0, now - 60000)  # remove old
EXPIRE("rate:user:1", 60)
count = ZCARD("rate:user:1")          # current count
if count > 100:
  return "Rate limited"

# token bucket (Lua script for atomicity)
# maintains a bucket of tokens refilled over time
# see: https://redis.io/docs/patterns/distributed-locks/

# GCRA (Generic Cell Rate Algorithm) — elegant single-key version

Leaderboard & Rangierung

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. Für Perzentil-Ränge ZCARD und ZREVRANK kombinieren. Dies ist einer von Redis' natürlichsten und mächtigsten Anwendungsfällen.

redis
# sorted set = perfect for leaderboards
ZADD leaderboard 100 "alice" 250 "bob" 150 "carol"

# top 10 players (highest scores)
ZREVRANGE leaderboard 0 9 WITHSCORES

# a player's rank
ZREVRANK leaderboard "alice"     # 0-indexed from top

# 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 TTL

Session-Store

Redis ist der klassische Session-Store: schnell, unterstützt TTL (automatisches Ablaufdatum) und wird über App-Server hinweg geteilt. Ein Hash pro Session mit gleitender TTL (bei jedem Request auffrischen). Die Sessions eines Nutzers in einem Set tracken für 'überall ausloggen'-Features. Im Cluster Hash-Tags ({user:1}) nutzen, um die Session und den Session-Index eines Nutzers im selben Shard zu halten. Session-IDs bei Login/Rechteänderungen rotieren, für die Sicherheit.

redis
# Redis is ideal for web sessions (fast, expiring, shared)
# store session as a hash with TTL
HSET session:abc123 user_id 1 last_active 1700000000 data "..."
EXPIRE session:abc123 1800     # 30-minute timeout

# update session (and refresh TTL)
HSET session:abc123 last_active 1700001000
EXPIRE session:abc123 1800     # sliding expiration

# destroy a session
DEL session:abc123

# list active sessions for a user (index by user)
SADD user:1:sessions "session:abc123"
SMEMBERS user:1:sessions       # all session IDs

# cluster-friendly: use a hash tag for the user's sessions
SADD {user:1}:sessions "session:abc123"
# enables multi-key operations on the user's session data

# rotate session ID on privilege change (security)
RENAME session:old session:new
EXPIRE session:new 1800
19

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). redis.call wirft Fehler (hält an), redis.pcall liefert sie zurück. Skripte werden nach ihrem SHA1-Hash gecacht, wiederholte Aufrufe nutzen also EVALSHA zur Effizienz.

redis
# run a Lua script inline
EVAL "return redis.call('SET', KEYS[1], ARGV[1])" 1 mykey "hello"
# 1 = number of keys
# mykey = KEYS[1]
# "hello" = ARGV[1]

# return types: string/integer/boolean/table (nil/true/false)
EVAL "return 42" 0
EVAL "return {1, 2, 3}" 0
EVAL "return redis.call('GET', KEYS[1])" 1 mykey

# 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" 0

EVALSHA & Skript-Cache

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.

redis
# load script once, get its SHA1
SCRIPT LOAD "return redis.call('GET', KEYS[1])"
# returns: "fa00..." (the SHA1)

# execute by hash (saves bandwidth on repeated calls)
EVALSHA "fa00..." 1 mykey

# check if a script is cached
SCRIPT EXISTS "fa00..." "abcd..."
# returns: 1) 1  2) 0

# flush the script cache
SCRIPT FLUSH

# list all running scripts (NOSCRIPT errors = cache miss -> reload)
SCRIPT DEBUG SYNC   # blocking debug mode
SCRIPT DEBUG NO     # disable

Atomare Operationen

Lua-Skripte sind der kanonische Weg für atomare Mehrbefehl-Operationen in Redis (keine MULTI/EXEC-Race). Compare-and-set, Semaphore-Beantragung und Queue-Migrationen 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.

redis
# atomic compare-and-set (only update if value matches)
local cur = redis.call('GET', KEYS[1])
if cur == ARGV[1] then
  return redis.call('SET', KEYS[1], ARGV[2])
end
return 0

# atomic 'decrement if positive' (semaphore / rate limit)
local val = tonumber(redis.call('GET', KEYS[1]) or 0)
if val > 0 then
  redis.call('DECR', KEYS[1])
  return 1
end
return 0

# atomic list pop + push (move between queues)
local item = redis.call('RPOP', KEYS[1])
if item then
  redis.call('LPUSH', KEYS[2], item)
end
return item

Redis Functions (7.0+)

Redis Functions (7.0+) sind der moderne Ersatz für Ad-hoc-EVAL-Skripte: registriert, benannt und versioniert wie Datenbank-Stored Procedures. Eine Bibliothek bündelt mehrere Funktionen; FCALL ruft sie auf. Functions werden in RDB/AOF persistiert (überstehen Neustarts), anders als flüchtige EVAL-Caches. Sie machen Scripting wartbarer für nicht-triviale Logik und lassen sich leichter auditieren und versionieren.

redis
# register a library of functions
FUNCTION LOAD "#!lua name=mylib
redis.register_function('myset', function(keys, args)
  return redis.call('SET', keys[1], args[1])
end)

redis.register_function('double', function(keys, args)
  local v = tonumber(redis.call('GET', keys[1]))
  return redis.call('SET', keys[1], v * 2)
end)
"

# call a function
FCALL myset 1 mykey "hello"
FCALL double 1 counter

# list libraries
FUNCTION LIST
FUNCTION LIST WITHCODE

# delete a library
FUNCTION DELETE mylib

# dump and restore (for backup / migration)
FUNCTION DUMP
FUNCTION RESTORE <payload>

Skripte debuggen

redis.log() nutzen, um Meldungen ins Redis-Log zu emittieren, ohne Rückgabewerte zu berühren. redis-cli --ldb ist ein interaktiver Lua-Debugger: Breakpoints setzen, Code durchsteppen, Locals inspizieren. SCRIPT DEBUG SYNC lässt den Server am Skript blockieren, sodass der Debugger steppen kann. Skripte immer im Staging testen — eine entfesselte Schleife kann den ganzen Redis-Server blockieren. Skripte deterministisch halten (kein random/time) für Replikationskorrektheit.

redis
# LOG writes to the Redis log (visible in redis-cli)
EVAL "redis.log(redis.LOG_NOTICE, 'hello from lua'); return 1" 0
# levels: LOG_DEBUG, LOG_VERBOSE, LOG_NOTICE, LOG_WARNING

# return the error object on pcall failure
EVAL "local ok, err = pcall(function()
  error('something broke')
end)
return {ok=tostring(ok), err=tostring(err)}" 0

# debugger (Redis 5.0+)
SCRIPT DEBUG SYNC   # synchronous, blocking
TDEBUG              # step / continue / print
# use redis-cli --ldb to launch debugger:
#   redis-cli --ldb --eval myscript.lua key1 key2 , arg1 arg2

# print variables in the debugger
print myvar
step
continue
20

Monitoring & Fehlerbehebung

INFO & LATENCY

INFO ist der wichtigste einzelne Monitoring-Befehl — er meldet Speicher, Clients, Replikation und Durchsatz in einem Rutsch. mem_fragmentation_ratio beobachten (ideal ~1,0–1,5); >1,5 verschwendet Speicher, <1 heißt, Redis swapped (katastrophal für die Latenz). LATENCY DOCTOR analysiert aktuelle langsame Events und schlägt Fixes vor. keyspace_misses vs. keyspace_hits beobachten, um die Cache-Hit-Ratio zu tracken.

redis
# INFO: server, clients, memory, stats, replication, cpu
INFO                # everything
INFO memory         # memory section only
INFO replication    # replica lag, master link
INFO stats          # ops/sec, keyspace hits/misses

# key metrics to watch:
#   used_memory_rss        # RSS from OS (real footprint)
#   mem_fragmentation_ratio # >1.5 = fragmentation, <1 = swapping (bad!)
#   connected_clients       # client connections
#   instantaneous_ops_per_sec
#   keyspace_misses         # cache hit ratio = hits / (hits + misses)

# LATENCY: samples slow events
LATENCY HISTORY event-name
LATENCY DOCTOR      # human-readable diagnosis
LATENCY RESET

# LATENCY GRAPH event-name (ASCII art)

SLOWLOG & CLIENT LIST

SLOWLOG erfasst Befehle, die langsamer als der konfigurierte Schwellwert sind (Standard 10 ms) — unbezahlbar, um die Abfragen zu finden, die Latenzspitzen verursachen. KEYSPACE-Operationen wie KEYS * und SMEMBERS auf riesigen Sets sind häufige Übeltäter. CLIENT LIST zeigt jede Verbindung mit Leerlaufzeit und aktuellem Befehl; CLIENT SETNAME nutzen, um die Verbindungen deiner App zu labeln, sodass du erkennst, zu welchem Pool ein hängender Client gehört.

redis
# SLOWLOG: record slow commands (over slowlog-log-slower-than, default 10ms)
CONFIG SET slowlog-log-slower-than 10000   # 10ms in microseconds
CONFIG SET slowlog-max-len 128             # keep last 128 entries

SLOWLOG GET          # last 10 slow commands
SLOWLOG GET 5        # last 5
SLOWLOG RESET        # clear

# each entry: id, timestamp, duration (us), command args, client, addr

# CLIENT LIST: see all connected clients
CLIENT LIST
# fields: id, addr, fd, name, age, idle, flags, db, cmd, ...

# kill a stuck client
CLIENT KILL ADDR 10.0.0.1:12345
CLIENT KILL ID 42

# name your connections for easier debugging
CLIENT SETNAME my-app-worker

MEMORY & OBJECT

MEMORY USAGE meldet die exakten Bytes eines Schlüssels (mit SAMPLES 0 für volle Genauigkeit bei großen Collections). OBJECT ENCODING legt Redis' internes Format offen — kleine Strukturen nutzen kompakte Kodierungen (listpack, ziplist), die CPU- und speichereffizient sind, und steigen automatisch auf Hash-Tabellen/Skiplists auf, wenn sie wachsen. Die Kodierung zu kennen erklärt, warum ein Schlüssel größer oder langsamer ist als erwartet.

redis
# MEMORY USAGE: bytes used by a single key
MEMORY USAGE key
MEMORY USAGE bigset SAMPLES 0   # scan all elements (accurate)

# MEMORY STATS: detailed allocator stats
MEMORY STATS

# MEMORY DOCTOR: diagnosis
MEMORY DOCTOR

# OBJECT ENCODING: see internal representation
OBJECT ENCODING mylist      # quicklist / ziplist / listpack / hashtable
OBJECT REFCOUNT mykey
OBJECT IDLETIME mykey       # seconds since last access
OBJECT FREQ mykey           # LFU access frequency (only with maxmemory-policy LFU)

# why is my key so big? use DEBUG OBJECT (careful, can be slow)
DEBUG OBJECT mykey

Bigkey & Keyspace-Scan

KEYS nie in Produktion verwenden — er blockiert den Server. SCAN ist die cursorbasierte, nicht-blockierende Alternative; iterieren, bis der Cursor auf 0 zurückkehrt. --bigkeys und --memkeys sind CLI-Helfer auf SCAN-Basis, die die größten Schlüssel ohne Blockierung aufdecken. Große Schlüssel (besonders Collections mit Millionen Elementen) verursachen Latenzspitzen bei Ablauf/Eviction — finden und splitten (z. B. einen riesigen Sorted Set nach Zeit shardn).

redis
# find big keys safely (production-safe, samples)
redis-cli --bigkeys
# scans keyspace, reports largest of each type

# more accurate: --memkeys (memory usage per key)
redis-cli --memkeys
redis-cli --hotkeys      # with LFU policy, finds frequently-accessed keys

# SCAN: iterate keys without blocking (never use KEYS *)
SCAN 0 MATCH user:* COUNT 100
# returns: next-cursor, [key1, key2, ...]
SCAN <next-cursor> ...
# cursor 0 = done

# scan a hash field-by-field
HSCAN myhash 0 COUNT 100
SSCAN myset 0 MATCH prefix*
ZSCAN myzset 0

# inspect a key's TTL (left to live)
TTL mykey           # seconds (-1 = no expire, -2 = no key)
PTTL mykey          # milliseconds

Cluster-Gesundheit & Failover

CLUSTER NODES und CLUSTER INFO sind die primären Cluster-Gesundheitschecks — auf cluster_state:ok achten und darauf, dass alle Slots zugewiesen sind (insgesamt 16384). CLUSTER FAILOVER auf einem Replica löst einen kontrollierten Master-Wechsel aus; FORCE überspringt die Erstsynchronisation (schneller, aber leichtes Datenverlustrisiko) und TAKEOVER umgeht den Cluster-Konsens (nur im Notfall). Nach Reshards oder Vorfällen immer --cluster check ausführen, um verwaiste Slots oder Split-Brain-Zustände zu erwischen.

redis
# cluster node status
CLUSTER NODES
# fields: id, addr, flags (master/slave/fail?), slots, ping/pong

# cluster-wide health
CLUSTER INFO
# cluster_state:ok / cluster_slots_assigned / cluster_slots_ok
# cluster_known_nodes

# slot ownership (which node owns a key)
CLUSTER KEYSLOT mykey    # hash slot number
CLUSTER COUNTKEYSINSLOT 1234

# reshard slots (use redis-cli --cluster reshard)
redis-cli --cluster reshard 127.0.0.1:7000 \
  --cluster-from <node-id> --cluster-to <node-id> \
  --cluster-slots 1000 --cluster-yes

# manual failover (on a replica)
CLUSTER FAILOVER          # wait for sync
CLUSTER FAILOVER FORCE    # skip sync (faster, slight data loss risk)
CLUSTER FAILOVER TAKEOVER # no consensus (emergency only)

# verify cluster after changes
redis-cli --cluster check 127.0.0.1:7000
redis-cli --cluster fix 127.0.0.1:7000    # auto-repair minor issues

Was this helpful?