Primeiros Passos
Conectar ao Servidor Redis
redis-cli é o cliente de linha de comando padrão. O padrão conecta a 127.0.0.1:6379. Use -h para host, -p para porta, -a para senha (ou defina a variável de ambiente REDISCLI_AUTH para evitar vazar segredos no histórico do shell). TLS precisa de --tls mais certificado/chave. O esquema de URL redis:// é suportado no Redis 6+, rediss:// para TLS.
# connect to local server (default port 6379)
redis-cli
# connect to a remote host with custom port
redis-cli -h redis.example.com -p 6380
# connect with authentication
redis-cli -a "yourpassword"
redis-cli -h host -p 6379 -a "yourpassword"
# connect over TLS
redis-cli --tls --cert client.crt --key client.key -h host -p 6379
# connect using a URL (Redis 6+)
redis-cli redis://user:password@host:6379/0
redis-cli rediss://user:password@host:6379/0 # TLSOpções e Modo de Conexão
redis-cli suporta tanto o modo interativo quanto o de batida única. Passar um comando como argumentos o executa e sai. O modo pipe lê comandos RESP/texto do stdin — ótimo para scripting e cargas em massa. -n seleciona o banco lógico. --stat e --latency são helpers de monitoramento embutidos. --raw produz valores sem prefixos de tipo, útil para pipes.
# select a specific database index (0-15)
redis-cli -n 1 # use database 1
# run a single command and exit (non-interactive)
redis-cli GET mykey
redis-cli -h host PING
# pass command with arguments
redis-cli SET counter 100
redis-cli INCR counter
# read commands from stdin (pipe mode)
echo "SET k1 v1" | redis-cli
cat commands.txt | redis-cli
# repeat a command every second (watch mode)
redis-cli --stat
redis-cli --latency
# pretty-print JSON output (Redis 6+)
redis-cli --raw GET user:jsonPING e Teste de Conectividade
PING é a checagem de saúde mais simples — um Redis funcionando retorna PONG. --latency mede continuamente o tempo de ida e volta (útil para diagnosticar problemas de rede). --latency-dist mostra um histograma. --latency-history registra estatísticas móveis. Use estes para estabelecer uma linha de base da qualidade da sua conexão antes de ajustar o desempenho.
# basic connectivity test
redis-cli ping
# PONG
# ping with a message (echoed back)
redis-cli PING "hello"
# "hello"
# test auth + connection in one shot
redis-cli -a password PING
# check round-trip latency (continuous)
redis-cli --latency
# output: min: 0, max: 1, avg: 0.27 (3421 samples)
# latency histogram
redis-cli --latency-dist
# latency history (rolling, every 15s by default)
redis-cli --latency-history -i 1Dicas do Modo Interativo
O modo interativo é um REPL para comandos Redis. HELP <comando> ou HELP @<grupo> mostra os docs embutidos (sem internet). CONNECT troca de servidor na sessão. CLEAR limpa a tela. A CLI detecta automaticamente entrada multilinha para strings entre aspas. Prefixe ':' para rodar comandos específicos da CLI (como :raw) em vez de comandos Redis.
# start interactive mode
redis-cli
# inside the CLI:
127.0.0.1:6379> HELP SET # command help
127.0.0.1:6379> HELP @string # help for a command group
127.0.0.1:6379> SCAN 0 # any Redis command
# clear the screen
127.0.0.1:6379> CLEAR
# connect to a different server without restarting
127.0.0.1:6379> CONNECT host 6380
# exit
127.0.0.1:6379> EXIT
127.0.0.1:6379> QUIT
# multi-line input: end with a backslash
127.0.0.1:6379> SET mykey "this is \
a multi-line value"
# toggle raw output mode
127.0.0.1:6379> :rawSeleção de Banco e Básico
Bancos Redis são namespaces lógicos (0-15) compartilhando a mesma memória — não são schemas isolados. A maioria dos apps usa só o db 0. FLUSHDB limpa o db atual; FLUSHALL limpa tudo (cuidado!). Múltiplos bancos são desencorajados em favor de instâncias separadas ou prefixos de chave, já que compartilham uma única thread.
# Redis has 16 logical databases (0-15) by default
SELECT 0 # switch to database 0
SELECT 15 # switch to database 15
# move a key to another database
MOVE mykey 1
# flush the current database (DESTRUCTIVE)
FLUSHDB
# flush ALL databases (VERY DESTRUCTIVE)
FLUSHALL
# get the number of keys in the current db
DBSIZE
# swap two databases (Redis 4.0+)
SWAPDB 0 1Ajuda e Descoberta de Comandos
COMMAND introspecta a tabela de comandos do servidor — útil para descobrir capacidades e aridade. COMMAND DOCS (7.0+) retorna documentação estruturada. O comando HELP da CLI mostra docs offline agrupados por categoria (@string, @hash, @server etc.). Rode 'redis-cli --help' para todas as flags e opções da CLI.
# list all commands (huge output)
COMMAND
# get details of a specific command
COMMAND INFO GET
COMMAND INFO SET HSET LPUSH
# structured documentation (Redis 7+)
COMMAND DOCS SET
COMMAND DOCS @string
# count available commands
COMMAND COUNT
# CLI help
redis-cli --help
redis-cli --version
# inside interactive mode
HELP
HELP @server
HELP @string
HELP @hash
HELP GETSETStrings
SET e GET Básicos
SET/GET são as operações de string fundamentais. NX = definir se não existe (usado para locks); XX = definir se existe. EX/PX/EXAT/PXAT definem expiração atomicamente (sem corrida entre SET e EXPIRE). GETSET retorna o valor anterior enquanto define um novo. Strings são seguras para binário até 512MB.
# set and get a key
SET mykey "Hello"
GET mykey # "Hello"
# set only if not exists (NX) or only if exists (XX)
SET mykey "new" NX # set only if key does NOT exist
SET mykey "new" XX # set only if key DOES exist
# set with expiration (seconds / milliseconds)
SET token "abc" EX 3600 # expires in 3600s
SET token "abc" PX 60000 # expires in 60000ms
# set with expiration at a Unix timestamp
SET token "abc" EXAT 1700000000
# get and set atomically (returns old value)
GETSET counter 0 # returns old value, sets new
# delete a key
DEL mykeyContadores Numéricos (INCR/DECR)
INCR/DECR são atômicos — seguros para acesso concorrente sem travas. Isso torna o Redis ideal para contadores, limitação de taxa (INCR + EXPIRE) e geração de IDs sequenciais. INCRBYFLOAT suporta decimais, mas usa precisão dupla (cuidado com arredondamento). Se o valor não for inteiro, INCR retorna erro.
# increment a numeric string atomically
SET counter 100
INCR counter # 101
INCRBY counter 10 # 111
# decrement
DECR counter # 110
DECRBY counter 5 # 105
# floating point increment
SET price "10.50"
INCRBYFLOAT price 0.25 # "10.75"
INCRBYFLOAT price -1.00 # "9.75"
# all increment ops are atomic and concurrency-safe
# use for: counters, rate limiting, sequence IDs, stats
# INCR on a non-integer value returns an error
SET mystr "hello"
INCR mystr # ERROR: value is not an integerAPPEND e Operações de String
APPEND estende uma string (cria se ausente). STRLEN reporta o comprimento. GETRANGE/SETRANGE operam em substrings (seguras para binário). GETDEL (6.2+) retorna e deleta atomicamente — útil para padrões de leitura única. GETEX retorna atomicamente o valor e define um TTL — prático para renovar a expiração da sessão na leitura.
# append to a string value
SET msg "Hello"
APPEND msg " World" # "Hello World"
# get string length
STRLEN msg # 11
# get substring
GETRANGE msg 0 4 # "Hello"
GETRANGE msg 6 -1 # "World"
# overwrite a substring (grows if needed)
SETRANGE msg 6 "Redis" # "Hello Redis"
# get and delete atomically
GETDEL mykey # returns value AND deletes key
# get and set expiration atomically (6.2+)
GETEX mykey EX 3600 # returns value, sets TTL
# append only if key exists
APPEND existing_key "more"MSET e MGET (Operações em Lote)
MSET/MGET agrupam operações numa única ida e volta — essencial para desempenho (o Redis é single-threaded, então o custo por comando importa). MSETNX é atômico: ou todas as chaves são definidas ou nenhuma. Para muitos pares chave-valor pequenos, considere agrupá-los num hash (HSET) por melhor eficiência de memória via codificação listpack.
# set multiple keys at once (atomic)
MSET k1 "v1" k2 "v2" k3 "v3"
# get multiple keys at once
MGET k1 k2 k3 # 1) "v1" 2) "v2" 3) "v3"
# set multiple only if ALL keys are new
MSETNX k1 "v1" k4 "v4" # 1 if all set, 0 if any existed
# MSET/MGET reduce round-trips — much faster than
# separate SET/GET calls in a loop
# get the length of a string value
STRLEN k1 # 2
# set multiple fields of different keys is not possible;
# for per-field updates use hashes (HSET)
# pipeline alternative in CLI:
printf '%s\n' "SET k1 v1" "SET k2 v2" "GET k1" | redis-cli --pipe-modeBitmaps (Baseados em String)
Bitmaps guardam flags booleanas para até 4 bilhões de usuários em ~512MB — extremamente eficientes em espaço. BITOP AND/OR/XOR/NOT combina bitmaps (ex.: usuários ativos em múltiplos dias). BITCOUNT conta usuários ativos. BITFIELD empacota múltiplos contadores pequenos numa única string. Posição = ID do usuário. Casos de uso: usuários ativos diários, feature flags.
# bitmaps are strings operated on at the bit level
# great for boolean flags on a large user base
# set bit at position (0 or 1)
SETBIT user:1:active 7 1 # user 1 active
GETBIT user:1:active 7 # 1
# count set bits
BITCOUNT user:1:active # total bits set to 1
# bitwise operations between strings
SETBIT users:d1 5 1
SETBIT users:d2 5 1
BITOP AND active-both users:d1 users:d2
BITCOUNT active-both # users active on both days
BITOP OR active-either users:d1 users:d2
BITOP XOR diff users:d1 users:d2
# find the first set bit
BITPOS user:1:active 1 # position of first 1-bit
# bitfield: multiple counters in one string
BITFIELD mycnt SET u8 0 100
BITFIELD mycnt INCRBY u8 0 10Expiração e TTL de String
TTL retorna -2 para chaves inexistentes e -1 para chaves sem expiração. SET com EX é atômico (sem corrida entre SET e EXPIRE). KEEPTTL (6.0+) permite atualizar um valor preservando seu TTL — útil para renovar valores cacheados sem resetar a janela de expiração. A expiração é preguiçosa (verificada no acesso) mais varreduras periódicas em segundo plano.
# set a key with expiration in one atomic command
SET session "data" EX 3600 # 1 hour
SET cache "value" PX 60000 # 60 seconds (ms)
# set expiration on an existing key
EXPIRE mykey 60 # 60 seconds
PEXPIRE mykey 60000 # 60 seconds (ms)
EXPIREAT mykey 1700000000 # Unix timestamp
# view remaining time to live
TTL mykey # seconds (-1 = no expiry, -2 = no key)
PTTL mykey # milliseconds
# remove expiration (make key persistent)
PERSIST mykey
# TTL with KEEPTTL option (6.0+): set value, keep existing TTL
SET mykey "newval" KEEPTTLLists
Operações Push e Pop
Listas são de dupla ponta: LPUSH+RPOP = fila (FIFO), LPUSH+LPOP = pilha (LIFO). BLPOP/BRPOP bloqueiam até um item estar disponível — a fundação das filas Redis (sem polling). Sempre defina um timeout no BLPOP para tratar desconexões. Listas são O(1) para operações de cabeça/cauda, mas O(N) para acesso no meio.
# lists are ordered sequences of strings (linked lists)
LPUSH mylist "a" "b" # list: [b, a]
RPUSH mylist "c" # list: [b, a, c]
# pop from head or tail
LPOP mylist # "b" (removes from head)
RPOP mylist # "c" (removes from tail)
# pop multiple (6.2+)
LPOP mylist 2 # pop 2 from head
# get length
LLEN mylist # 0
# blocking pop (waits if empty, up to timeout)
BLPOP queue:tasks 30 # blocks up to 30 seconds
BRPOP queue:tasks 0 # blocks forever
# push only if the list exists (don't create new key)
LPUSHX mylist "x" # 0 if key doesn't existLRANGE e Indexação
LRANGE 0 -1 retorna a lista inteira. LINDEX é O(N) para elementos do meio — listas são otimizadas para acesso nas pontas. LSET modifica por índice. LINSERT é O(N) (use com parcimônia em listas grandes). LPOS acha posições de elementos sem removê-los. Para acesso aleatório frequente por índice, uma lista é a escolha errada — considere um sorted set.
# get a range of elements (0-based, negative from end)
LRANGE mylist 0 -1 # all elements
LRANGE mylist 0 2 # first 3 elements
LRANGE mylist -3 -1 # last 3 elements
# get element by index (O(N) traversal)
LINDEX mylist 0 # first element
LINDEX mylist -1 # last element
# set an element by index
LSET mylist 1 "newval"
# get length
LLEN mylist
# insert before or after a pivot element
LINSERT mylist BEFORE "pivot" "new"
LINSERT mylist AFTER "pivot" "new"
# find the position of an element (6.0+)
LPOS mylist "value"
LPOS mylist "value" RANK 2 # find 2nd occurrencePops Bloqueantes e Filas
BRPOPLPUSH/BLMOVE move um item atomicamente da fonte ao destino — o consumidor pode processá-lo com segurança, e se cair, o item continua no destino (padrão de fila confiável). Isso vence BRPOP+processamento, porque um crash após BRPOP perde o item. Após processar, delete da lista de destino.
# simple FIFO queue: LPUSH to add, RPOP to consume
LPUSH tasks "job1" "job2"
RPOP tasks # "job1" (FIFO order)
# reliable queue with BRPOP (blocking, waits for work)
BRPOP tasks 0 # blocks until a task is available
# move items between lists atomically
RPOPLPUSH source destination # move one item
# blocking move (reliable queue pattern)
BRPOPLPUSH source destination 30 # blocks up to 30s
# Redis 6.2+: BLMOVE replaces BRPOPLPUSH
BLMOVE source destination RIGHT LEFT 30
# capped queue (e.g., recent events)
LPUSH recent "event"
LTRIM recent 0 99 # keep latest 100LREM, LSET e LTRIM
LTRIM é um padrão comum para limitar o tamanho da lista (ex.: manter só os últimos 100 eventos). LREM remove por valor (count: positivo=cabeça, negativo=cauda, 0=tudo). LMPOP (7.0+) faz pop de múltiplas listas numa chamada, útil para filas priorizadas. Para operações frequentes no meio da lista, uma lista é a escolha errada.
# trim to a range (removes everything outside)
LTRIM mylist 0 99 # keep only first 100 elements
LTRIM mylist -50 -1 # keep only last 50
# remove elements by value
LREM mylist 2 "value" # remove first 2 occurrences of "value"
LREM mylist -2 "value" # remove last 2 occurrences
LREM mylist 0 "value" # remove ALL occurrences
# pop and push in one atomic operation
RPOPLPUSH source dest
# pop from multiple lists (7.0+)
LMPOP 2 mylist1 mylist2 LEFT COUNT 3
# blocking pop from multiple lists (7.0+)
BLMPOP 30 2 mylist1 mylist2 LEFT COUNT 3
# remove a key only if it's a list (type-safe)
DEL mylist # works on any typeCasos de Uso de Lista
Listas são melhores para sequências com padrões de acesso nas pontas: filas, pilhas, feeds, buffers. LTRIM as torna ideais para logs/feeds limitados. Para limitação de taxa, uma lista de timestamps + LTRIM é uma janela deslizante simples. Para filas ordenadas/priorizadas, use um sorted set. Listas não suportam deduplicação — use um set para isso.
# 1. Task queue (FIFO)
LPUSH tasks "process_order:123"
BRPOP tasks 30
# 2. Recent activity feed (capped)
LPUSH user:1:feed "post:99" "post:98"
LTRIM user:1:feed 0 49 # latest 50
# 3. Stack (LIFO)
LPUSH stack "item"
LPOP stack
# 4. Circular buffer (limited size)
LPUSH buffer "new"
LTRIM buffer 0 999 # keep 1000 items
# 5. Rate limiter (sliding window)
LPUSH rate:user:1 1700000000
LTRIM rate:user:1 0 99
LLEN rate:user:1 # request count in window
# 6. Chat history (capped)
LPUSH chat:room:1 "alice: hello"
LTRIM chat:room:1 0 999 # keep last 1000 messagesSets
SADD, SMEMBERS e SISMEMBER
Sets guardam valores únicos — perfeitos para tags, categorias e deduplicação. SISMEMBER é O(1) — muito mais rápido que checar uma lista. SMEMBERS pode bloquear em sets grandes; use SSCAN para iteração. SMISMEMBER (7.4+) verifica pertinência em lote, reduzindo idas e voltas. Sets usam intset (array ordenado) quando cada um dos membros são inteiros — muito eficiente em memória.
# sets: unordered collection of unique strings
SADD tags "redis" "db" "cache"
SADD tags "redis" # ignored (already exists)
# check membership (O(1))
SISMEMBER tags "redis" # 1 if member, 0 if not
# get all members (avoid on large sets)
SMEMBERS tags # 1) "redis" 2) "db" 3) "cache"
# get the number of members
SCARD tags # 3
# remove a member
SREM tags "cache" # 1
# check multiple memberships at once (7.4+)
SMISMEMBER tags "redis" "db" "missing"
# 1) 1 2) 1 3) 0Operações de Set (Union/Inter/Diff)
Operações de set são o superpoder do Redis — união, interseção e diferença em O(N) sem processamento no cliente. Casos de uso: amigos em comum (SINTER), visitantes únicos (SUNION), filtragem por tags (SINTER de sets de tags). SINTERCARD (7.0+) retorna só a contagem, mais rápido quando não precisa dos membros. Guarde os resultados para evitar recomputar.
# set union, intersection, difference
SADD set1 "a" "b" "c"
SADD set2 "b" "c" "d"
# union (all unique members from all sets)
SUNION set1 set2 # a, b, c, d
# intersection (members in ALL sets)
SINTER set1 set2 # b, c
# difference (members in set1 but NOT in set2)
SDIFF set1 set2 # a
# store the result in a new set
SUNIONSTORE result set1 set2
SINTERSTORE result set1 set2
SDIFFSTORE result set1 set2
# count intersection without returning members (7.0+)
SINTERCARD 2 set1 set2 LIMIT 0
# operations on multiple sets at once
SUNION s1 s2 s3 s4SREM, SMOVE e SPOP
SMOVE é atômico — útil para transições de estado (ex.: mover um usuário do set 'pending' para o 'active'). SPOP remove membros aleatórios (útil para loteria/sharding). SRANDMEMBER não remove. BSPOP (7.0+) bloqueia como BLPOP, mas para sets — útil para padrões dirigidos a eventos em que a ordem não importa. SREM retorna a contagem realmente removida.
# remove one or more members
SADD myset "a" "b" "c" "d"
SREM myset "a" "b" # 2 (number removed)
# move a member from one set to another atomically
SMOVE source dest "member"
# pop a random member (removes it)
SPOP myset # removes and returns one
SPOP myset 3 # removes and returns 3 (6.2+)
# get a random member (does NOT remove)
SRANDMEMBER myset # one random member
SRANDMEMBER myset 3 # 3 random (may repeat)
SRANDMEMBER myset -3 # 3 unique random
# blocking set pop (7.0+) - waits until a member exists
BSPOP myset 30 # blocks up to 30 seconds
# delete the entire set
DEL mysetIteração SSCAN
SSCAN é a forma segura de iterar sets grandes — SMEMBERS bloqueia o servidor para sets enormes. SSCAN é baseado em cursor: chame repetidamente até o cursor voltar a 0. COUNT é uma dica (pode retornar mais ou menos). SSCAN oferece garantias fracas: pode retornar duplicatas ou perder membros adicionados durante a iteração, mas nunca bloqueia. Sempre trate o loop do cursor no seu código.
# SSCAN: cursor-based iteration for large sets
SSCAN myset 0 MATCH "pre*" COUNT 100
# returns: [nextCursor, [member1, member2, ...]]
# continue until cursor returns to 0
SSCAN myset <nextCursor> MATCH "pre*" COUNT 100
# iterate all members safely
cursor=0
while true:
cursor, members = SSCAN myset cursor COUNT 100
process(members)
if cursor == 0: break
# scan with type filtering (7.0+ for SCAN, sets always same type)
# COUNT is a hint, not exact (may return more or fewer)
# MATCH pattern supports glob: *, ?, [abc]
SSCAN myset 0 MATCH "user:*" COUNT 1000
# for small sets, SMEMBERS is fine
# for large sets (>10k), always use SSCANCasos de Uso de Set
Sets são a escolha padrão para unicidade e relações. O padrão SINTER para seguidores/amigos em comum é um clássico. Para 'visitantes por dia' com cardinalidade enorme, considere HyperLogLog (aproximado, mas com 12KB fixos). Para dados únicos ordenados (leaderboards), use um sorted set. Sets são sem ordem — se a ordem importa, use uma list ou sorted set.
# 1. Tags / categories
SADD post:1:tags "redis" "db"
SADD post:2:tags "redis" "cache"
SINTER post:1:tags post:2:tags # posts sharing "redis"
# 2. Unique visitors per day
SADD visitors:2025-01-01 "user:1" "user:2"
SCARD visitors:2025-01-01 # visitor count
# 3. Followers / following (mutual friends)
SADD user:1:following "user:2" "user:3"
SADD user:2:following "user:1" "user:3"
SINTER user:1:following user:2:following # mutual follows
# 4. Blacklist / whitelist
SADD blacklist "ip:1.2.3.4"
SISMEMBER blacklist "ip:1.2.3.4" # 1 = blocked
# 5. Lottery / random selection
SADD participants "u1" "u2" "u3" "u4"
SPOP participants 1 # draw a winnerSorted Sets
ZADD, ZSCORE e ZRANK
Sorted sets (zsets) são a estrutura mais poderosa do Redis — membros únicos ordenados por pontuação, com operações O(log N). As opções do ZADD (NX/XX/GT/LT) habilitam atualizações condicionais: GT só atualiza se a nova pontuação for maior (ótimo para rastrear 'melhor pontuação'). Pontuações são doubles; membros são únicos. Empates são resolvidos lexicograficamente.
# sorted set: unique members ordered by a float score
ZADD leaderboard 100 "alice" 200 "bob" 150 "carol"
# update a score (re-add with new score)
ZADD leaderboard 250 "alice" # alice's score becomes 250
# add with options (NX: only new, XX: only existing, GT/LT)
ZADD leaderboard NX 300 "new" # only if new
ZADD leaderboard GT 300 "alice" # only if new score > current
ZADD leaderboard LT 50 "alice" # only if new score < current
# get a member's score
ZSCORE leaderboard "alice" # "250"
# get a member's rank (0-based, ascending)
ZRANK leaderboard "alice" # rank from lowest
ZREVRANK leaderboard "alice" # rank from highest (0 = top)
# get the number of members
ZCARD leaderboard # 3
# get multiple scores at once (6.2+)
ZMSCORE leaderboard "alice" "bob" # ["250", "200"]ZRANGE e ZREVRANGE
ZRANGE retorna por rank (índice); com BYSCORE retorna por intervalo de pontuação. Redis 6.2 unificou ZRANGEBYSCORE/ZREVRANGE em ZRANGE com opções BYSCORE/BYLEX/REV. WITHSCORES inclui a pontuação na saída. Para leaderboards, ZRANGE 0 9 REV dá o top 10. ZRANGESTORE (6.2+) guarda o resultado numa nova chave para processamento posterior.
# get members by index range (ascending)
ZRANGE leaderboard 0 -1 # all, ascending
ZRANGE leaderboard 0 2 # first 3 (lowest scores)
ZRANGE leaderboard -3 -1 # last 3 (highest scores)
# descending order
ZREVRANGE leaderboard 0 2 # top 3 (highest scores)
# with scores
ZRANGE leaderboard 0 -1 WITHSCORES
# Redis 6.2+: unified ZRANGE with BYSCORE/REV options
ZRANGE leaderboard 100 200 BYSCORE
ZRANGE leaderboard 200 100 BYSCORE REV
# store a range in a new key (6.2+)
ZRANGESTORE top3 leaderboard 0 2 REV
# get by rank with scores
ZRANGE leaderboard 0 9 REV WITHSCORES # top 10
# limit results (pagination)
ZRANGE leaderboard 0 -1 BYSCORE LIMIT 0 10ZRANGEBYSCORE e ZCOUNT
ZRANGEBYSCORE retorna por intervalo de pontuação; o prefixo '(' torna a pontuação exclusiva. ZCOUNT dá a contagem num intervalo sem buscar membros. ZINCRBY ajusta uma pontuação atomicamente e reordena — perfeito para leaderboards ao vivo. ZREMRANGEBYRANK é ótimo para manter um zset limitado (ex.: manter só o top 1000).
# get members by score range
ZRANGEBYSCORE leaderboard 100 200 # scores 100-200
ZRANGEBYSCORE leaderboard 100 +inf # scores >= 100
ZRANGEBYSCORE leaderboard -inf 200 # scores <= 200
ZRANGEBYSCORE leaderboard (100 200 # scores > 100 (exclusive)
# with pagination
ZRANGEBYSCORE leaderboard 100 200 LIMIT 0 10
# count members in a score range
ZCOUNT leaderboard 100 200
# increment a member's score atomically
ZINCRBY leaderboard 50 "alice" # alice += 50
# remove a member
ZREM leaderboard "bob"
# remove by rank range
ZREMRANGEBYRANK leaderboard 0 9 # remove lowest 10
ZREMRANGEBYSCORE leaderboard 0 100 # remove scores <= 100ZUNIONSTORE e ZINTERSTORE
ZUNIONSTORE/ZINTERSTORE combinam zsets com agregação configurável (SUM/MIN/MAX) e pesos — poderoso para pontuação ponderada (ex.: relevância = match_texto*2 + recencia*1). Redis 6.2 adicionou ZUNION/ZINTER/ZDIFF, que retornam resultados sem guardar (um comando a menos). São O(N*M) — cuidado com muitos sets grandes. A contagem de sets precede os nomes dos sets.
# combine multiple sorted sets
ZADD set1 1 "a" 2 "b"
ZADD set2 2 "a" 3 "c"
# union: sum scores by default (a = 1+2 = 3)
ZUNIONSTORE result 2 set1 set2
ZRANGE result 0 -1 WITHSCORES # a=3, b=2, c=3
# specify aggregation: SUM (default), MIN, MAX
ZUNIONSTORE result 2 set1 set2 AGGREGATE MAX # a=2, b=2, c=3
# apply weights to each set's scores
ZUNIONSTORE result 2 set1 set2 WEIGHTS 2 1 # set1 scores * 2
# intersection (only members in ALL sets)
ZINTERSTORE result 2 set1 set2 # only "a"
# Redis 6.2+: return without storing
ZUNION 2 set1 set2 WITHSCORES
ZINTER 2 set1 set2 WITHSCORES
ZDIFF 2 set1 set2 WITHSCORES
# count intersection (7.0+)
ZINTERCARD 2 set1 set2 LIMIT 0Intervalos Lexicográficos (BYLEX)
BYLEX habilita consultas de intervalo por membros quando as pontuações são iguais — transformando um sorted set num índice de strings auto-ordenado. Casos de uso: autocomplete (guarde palavras com pontuação 0, consulte intervalos de prefixo), dicionários ordenados. '[a' significa inclusivo, '(a' exclusivo, '-' início, '+' fim. Só faz sentido quando todas as pontuações são idênticas.
# when all scores are equal, sorted sets act as a sorted string set
ZADD myset 0 "apple" 0 "banana" 0 "cherry" 0 "date"
# range by lexicographical order
ZRANGEBYLEX myset "[a" "[c" # apple, banana, cherry
ZRANGEBYLEX myset "(a" "[c" # banana, cherry (a exclusive)
ZRANGEBYLEX myset "-" "[b" # from start to banana
ZRANGEBYLEX myset "[c" "+" # cherry to end
# count in a lex range
ZLEXCOUNT myset "[a" "[c" # 3
# remove by lex range
ZREMRANGEBYLEX myset "[a" "[b"
# Redis 6.2+: use ZRANGE with BYLEX
ZRANGE myset "[a" "[c" BYLEX
# limit results (pagination)
ZRANGEBYLEX myset "[a" "[c" LIMIT 0 10Padrão de Leaderboard
Sorted sets tornam leaderboards triviais: ZADD para atualizar pontuações, ZREVRANGE para o top N, ZREVRANK para a posição de um jogador. ZINCRBY atualiza pontuações atomicamente. Para leaderboards por intervalo de tempo (diário/semanal), use uma chave por período com TTL. A paginação usa ZREVRANGE com offset. Este é um dos casos de uso mais naturais e poderosos do Redis.
# build a leaderboard
ZADD leaderboard 100 "alice" 250 "bob" 150 "carol"
# top 10 players (highest scores)
ZREVRANGE leaderboard 0 9 WITHSCORES
# a player's rank (0 = top)
ZREVRANK leaderboard "alice"
# update a score (atomic)
ZINCRBY leaderboard 50 "alice"
# players within a score range (e.g., silver tier 100-199)
ZRANGEBYSCORE leaderboard 100 199
# percentile rank
total = ZCARD(leaderboard)
rank = ZREVRANK(leaderboard "alice")
# percentile = (total - rank) / total * 100
# pagination (page 3, 10 per page)
ZREVRANGE leaderboard 20 29 WITHSCORES
# time-bucketed leaderboards (weekly)
ZADD leaderboard:2025-W01 100 "alice"
EXPIRE leaderboard:2025-W01 604800 # 1 week TTLHashes
HSET, HGET e HGETALL
Hashes são ideais para guardar objetos — uma chave por objeto, campos por propriedade. Isso vence serializar JSON, porque você pode atualizar campos individuais atomicamente (HSET) sem ler-modificar-escrever. HGETALL retorna cada um dos campos; para hashes grandes, prefira HSCAN. Hashes usam codificação listpack quando pequenos (abaixo de ~128 campos), tornando-os eficientes em memória.
# a hash maps fields to values (like a small object)
HSET user:1 name "Alice" age 30 email "[email protected]"
# get a single field
HGET user:1 name # "Alice"
# get all fields and values
HGETALL user:1
# 1) "name" -> "Alice"
# 2) "age" -> "30"
# 3) "email" -> "[email protected]"
# get the number of fields
HLEN user:1 # 3
# get the string length of a field's value
HSTRLEN user:1 name # 5 (length of "Alice")
# set a field only if it doesn't exist
HSETNX user:1 status "new" # 1 if set, 0 if existed
# delete a field
HDEL user:1 email # removes the email fieldHMGET (Busca de Múltiplos Campos)
HMGET busca múltiplos campos em lote numa única ida e volta — muito mais rápido que chamadas HGET separadas. HSET (desde a 4.0) aceita múltiplos pares campo-valor, tornando HMSET obsoleto. HKEYS/HVALS retornam cada um dos nomes/valores de campos. HRANDFIELD (6.2+) é útil para amostragem (ex.: feature flags aleatórias). HGETALL bloqueia em hashes grandes — use HSCAN para iteração em produção.
# get multiple fields at once
HMGET user:1 name age # 1) "Alice" 2) "30"
HMGET user:1 name missing age # 1) "Alice" 2) nil 3) "30"
# set multiple fields (HSET supports multiple field-value pairs)
HSET user:1 name "Bob" age 25 email "[email protected]"
# HMSET is deprecated (use HSET with multiple fields)
# HMSET still works but returns OK instead of count
# get all field names
HKEYS user:1 # 1) "name" 2) "age" 3) "email"
# get all values
HVALS user:1 # 1) "Alice" 2) "30" 3) "[email protected]"
# check if a field exists
HEXISTS user:1 name # 1 if exists, 0 if not
# get a random field (6.2+)
HRANDFIELD user:1 # one random field name
HRANDFIELD user:1 3 WITHVALUES # 3 random fields + valuesHINCRBY (Campos Numéricos)
HINCRBY em campos de hash é atômico — perfeito para contadores por usuário (contagem de logins, visualizações, quantidades de carrinho). HINCRBYFLOAT suporta decimais. Hashes se auto-deletam quando o último campo é removido (HDEL). Isso torna hashes a estrutura ideal para objetos com contadores numéricos — muito mais eficiente que chaves de string separadas por contador.
# increment a numeric field atomically
HSET user:1:stats logins 0
HINCRBY user:1:stats logins 1 # logins = 1
HINCRBY user:1:stats logins 1 # logins = 2
HINCRBY user:1:stats logins -1 # logins = 1
# increment by a specific amount
HINCRBY user:1:stats page_views 10
# floating point increment
HINCRBYFLOAT user:1:stats score 0.5
# all HINCRBY operations are atomic
# perfect for per-user/per-object counters
# use case: shopping cart (product_id -> quantity)
HSET cart:user:1 product:100 2
HINCRBY cart:user:1 product:100 1 # now 3
HINCRBY cart:user:1 product:100 -1 # now 2
HDEL cart:user:1 product:100 # remove itemHSCAN (Iteração de Hash)
HGETALL bloqueia o servidor para hashes grandes — use HSCAN para iteração em produção. HSCAN é baseado em cursor: chame repetidamente até o cursor voltar a 0. COUNT é uma dica. Os resultados vêm como um array plano [campo, valor, campo, valor, ...] — pareie-os no seu código. Para hashes com milhões de campos, considere dividir em múltiplas chaves.
# HSCAN: cursor-based iteration (for large hashes)
HSCAN user:1 0 MATCH "na*" COUNT 10
# returns [cursor, [field, value, field, value, ...]]
# iterate all fields safely
cursor=0
while true:
cursor, fields = HSCAN user:1 cursor COUNT 100
process(fields)
if cursor == 0: break
# HGETALL is fine for small hashes (< 100 fields)
# HSCAN is required for large hashes to avoid blocking
# match field names with glob patterns
HSCAN user:1 0 MATCH "user:*" COUNT 1000
# no VALUES-only option; results are [field, value, field, value, ...]
# pair them up in your code
# COUNT is a hint — may return more or fewer than requested
# HSCAN never blocks; safe for production useCasos de Uso de Hash
Hashes brilham para objetos e contadores agrupados. Uma técnica de memória poderosa: quando você tem muitas chaves de string pequenas, agrupe-as num único hash — a codificação listpack usa muito menos custo que milhares de chaves individuais (cada uma com metadados). Esse 'key bucketing' pode cortar o uso de memória em 5-10x para valores pequenos. TTL no nível de campo (7.4+) é uma adição importante.
# 1. Store an object (user profile, config)
HSET config:app name "MyApp" version "2.0" debug "off"
# 2. Per-user counters
HINCRBY user:1:stats logins 1
HINCRBY user:1:stats page_views 1
HGET user:1:stats logins
# 3. Shopping cart (product_id -> quantity)
HSET cart:user:1 product:100 2
HINCRBY cart:user:1 product:100 1
HDEL cart:user:1 product:100
# 4. Feature flags
HSET feature_flags user:1 new_ui 1 beta 0
HGET feature_flags user:1 new_ui # 1
# 5. Session store with TTL
HSET session:abc user_id 1 data "..."
EXPIRE session:abc 1800 # 30 min
# 6. Hash field expiration (Redis 7.4+)
HEXPIRE user:1 60 FIELDS 1 session_token
HPTTL user:1 FIELDS 1 session_tokenGestão de Chaves
EXISTS, TYPE e DEL
EXISTS com múltiplas chaves retorna a contagem das existentes. TYPE retorna o tipo da estrutura de dados — sempre verifique antes de operar, para evitar erros WRONGTYPE (o tipo de uma chave é imutável pelo seu tempo de vida). DEL é bloqueante e pode travar o servidor em estruturas grandes; prefira UNLINK para chaves grandes. TYPE retorna 'none' para chaves inexistentes.
# check if a key exists
SET mykey "hello"
EXISTS mykey # 1
EXISTS missing # 0
EXISTS key1 key2 key3 # count of existing keys (multiple)
# get the type of a value
TYPE mykey # "string"
TYPE mylist # "list"
TYPE missing # "none"
# delete one or more keys
DEL mykey # 1 if deleted, 0 if not
DEL key1 key2 key3 # number of keys deleted
# delete is blocking for large keys — use UNLINK instead
# UNLINK deletes in a background thread
# check type before operating to avoid WRONGTYPE errors
TYPE mykey
# returns: string | list | hash | set | zset | stream | noneUNLINK (Delete Assíncrono)
UNLINK (4.0+) é a alternativa não bloqueante ao DEL para chaves grandes — remove a chave do keyspace imediatamente, mas libera a memória numa thread de segundo plano, prevenindo travas do servidor. Para chaves com milhões de elementos, sempre use UNLINK. FLUSHDB ASYNC / FLUSHALL ASYNC fazem o mesmo para deleção em massa. O pool de threads lazyfree cuida da liberação real.
# UNLINK: non-blocking delete (large keys)
UNLINK biglist bighash # returns count of deleted keys
# UNLINK removes the key from the keyspace immediately
# but frees the memory in a background thread
# compare:
DEL biglist # blocks until fully freed
UNLINK biglist # returns immediately, frees later
# for small keys, DEL and UNLINK are equivalent
# for large keys (millions of elements), UNLINK is essential
# flush database asynchronously (non-blocking)
FLUSHDB ASYNC
FLUSHALL ASYNC
# check what's being freed in background
INFO memory | grep lazyfreeRENAME e RENAMENX
RENAME move atomicamente uma chave para um nome novo, sobrescrevendo qualquer chave de destino existente (e seu valor). RENAMENX (6.2+) só renomeia se o destino não existir, prevenindo sobrescritas acidentais. O TTL é preservado na renomeação. RENAME é atômico — nenhum outro cliente vê um estado intermediário. Renomeação entre bancos não é suportada; use MOVE ou DUMP/RESTORE.
# rename a key (overwrites destination if it exists)
SET oldkey "value"
RENAME oldkey newkey # OK; oldkey is gone, newkey has "value"
# rename only if destination doesn't exist (6.2+)
RENAMENX oldkey newkey # 1 if renamed, 0 if newkey already exists
# rename preserves the type and TTL
SET tempkey "data" EX 3600
RENAME tempkey permkey # permkey now has TTL of ~3600s
TTL permkey # ~3600
# rename across databases is not supported
# use MOVE + RENAME, or DUMP/RESTORE for cross-db moves
# type is immutable — rename keeps the type
TYPE permkey # "string"
# renaming is atomicKEYS vs SCAN
KEYS bloqueia o servidor enquanto varre o keyspace inteiro — NUNCA use em produção em datasets grandes. SCAN é a alternativa segura para produção: baseada em cursor, não bloqueante, retorna um cursor que você segue até 0. SCAN pode retornar duplicatas ou perder chaves adicionadas durante a iteração, mas nunca bloqueia. COUNT é uma dica (pode retornar mais ou menos). Sempre trate o loop do cursor no seu código.
# KEYS: blocks the server while scanning — NEVER in production
KEYS * # all keys (DANGEROUS on large DBs)
KEYS user:* # keys matching pattern
KEYS session:*
# SCAN: cursor-based iteration (non-blocking, production-safe)
SCAN 0 MATCH user:* COUNT 100
# returns: [nextCursor, [key1, key2, ...]]
# continue until cursor returns to 0
SCAN <nextCursor> MATCH user:* COUNT 100
# scan by type (7.0+)
SCAN 0 TYPE hash
SCAN 0 MATCH user:* TYPE string COUNT 100
# SCAN is weakly consistent:
# - may return duplicates
# - may miss keys added during iteration
# - but NEVER blocks the server
# COUNT is a hint, not exactRANDOMKEY e DBSIZE
RANDOMKEY retorna uma chave aleatória sem removê-la — útil para amostragem. DBSIZE retorna a contagem exata de chaves no banco atual (O(1)). INFO keyspace mostra contagens por banco com estatísticas de expiração (keys, expires, avg_ttl). Para uma chave aleatória de um tipo específico, não há comando embutido — use SCAN + TYPE num loop.
# get a random key (O(1), does not remove)
RANDOMKEY # "user:1" or nil if db is empty
# get the number of keys in the current database
DBSIZE # 1234
# count keys across all databases (in a cluster)
# note: DBSIZE only counts the current db
SELECT 0; DBSIZE
SELECT 1; DBSIZE
# get keyspace info (keys per db with expiry info)
INFO keyspace
# db0:keys=1000,expires=500,avg_ttl=3600000
# db1:keys=50,expires=10,avg_ttl=60000
# scan with count for approximate size estimation
SCAN 0 COUNT 1 # get cursor + small sample
# find a random key of a specific type
# (no built-in; use SCAN + TYPE in a loop)Comandos OBJECT
OBJECT ENCODING revela a representação interna (depuração de memória). OBJECT IDLETIME acha chaves frias (candidatas ao despejo). OBJECT FREQ funciona só com maxmemory-policy LFU. MEMORY USAGE com SAMPLES 0 conta exatamente (o padrão amostra em coleções grandes). COMMAND DOCS (7.0+) retorna documentação estruturada. Essas ferramentas de introspecção ajudam a depurar inchaço de memória.
# OBJECT subcommands for introspection
OBJECT ENCODING mykey # internal encoding (embstr, raw, int, listpack, etc.)
OBJECT REFCOUNT mykey # reference count
OBJECT IDLETIME mykey # seconds since last access
OBJECT FREQ mykey # access frequency (LFU mode only)
# check memory usage of a key (bytes)
MEMORY USAGE mykey
MEMORY USAGE mykey SAMPLES 0 # exact count (slower for large keys)
# total memory used by the server
INFO memory | grep used_memory_human
# inspect a key's internal structure (debugging, can be slow)
DEBUG OBJECT mykey # raw internal info
# the encoding changes automatically as the structure grows
# e.g., hash: listpack -> hashtable when fields exceed threshold
# help understand a command
COMMAND INFO GET
COMMAND DOCS SET # structured docs (7.0+)Expiração e Persistência
EXPIRE e EXPIREAT
EXPIRE define TTL numa chave existente; SET com EX/PX/EXAT/PXAT faz isso atomicamente (preferido). As opções NX/GT/LT (7.0+) habilitam definição condicional de TTL — útil para 'só adicionar expiração se não houver' ou 'só estender, nunca encurtar'. TTL retorna -1 para chaves sem expiração, -2 para chaves inexistentes. A expiração é preguiçosa (verificada no acesso) mais varreduras periódicas em segundo plano.
# set expiration on an existing key (seconds)
SET mykey "value"
EXPIRE mykey 60 # expires in 60 seconds
EXPIRE mykey 60 NX # only set TTL if none exists (7.0+)
EXPIRE mykey 60 GT # only set if new TTL > current (7.0+)
EXPIRE mykey 60 LT # only set if new TTL < current (7.0+)
# set expiration in milliseconds
PEXPIRE mykey 60000
# set expiration at a Unix timestamp
EXPIREAT mykey 1700000000 # seconds
PEXPIREAT mykey 1700000000000 # milliseconds
# set value AND expiration atomically (preferred)
SET token "abc" EX 3600
SET token "abc" PX 3600000
SET token "abc" EXAT 1700000000
# get remaining TTL
TTL mykey # seconds (-1 = no expiry, -2 = no key)
PTTL mykey # millisecondsPERSIST (Remover TTL)
PERSIST remove o TTL, tornando uma chave persistente (o valor permanece). GETEX (6.2+) retorna atomicamente o valor e define ou remove o TTL — útil para renovar a expiração da sessão na leitura (GETEX chave EX 3600) ou tornar uma chave temporária permanente (GETEX chave PERSIST). COPY (6.2+) copia uma chave, opcionalmente entre bancos, sem a corrida de GET+SET.
# remove expiration (make key persistent)
SET session "data" EX 3600
TTL session # 3600
PERSIST session # 1 (success)
TTL session # -1 (no expiry)
# PERSIST returns 1 if the TTL was removed, 0 if key had no TTL or doesn't exist
# copy a key with optional TTL handling (6.2+)
COPY source dest # copy without TTL
COPY source dest REPLACE # overwrite destination
COPY source dest DB 1 # copy to another database
# GETEX: get value and optionally set/remove TTL (6.2+)
GETEX mykey EX 3600 # returns value, sets 3600s TTL
GETEX mykey PERSIST # returns value, removes TTL
# note: PERSIST only removes TTL; the key and value remainSAVE e BGSAVE (RDB)
SAVE bloqueia o servidor até o snapshot completar — nunca use em produção. BGSAVE bifurca o processo (copy-on-write) para que a thread principal não bloqueie, mas datasets grandes podem causar picos de memória durante a bifurcação. As regras 'save' disparam snapshots automáticos conforme a taxa de mudança. RDB é compacto e ideal para backups, mas arrisca perder dados escritos após o último snapshot.
# SAVE: synchronous snapshot (BLOCKS the server until done)
SAVE # blocks — use only in maintenance windows
# BGSAVE: background snapshot (non-blocking, forks a child)
BGSAVE # returns immediately, saves in background
LASTSAVE # Unix timestamp of the last successful save
# check if a BGSAVE is in progress
INFO persistence | grep rdb_bgsave_in_progress
# configure automatic snapshots in redis.conf:
# save 3600 1 # save if >= 1 key changed in 3600s
# save 300 100 # save if >= 100 keys changed in 300s
# save 60 10000 # save if >= 10000 keys changed in 60s
# save "" # disable RDB entirely
# RDB file location
CONFIG GET dbfilename # "dump.rdb"
CONFIG GET dir # "/var/lib/redis"
# RDB pros: compact, fast restart, great for backups
# RDB cons: potential data loss between snapshotsBGREWRITEAOF (Compactação AOF)
AOF acrescenta cada comando de escrita a um log — muito mais durável que RDB (no máximo 1 segundo de perda de dados com everysec). 'always' faz fsync a cada escrita (muito lento, use só para dados críticos). BGREWRITEAOF compacta o log (reescreve-o como o conjunto mínimo de comandos). Redis 7 usa um formato AOF multi-partes (base RDB + log incremental) — appenddirname guarda as partes.
# AOF: logs every write command (durable, replayable)
# enable in redis.conf:
# appendonly yes
# appendfilename "appendonly.aof"
# fsync policies:
# appendfsync always # fsync every write (safest, slowest)
# appendfsync everysec # fsync once per second (default, balanced)
# appendfsync no # let OS decide (fastest, risk of data loss)
# trigger AOF rewrite (compacts the log)
BGREWRITEAOF # non-blocking, rewrites in background
# AOF auto-rewrite thresholds:
# auto-aof-rewrite-percentage 100
# auto-aof-rewrite-min-size 64mb
# check AOF status
INFO persistence | grep aof
# AOF pros: minimal data loss (1 sec max with everysec)
# AOF cons: larger files, slower load on restart
# Redis 7: multi-part AOF (base + incremental files)
CONFIG GET appenddirname # "appendonlydir"Configuração de Persistência
CONFIG SET muda configurações em runtime (sem reinício); CONFIG REWRITE as persiste no redis.conf. O setup de produção recomendado é o híbrido RDB + AOF: RDB para reinício rápido e backups, AOF para perda mínima de dados. Desde o Redis 7, o AOF começa com um snapshot base RDB seguido de comandos incrementais — combinando carga rápida com durabilidade.
# view current persistence settings
CONFIG GET save
CONFIG GET appendonly
CONFIG GET appendfsync
CONFIG GET dir
CONFIG GET dbfilename
CONFIG GET appendfilename
# enable AOF at runtime
CONFIG SET appendonly yes
# change fsync policy at runtime
CONFIG SET appendfsync everysec
# disable RDB snapshots
CONFIG SET save ""
# persist config changes to redis.conf
CONFIG REWRITE
# hybrid persistence (recommended):
# RDB for fast restart + AOF for durability
# redis.conf:
# save 3600 1
# appendonly yes
# aof-use-rdb-preamble yes # RDB header in AOF (faster load)
# check persistence status
INFO persistenceBackup e Restauração
Faça backup do arquivo RDB (compacto, rápido) regularmente — é um snapshot consistente mesmo com o Redis rodando (copy-on-write). Para AOF, faça backup do diretório appendonly inteiro (multi-partes do Redis 7). Restaure parando o Redis, trocando os arquivos e reiniciando. Para se recuperar de um comando ruim, edite o AOF para removê-lo antes do reinício. redis-cli --rdb executa um backup online sem tocar no filesystem diretamente.
# backup: copy the RDB file while Redis runs
BGSAVE
# wait for LASTSAVE to update, then copy the file
cp /var/lib/redis/dump.rdb /backup/dump-$(date +%F).rdb
# AOF backup: copy the AOF manifest + files (Redis 7)
cp -r /var/lib/redis/appendonlydir /backup/
# restore: stop Redis, replace data files, restart
redis-cli SHUTDOWN
cp /backup/dump.rdb /var/lib/redis/dump.rdb
redis-server /etc/redis/redis.conf
# for point-in-time recovery from AOF:
# edit the AOF file to remove unwanted commands, then restart
# RDB file analysis (offline, safe)
redis-check-rdb /var/lib/redis/dump.rdb
redis-check-aof /var/lib/redis/appendonly.aof
# fix a truncated AOF
redis-check-aof --fix /var/lib/redis/appendonly.aof
# online backup with --rdb (dumps RDB to stdout/file)
redis-cli --rdb /backup/dump.rdbPub/Sub
SUBSCRIBE e UNSUBSCRIBE
SUBSCRIBE bloqueia o cliente para receber mensagens de um ou mais canais. Um cliente inscrito só pode chamar SUBSCRIBE/UNSUBSCRIBE/PSUBSCRIBE/PUNSUBSCRIBE/PING/QUIT — nenhum outro comando. PUBSUB introspecta o estado do pub/sub (canais ativos, contagens de inscritos). As mensagens são dispara-e-esquece: se nenhum inscrito está escutando, a mensagem se perde. Para entrega confiável, use Streams.
# subscribe to channels (in one client, blocks)
SUBSCRIBE news alerts
# the client now listens for messages:
# 1) "subscribe" 2) "news" 3) 1
# 1) "subscribe" 2) "alerts" 3) 2
# unsubscribe from specific channels
UNSUBSCRIBE news
UNSUBSCRIBE news alerts
# unsubscribe from ALL channels
UNSUBSCRIBE
# note: published messages are NOT persisted
# if no subscriber is listening, the message is lost
# for persistent messaging, use Streams instead
# count active subscriptions (in another client)
PUBSUB CHANNELS # list active channels
PUBSUB NUMSUB news # subscriber count for "news"PUBLISH
PUBLISH retorna o número de inscritos que receberam a mensagem (0 se nenhum). Não há como recuperar uma mensagem depois de publicada — se nenhum inscrito está escutando, ela se perde. PUBSUB CHANNELS lista os canais ativos (os com pelo menos um inscrito); PUBSUB NUMSUB retorna contagens de inscritos. Para mensagens confiáveis e reproduzíveis, use Streams (XADD/XREAD).
# publish a message to a channel (from another client)
PUBLISH news "Breaking: Redis 7.4 released"
# returns: number of subscribers that received the message
# publish to a channel with no subscribers
PUBLISH empty "hello"
# returns: 0 (message is lost)
# publish to multiple channels (separate PUBLISH calls)
PUBLISH news "msg1"
PUBLISH alerts "msg2"
# pub/sub has no persistence, no replay, no consumer groups
# subscribers must be connected to receive messages
# check how many clients are listening
PUBSUB NUMSUB news
PUBSUB NUMSUB news alerts # multiple channels
# list active channels (with pattern)
PUBSUB CHANNELS # all active channels
PUBSUB CHANNELS news:* # channels matching patternPSUBSCRIBE (Assinatura por Padrão)
PSUBSCRIBE assina canais que casem com padrões glob — poderoso para roteamento de eventos (ex.: user:*:login captura cada um dos eventos de login de usuários). Uma mensagem que case tanto com uma assinatura direta quanto com um padrão é entregue duas vezes. Inscritos por padrão recebem eventos 'pmessage' com o padrão, o canal e a mensagem. PUNSUBSCRIBE cancela assinaturas por padrão.
# subscribe to channels matching a glob pattern
PSUBSCRIBE news.*
PSUBSCRIBE user:*:login
PSUBSCRIBE events:*
# patterns use glob syntax:
# * matches any sequence
# ? matches one character
# [ab] matches 'a' or 'b'
# unsubscribe from patterns
PUNSUBSCRIBE news.*
PUNSUBSCRIBE # unsubscribe from ALL patterns
# a message matching both a direct subscription and a pattern
# is delivered twice (once for each)
# pattern subscribers receive:
# 1) "pmessage" 2) "news.*" 3) "news.tech" 4) "the message"
# use case: event routing
PSUBSCRIBE user:*:login # all user logins
PSUBSCRIBE order:*:created # all order creations
PSUBSCRIBE cache:*:invalidate # cache invalidation eventsPub/Sub Sharded (7.0+)
Pub/Sub Sharded (7.0+) resolve um problema do modo Cluster: o Pub/Sub regular transmite cada PUBLISH a cada um dos nós do cluster, desperdiçando banda. O Pub/Sub Sharded roteia mensagens só ao shard dono da chave do canal — muito mais eficiente em clusters grandes. Use SSUBSCRIBE/SPUBLISH em implantações Cluster. O nome do canal determina o shard (como uma chave).
# regular Pub/Sub broadcasts to ALL cluster nodes (expensive)
# sharded Pub/Sub routes messages only to the shard owning the channel
# subscribe to a shard channel
SSUBSCRIBE mychannel
# publish to a shard channel
SPUBLISH mychannel "hello"
# sharded pub/sub uses the channel name for shard routing
# so messages only travel within one shard (more efficient)
# use sharded pub/sub in a Redis Cluster to avoid
# broadcasting messages to every node
# regular SUBSCRIBE/PUBLISH still work in cluster mode
# but they broadcast to all shards (cluster-wide overhead)
# check shard channel subscribers (7.0+)
PUBSUB SHARDCHANNELS
PUBSUB SHARDNUMSUB mychannelNotificações de Keyspace
Notificações de keyspace permitem que clientes reajam a eventos do ciclo de vida das chaves (set, delete, expire, evict). Configure com notify-keyspace-events. São dispara-e-esquece (sem persistência) e não confiáveis — se o servidor Redis reinicia, eventos pendentes se perdem. Para processamento confiável de eventos, use Streams. Notificações de keyspace são ótimas para efeitos colaterais como limpeza ou aquecimento de cache.
# enable keyspace notifications (disabled by default)
CONFIG SET notify-keyspace-events "KEA"
# K = keyspace events, E = keyevent events
# g = generic (DEL, EXPIRE, ...), $ = string, l = list
# h = hash, s = set, z = sorted set, x = expired, e = evicted
# A = all except m (m = keymiss)
# subscribe to events on a specific key
SUBSCRIBE __keyspace@0__:mykey
# publishes "set", "del", "expire", etc.
# subscribe to events of a specific type
SUBSCRIBE __keyevent@0__:del
# publishes the key name that was deleted
# example: react when a key expires
SUBSCRIBE __keyspace@0__:session:abc
# receives "expired" when the key TTL ends
# example: react to all expired keys
SUBSCRIBE __keyevent@0__:expired
# check current setting
CONFIG GET notify-keyspace-eventsTransações
MULTI e EXEC
MULTI/EXEC agrupa comandos num bloco atômico e sequencial — nenhum outro cliente pode se intercalar. Os comandos são enfileirados (retornando QUEUED) e executados juntos no EXEC. Um erro de enfileiramento (nome de comando ruim) aborta a transação inteira. Um erro de runtime (tipo errado numa chave) pula só aquele comando — o resto executa. Isso difere das transações SQL.
# MULTI starts a transaction; commands are queued
MULTI
SET counter 1
INCR counter
INCR counter
GET counter
EXEC
# returns: 1) OK 2) 2 3) 3 4) "3"
# all queued commands execute atomically (no interleaving)
# other clients cannot run commands between MULTI and EXEC
# each queued command returns "QUEUED" until EXEC
MULTI
SET x 1
# "QUEUED"
INCR x
# "QUEUED"
EXEC
# 1) OK 2) 2
# the transaction is atomic: all or nothing (at queuing time)DISCARD (Cancelar Transação)
DISCARD cancela uma transação, limpando cada um dos comandos enfileirados e libertando a conexão do modo transação. Também limpa quaisquer chaves observadas com WATCH (veja WATCH). Após DISCARD, o cliente pode emitir comandos normais de novo. DISCARD é o equivalente ao 'rollback' — mas note que o Redis não suporta rollback parcial dentro do EXEC; erros de runtime pulam o comando falho, mas confirmam o resto.
# DISCARD cancels a transaction (clears all queued commands)
MULTI
SET x 1
INCR x
DISCARD
# OK — no commands are executed
# after DISCARD, the connection returns to normal mode
GET x
# (nil) or the previous value — nothing changed
# DISCARD also clears all WATCHed keys
WATCH counter
MULTI
INCR counter
DISCARD
# counter is no longer watched
# you must call MULTI before DISCARD
DISCARD
# ERR DISCARD without MULTIWATCH (Lock Otimista)
WATCH implementa lock otimista: se uma chave observada muda entre WATCH e EXEC, a transação é abortada (EXEC retorna nil). Este é o padrão Redis padrão para atomicidade de ler-modificar-escrever (já que o Redis não tem travas de linha). Sempre repita no nil. WATCH é verificado na hora do EXEC. UNWATCH cancela as observações (também ocorre no DISCONNECT). Uma chave observada modificada pelo mesmo cliente também aciona o aborto.
# WATCH monitors keys; if any change before EXEC, transaction aborts
WATCH counter
val = GET counter # read current value
MULTI
INCR counter # queue the update
EXEC # nil if counter changed -> retry
# typical pattern: read-modify-write with retry
WATCH key
current = GET key
new_value = compute(current)
MULTI
SET key new_value
EXEC
# if EXEC returns nil, the key changed — loop and retry
# UNWATCH cancels all watches
UNWATCH
# WATCH is checked at EXEC time, not during queuing
# if a watched key is modified (by any client, including yourself),
# EXEC returns nil and the transaction is not executedUNWATCH e Casos Extremos de WATCH
Após EXEC (seja a transação confirmada ou abortada por causa do WATCH), todas as observações são automaticamente limpas. O mesmo vale para DISCARD. Para repetir um loop de lock otimista, você precisa chamar WATCH de novo antes do próximo MULTI. WATCH dentro de MULTI é erro — WATCH sempre deve preceder MULTI. UNWATCH serve principalmente para cancelar observações sem entrar numa transação.
# UNWATCH cancels all watches
WATCH key1 key2
UNWATCH # both keys are no longer watched
# WATCH inside a MULTI is not allowed (error)
MULTI
WATCH key
# ERR WATCH inside MULTI is not allowed
# after EXEC (success or abort), watches are cleared
WATCH key
MULTI
SET key "new"
EXEC
# key is no longer watched after EXEC
# after DISCARD, watches are cleared
WATCH key
MULTI
DISCARD
# key is no longer watched
# re-WATCH after EXEC to retry the optimistic lock loop
WATCH key
val = GET key
MULTI
SET key newval
EXEC
# if nil, loop: WATCH key again, GET, MULTI, SET, EXECTratamento de Erros em Transações
O Redis tem dois tipos de erro em transações. Erros de enfileiramento (nome/aridade de comando ruim) abortam a transação inteira na hora do EXEC (EXECABORT) — nada roda. Erros de runtime (ex.: INCR num não inteiro) pulam só o comando falho — o resto executa. NÃO há rollback. Esta é uma diferença crítica dos bancos SQL. Valide seus dados antes do MULTI para evitar erros de runtime.
# two types of errors in transactions:
# 1. Queuing errors (bad command syntax) — aborts the WHOLE transaction
MULTI
SET key "value"
INCRBY key "notanumber" # error during queuing (wrong arity/type at parse)
GET key
EXEC
# EXECABORT Transaction discarded because of previous errors.
# NOTHING executes — not even the SET
# 2. Runtime errors (wrong type at execution) — skips ONLY that command
SET key "stringvalue"
MULTI
INCR key # queues fine (syntax OK)
SET otherkey "ok"
EXEC
# 1) (error) ERR value is not an integer
# 2) OK
# the INCR failed but SET otherkey succeeded — no rollback!
# lesson: Redis transactions do NOT have rollback like SQLPipelining
Básico de Pipeline
Pipelining agrupa comandos para reduzir idas e voltas de rede — dramaticamente mais rápido que comandos individuais pela rede. Cada ida e volta custa latência de rede (~0.1-1ms); 1000 comandos individuais = 100-1000ms, mas com pipeline = ~1ms. A maioria das bibliotecas cliente fornece uma função pipeline/multi. redis-cli pode fazer pipelining via stdin. Pipelining NÃO garante atomicidade — outros clientes podem se intercalar.
# pipelining sends multiple commands in one network round-trip
# (no atomicity guarantee, just reduced latency)
# using redis-cli with stdin (simple pipeline):
printf '%s\n' "SET k1 v1" "SET k2 v2" "GET k1" | redis-cli
# OK
# OK
# "v1"
# using redis-cli --pipe (raw RESP, fastest for bulk loads):
# (see the data-import-export section for details)
# in a client library (e.g., Node.js with ioredis):
const pipe = redis.pipeline()
pipe.set("k1", "v1")
pipe.set("k2", "v2")
pipe.incr("counter")
const results = await pipe.exec()
# vs individual commands:
await redis.set("k1", "v1") # round-trip 1
await redis.set("k2", "v2") # round-trip 2
await redis.incr("counter") # round-trip 3MULTI vs Pipelining
MULTI/EXEC garante atomicidade (nenhum outro cliente pode se intercalar) E é automaticamente pipelineado pela maioria das bibliotecas cliente (então você também ganha idas e voltas reduzidas). O pipelining simples só reduz idas e voltas — outros clientes podem executar entre seus comandos pipelineados. Use MULTI/EXEC quando precisar de atomicidade (ex.: ler-modificar-escrever com WATCH); use pipelining simples para operações em massa onde ordem/atomicidade não importam.
# MULTI/EXEC: atomic (no interleaving), pipelined automatically
MULTI
SET k1 v1
SET k2 v2
INCR counter
EXEC
# all 3 commands run atomically as one block
# Pipelining: NOT atomic, just batched (other clients can interleave)
# (in client code)
pipe.set("k1", "v1")
pipe.set("k2", "v2")
pipe.incr("counter")
pipe.exec()
# commands may interleave with other clients
# when to use which:
# - need atomicity (all-or-nothing)? -> MULTI/EXEC
# - just want speed (bulk operations)? -> pipelining
# - both? -> MULTI/EXEC (auto-pipelined)
# MULTI/EXEC is automatically pipelined by most clients
# so you get atomicity + batch round-trips in oneProtocolo RESP
RESP é o protocolo de transmissão do Redis — simples, baseado em texto e rápido. *N denota um array de N elementos; $N denota uma string em massa de N bytes; + é uma string simples; : é um inteiro; - é um erro. O modo redis-cli --pipe aceita RESP cru para carga em massa na velocidade máxima (muito mais rápido que comandos de texto via stdin). Entender RESP ajuda na depuração e na construção de clientes personalizados.
# RESP (REdis Serialization Protocol) is the wire format
# redis-cli sends RESP; you can also send it raw with --pipe
# simple command (PING) in RESP:
# *1\r\n$4\r\nPING\r\n
# SET key value in RESP:
# *3\r\n$3\r\nSET\r\n$3\r\nkey\r\n$5\r\nvalue\r\n
# RESP types:
# +OK simple string
# -ERR error
# :42 integer
# $5\r\nhello bulk string
# *2\r\n... array
# raw pipeline with RESP (fastest bulk insert):
# generate a RESP file and pipe it:
cat commands.resp | redis-cli --pipe
# --pipe mode expects raw RESP; checks reply counts
# output: "Last reply received from server: ..."
# "errors: 0, replies: N"Pipeline em Scripts de Shell
Scripting de shell com redis-cli é uma forma comum de carregar dados em massa ou rodar operações em lote. A abordagem mais simples conecta por pipe comandos de texto via stdin (echo/cat | redis-cli). Para velocidade máxima, gere RESP e use o modo --pipe (uma ordem de magnitude mais rápido para cargas grandes). Os exemplos de loop bash mostram ambas as abordagens — escolha pelo seu volume e necessidades de desempenho.
# pipeline multiple commands via stdin
echo -e "SET k1 v1\nSET k2 v2\nGET k1\nGET k2" | redis-cli
# pipeline from a file
cat commands.txt | redis-cli
# pipeline with --pipe-mode (raw RESP, fastest)
# first generate RESP, then pipe:
redis-cli --pipe < commands.resp
# bulk insert example (bash, generate RESP):
for i in $(seq 1 1000); do
printf '*3\r\n$3\r\nSET\r\n$4\r\nkey:\r\n$1\r\n%s\r\n' "$i"
done | redis-cli --pipe
# or simpler (text mode, slightly slower):
for i in $(seq 1 1000); do
echo "SET key:$i value$i"
done | redis-cli
# --pipe-mode reports errors and throughputLimites e Boas Práticas de Pipeline
Pipelining é a maior alavanca de desempenho do Redis, mas não abuse — respostas enfileiradas consomem memória no cliente e no servidor. Agrupe em lotes de 100-1000 comandos. Faça benchmark com redis-benchmark -P para achar seu ponto ideal (o rendimento estabiliza, a latência aumenta com pipelines muito grandes). Para comandos que dependem de resultados anteriores, use scripts Lua (atômicos, ida e volta única) em vez de múltiplas chamadas pipelineadas.
# don't pipeline too many commands at once
# (queued replies consume memory on both client and server)
# bad: 1 million commands in one pipeline
# -> huge memory buffer, potential timeout
# good: batch in groups of 100-1000
for batch in chunks(data, 500):
pipe = redis.pipeline()
for item in batch:
pipe.set(item.key, item.value)
pipe.exec()
# benchmark pipelining
redis-benchmark -t set -n 100000 -P 16 # -P = pipeline size
# try -P 1, 10, 100, 1000 to find the sweet spot
# use pipelining for:
# - bulk imports
# - batch reads (MGET is better for simple multi-get)
# - pre-warming cache
# - reducing latency in high-RTT environments
# avoid pipelining for:
# - commands that depend on previous results (use Lua instead)
# - very large batches (split into chunks)Scripting Lua
Básico de EVAL
EVAL roda scripts Lua atomicamente — enquanto um script roda, nenhum outro comando executa, tornando-o ideal para operações atômicas de múltiplos passos. KEYS e ARGV passam dados do chamador; nunca construa chaves por concatenação de string no script (viola as regras do cluster — todas as chaves devem estar em KEYS). redis.call lança erros (interrompe), redis.pcall os retorna. Scripts são cacheados pelo seu hash SHA1 para EVALSHA.
# EVAL: run a Lua script inline
# EVAL "script" numkeys key1 key2 ... arg1 arg2 ...
EVAL "return redis.call('GET', KEYS[1])" 1 mykey
# 1 = number of keys
# mykey = KEYS[1]
# run a simple script (no keys)
EVAL "return 42" 0
EVAL "return {1, 2, 3}" 0
EVAL "return 'hello'" 0
# a check-and-set script:
EVAL "
local cur = redis.call('GET', KEYS[1])
if cur == ARGV[1] then
return redis.call('SET', KEYS[1], ARGV[2])
end
return 0
" 1 mykey "expected" "newvalue"
# redis.call() raises error if command fails (stops script)
# redis.pcall() returns error as a table (can handle)
EVAL "local ok, err = pcall(redis.call, 'GET', 'missing'); return err" 0EVALSHA e SCRIPT LOAD
EVALSHA roda um script previamente carregado pelo seu hash SHA1, evitando reenviar o corpo do script a cada chamada — um grande ganho de banda para apps que rodam o mesmo script repetidamente. Em cache miss (após SCRIPT FLUSH ou reinício), Redis retorna NOSCRIPT; clientes capturam isso e recuem para EVAL + SCRIPT LOAD. Sempre use bibliotecas (redis-py, ioredis) que tratam isso de forma transparente.
# load a script once, get its SHA1
SCRIPT LOAD "return redis.call('GET', KEYS[1])"
# returns: "fa00d1f0..." (the SHA1 hash)
# execute by hash (saves bandwidth on repeated calls)
EVALSHA "fa00d1f0..." 1 mykey
# check if a script is cached
SCRIPT EXISTS "fa00d1f0..." "abcd1234..."
# 1) 1 2) 0 (1 = exists, 0 = not cached)
# flush the script cache
SCRIPT FLUSH
# list all running scripts (during debug)
SCRIPT DEBUG SYNC # blocking debug mode
SCRIPT DEBUG NO # disable debugger
# typical client library pattern:
# 1. SCRIPT LOAD the script on startup
# 2. EVALSHA to run it (falls back to EVAL on NOSCRIPT error)SCRIPT LOAD, FLUSH e EXISTS
SCRIPT LOAD cacheia um script e retorna seu SHA1. SCRIPT EXISTS verifica se scripts estão cacheados (útil após um reinício). SCRIPT FLUSH limpa cada um dos scripts cacheados — EVALSHA subsequentes retornam NOSCRIPT. SCRIPT KILL interrompe um script de longa duração, mas só se ele ainda não fez nenhuma escrita (para manter consistência); se fez, você precisa de SHUTDOWN NOSAVE. Scripts são efêmeros — use Functions (7.0+) para persistência.
# SCRIPT LOAD: load a script without running it
SCRIPT LOAD "return redis.call('SET', KEYS[1], ARGV[1])"
# returns the SHA1 hash
# SCRIPT EXISTS: check if scripts are cached (after load or restart)
SCRIPT EXISTS "abc123..." "def456..."
# 1) 1 2) 0
# SCRIPT FLUSH: clear the script cache
SCRIPT FLUSH
# all EVALSHA calls will now return NOSCRIPT until scripts are reloaded
# SCRIPT KILL: stop a running script (only if it hasn't written yet)
SCRIPT KILL
# if the script has already executed a write command:
# SHUTDOWN NOSAVE is the only way to stop it (extreme measure)
# scripts are ephemeral — they don't survive a restart
# use Redis Functions (7.0+) for persistent scripts
# check the script cache size
INFO memory | grep script_cacheKEYS e ARGV
KEYS[] carrega nomes de chaves (essencial para o roteamento do cluster — o cluster usa estes para determinar qual shard trata o script). ARGV[] carrega valores e parâmetros. Nunca fixe nomes de chaves no código dentro do script (ex.: redis.call('GET', 'mykey')) — isso quebra o roteamento do cluster, pois o cluster não sabe em qual shard 'mykey' vive. Sempre passe chaves via KEYS[]. O argumento numkeys diz ao Redis quantas KEYS esperar.
# KEYS[]: key names passed to the script
# ARGV[]: additional arguments (values, options)
# example: atomic increment with cap
EVAL "
local current = tonumber(redis.call('GET', KEYS[1]) or 0)
local max = tonumber(ARGV[1])
if current >= max then
return -1 -- cap reached
end
return redis.call('INCR', KEYS[1])
" 1 counter 100
# KEYS[1] = counter, ARGV[1] = 100
# example: move item between lists atomically
EVAL "
local item = redis.call('RPOP', KEYS[1])
if item then
redis.call('LPUSH', KEYS[2], item)
end
return item
" 2 source_list dest_list
# NEVER hardcode key names in scripts (breaks cluster routing)
# always pass keys via KEYS[] so the cluster can route correctlyOperações Atômicas com Lua
Scripts Lua são a forma canônica de fazer operações atômicas de múltiplos comandos no Redis (sem corrida de MULTI/EXEC). Compare-and-set, aquisição de semáforo, migrações de fila e limitação de taxa se beneficiam de tudo isso. Scripts bloqueiam o servidor enquanto rodam — mantenha-os curtos e evite loops sobre muitas chaves (podem travar outros clientes). Para trabalho muito longo, use Redis Functions (Redis 7.0+), que são declaradas e versionadas como stored procedures.
# atomic compare-and-set (only update if value matches)
EVAL "
local cur = redis.call('GET', KEYS[1])
if cur == ARGV[1] then
return redis.call('SET', KEYS[1], ARGV[2])
end
return 0
" 1 mykey "expected" "newvalue"
# atomic 'decrement if positive' (semaphore / rate limit)
EVAL "
local val = tonumber(redis.call('GET', KEYS[1]) or 0)
if val > 0 then
redis.call('DECR', KEYS[1])
return 1
end
return 0
" 1 semaphore
# atomic list pop + push (move between queues)
EVAL "
local item = redis.call('RPOP', KEYS[1])
if item then
redis.call('LPUSH', KEYS[2], item)
end
return item
" 2 source_queue dest_queue
# atomic rate limiter (fixed window)
EVAL "
local count = redis.call('INCR', KEYS[1])
if count == 1 then
redis.call('EXPIRE', KEYS[1], ARGV[1])
end
return count
" 1 rate:user:1 60Redis Functions (7.0+)
Functions (7.0+) melhoram os scripts EVAL: são nomeadas (não só hasheadas), organizadas em bibliotecas e persistem entre reinícios (scripts EVAL são efêmeros). Isso as torna mais fáceis de gerenciar e implantar. FCALL invoca uma função pelo nome. Functions são a forma moderna de adicionar lógica atômica no servidor. Como scripts, precisam ser determinísticas para a replicação. FUNCTION DUMP/RESTORE habilita backup e migração.
# FUNCTIONS are named, versioned Lua scripts (better than EVAL)
# register a function library
FUNCTION LOAD '#!lua name=mylib
redis.register_function("my_set",
function(keys, args)
return redis.call("SET", keys[1], args[1])
end
)'
# call a function by name
FCALL my_set 1 mykey "hello"
# list loaded libraries
FUNCTION LIST
FUNCTION LIST WITHCODE # include source
# get the function's code (for backup)
FUNCTION DUMP
# delete a library
FUNCTION DELETE mylib
# restore from a dump (for migration)
FUNCTION RESTORE <payload>
# functions persist across restarts (unlike EVAL scripts)
# they're saved in RDB/AOFGestão de Conexões
CLIENT LIST
CLIENT LIST mostra cada cliente conectado com endereço, idade, tempo ocioso, comando atual e flags — inestimável para achar vazamentos ou clientes travados. O campo 'idle' ajuda a notar conexões abandonadas. 'cmd' mostra o último comando (útil para achar um cliente rodando um comando lento). 'flags' indica o tipo de cliente (N=normal, M=mestre, S=escravo/réplica, P=pubsub, b=bloqueado). Filtre por TYPE na 7.0+.
# list all connected clients
CLIENT LIST
# fields: id, addr, laddr, fd, name, age, idle, flags, db, cmd, ...
# filter by type (7.0+)
CLIENT LIST TYPE normal # normal clients only
CLIENT LIST TYPE replica # replicas
CLIENT LIST TYPE pubsub # pub/sub subscribers
# filter by ID (7.0+)
CLIENT LIST ID 1 2 3
# output includes useful fields:
# addr=10.0.0.1:12345 remote address
# age=3600 seconds since connected
# idle=0 seconds since last command
# cmd=get last command executed
# db=0 current database
# flags=N N=normal, M=master, S=slave, P=pubsub
# count connected clients
CLIENT LIST | wc -lCLIENT SETNAME e GETNAME
CLIENT SETNAME rotula uma conexão para que você a identifique no CLIENT LIST — essencial para depurar vazamentos de conexão em ambientes multi-serviço. Defina o nome imediatamente após conectar no seu app (ex.: 'api-server:pid12345:pool1'). Nomes aparecem no campo 'name' do CLIENT LIST. Isso torna trivial descobrir qual serviço é dono de uma conexão travada ou com vazamento.
# name your connection (for identification in CLIENT LIST)
CLIENT SETNAME "my-app-worker-1"
# get the current connection's name
CLIENT GETNAME
# in application code, set the name immediately after connecting:
# redis-cli example:
redis-cli CLIENT SETNAME "debug-session"
# names appear in CLIENT LIST output:
CLIENT LIST
# ... name=my-app-worker-1 ...
# names are useful for:
# - identifying which app/pool a connection belongs to
# - finding leaks (connections that should have been closed)
# - debugging stuck clients
# - naming conventions: app:hostname:pid or pool:name
# names are limited to a reasonable length and cannot contain spacesCLIENT KILL
CLIENT KILL desconecta à força um cliente — útil para remover conexões travadas ou com vazamento. Mate por ADDR (ip:porta), ID, TYPE ou USER (ACL). MAXAGE (7.0+) mata clientes ociosos há mais de N segundos. SKIPME yes (padrão) impede matar a própria conexão. Use CLIENT LIST primeiro para achar o alvo, depois CLIENT KILL para desconectá-lo. As mortes são imediatas (sem desligamento gracioso).
# kill a client by address
CLIENT KILL ADDR 10.0.0.1:12345
# kill a client by ID
CLIENT KILL ID 42
# kill by type (7.0+)
CLIENT KILL TYPE normal # kill all normal clients
CLIENT KILL TYPE pubsub # kill all pub/sub clients
# kill by user (ACL, 6.0+)
CLIENT KILL USER appuser
# kill by address with skip-me
CLIENT KILL ADDR 10.0.0.1:0 SKIPME yes # don't kill myself
# kill all clients matching filters (7.0+)
CLIENT KILL TYPE normal MAXAGE 3600 # kill idle > 1h
# kill returns the number of clients killed
# use with caution — kills are immediate, no graceful shutdown
# common use: disconnect a stuck client consuming resources
CLIENT LIST
CLIENT KILL ID <id>CLIENT ID e INFO
CLIENT ID retorna um inteiro único, nunca reutilizado, para a conexão — útil para logs e correlação. CLIENT INFO dá informação detalhada sobre a própria conexão. CLIENT NO-EVICT (6.0+) protege as escritas de um cliente de acionar despejo (útil para escritas críticas). CLIENT REPLY controla se o servidor envia respostas (OFF para cargas em massa dispara-e-esquece, SKIP para um comando).
# get the current client's unique ID (never reused)
CLIENT ID
# get the current client's info (detailed)
CLIENT INFO
# id=42 addr=127.0.0.1:12345 laddr=127.0.0.1:6379 name= db=0 ...
# the ID is a monotonically increasing integer
# it's unique per connection and never reused
# useful for logging and tracking
# CLIENT NO-EVICT (6.0+): this client's writes won't trigger eviction
CLIENT NO-EVICT ON # protect this client from eviction
CLIENT NO-EVICT OFF # normal behavior
# CLIENT REPLY (6.0+): control reply mode
CLIENT REPLY ON # normal replies
CLIENT REPLY OFF # no replies
CLIENT REPLY SKIP # skip reply for next command only
# CLIENT UNPAUSE: resume processing after CLIENT PAUSE
CLIENT UNPAUSECLIENT PAUSE
CLIENT PAUSE bloqueia a execução de comandos de cada um dos outros clientes por N milissegundos — útil para snapshots, migrações e failovers de cluster seguros. O modo WRITE (7.0+) pausa só escritas, permitindo que as leituras continuem (menos disruptivo). O próprio cliente que pausa não é bloqueado. Durante a pausa, comandos enfileirados consomem memória, então mantenha as pausas curtas. CLIENT UNPAUSE retoma imediatamente.
# pause all client processing for N milliseconds
CLIENT PAUSE 10000 # pause for 10 seconds
# all other clients' commands are queued, not executed
# pause modes (7.0+):
CLIENT PAUSE 10000 ALL # pause all commands (default)
CLIENT PAUSE 10000 WRITE # pause only writes (reads continue)
# resume processing immediately
CLIENT UNPAUSE
# use cases:
# - safe snapshot/migration (pause writes, take consistent backup)
# - cluster failover (pause to ensure clean handoff)
# - debugging (pause to inspect state)
# during pause:
# - commands from OTHER clients are queued (memory grows)
# - the pausing client can still run commands
# - paused commands execute when the pause ends
# check if a pause is active
CLIENT INFO | grep flags
# 'P' flag = pausedLimites de Conexões e Timeout
maxclients limita conexões concorrentes (padrão 10000) — aumente se tiver muitos servidores de app ou pools de conexão. timeout desconecta clientes ociosos (0 = nunca; defina 300s por segurança). tcp-keepalive detecta conexões TCP mortas (padrão 300s). Cada cliente consome memória para o buffer de saída — monitore com INFO clients. client-output-buffer-limit impede que um cliente lento consuma toda a memória do servidor (especialmente importante para pub/sub e réplicas).
# max concurrent clients
CONFIG GET maxclients # default 10000
CONFIG SET maxclients 50000 # increase limit
# timeout: disconnect idle clients after N seconds
CONFIG GET timeout # default 0 (never)
CONFIG SET timeout 300 # 5 minutes
# TCP keepalive (detect dead connections)
CONFIG GET tcp-keepalive # default 300
CONFIG SET tcp-keepalive 60
# when maxclients is reached, new connections are rejected
# error: "ERR max number of clients reached"
# check current client count vs limit
INFO clients
# connected_clients:150
# blocked_clients:5
# maxclients:10000
# each connection uses memory (~a few KB for the output buffer)
# monitor for output buffer growth:
INFO clients | grep client_recent_max_output_buffer
# set output buffer limits (prevent one client from using all memory)
CONFIG GET client-output-buffer-limitGestão do Servidor
Seções do INFO
INFO é o comando primário de monitoramento — reporta memória, clientes, replicação, persistência e estatísticas numa tacada. Filtre seções (INFO memory) para reduzir a saída. Métricas-chave: used_memory_rss (pegada real), mem_fragmentation_ratio (ideal ~1.0-1.5), connected_clients, instantaneous_ops_per_sec, keyspace_hits/misses (taxa de acerto do cache). TIME retorna a hora do servidor para sincronização de relógios.
# comprehensive server information
INFO # all sections
INFO server # version, uptime, config
INFO clients # connected clients
INFO memory # memory usage, fragmentation
INFO persistence # RDB/AOF status
INFO stats # ops/sec, hit rate, keyspace
INFO replication # primary/replica state
INFO cpu # CPU usage
INFO keyspace # keys per database
INFO commandstats # command frequency
INFO errorstats # error frequency
# get a specific metric
INFO memory | grep used_memory_human
INFO stats | grep instantaneous_ops_per_sec
INFO replication | grep role
# check Redis version and mode
INFO server | grep redis_version
INFO server | grep redis_mode # standalone, cluster, sentinel
# get server time
TIME # [unix_timestamp, microseconds]CONFIG GET e SET
CONFIG SET muda configurações em runtime sem reiniciar o Redis — ideal para ajuste. CONFIG GET recupera os valores atuais (use padrões como CONFIG GET *memory*). Ajustes comuns em runtime: maxmemory + política de despejo, limiar do slowlog, timeout, limiares de codificação. Nem todas as configurações são alteráveis em runtime (ex.: porta, endereço de vinculação exigem reinício). Sempre teste mudanças de config em staging primeiro.
# view config (runtime changes with CONFIG SET)
CONFIG GET maxmemory
CONFIG GET maxmemory-policy
CONFIG GET save
CONFIG GET appendonly
CONFIG GET requirepass
# change config at runtime (no restart needed)
CONFIG SET maxmemory 4gb
CONFIG SET maxmemory-policy allkeys-lru
CONFIG SET slowlog-log-slower-than 10000 # 10ms in microseconds
CONFIG SET timeout 300
# view all config (large output)
CONFIG GET *
# get a specific pattern
CONFIG GET *max*
CONFIG GET *timeout*
# common runtime tweaks:
CONFIG SET maxclients 20000
CONFIG SET hash-max-listpack-entries 256
CONFIG SET appendfsync everysecCONFIG REWRITE
CONFIG REWRITE persiste as mudanças de CONFIG SET em runtime de volta ao redis.conf — o arquivo é atualizado no próprio local, preservando comentários e estrutura. Isso pontua a lacuna entre mudanças em runtime e persistência entre reinícios. Sempre faça backup do redis.conf antes do REWRITE (raramente causa problemas, mas segurança primeiro). Versione seu redis.conf, para que possa acompanhar e auditar mudanças ao longo do tempo.
# persist config changes to redis.conf
CONFIG REWRITE
# after CONFIG SET maxmemory 4gb
# CONFIG REWRITE updates redis.conf to include:
# maxmemory 4gb
# the original redis.conf is updated in-place
# comments and structure are preserved
# view the config file path
CONFIG GET *
# typical redis.conf (production):
# bind 127.0.0.1
# protected-mode yes
# port 6379
# maxmemory 4gb
# maxmemory-policy allkeys-lru
# save 3600 1
# appendonly yes
# appendfsync everysec
# tcp-keepalive 300
# timeout 0
# always back up redis.conf before CONFIG REWRITESLOWLOG
SLOWLOG registra comandos mais lentos que o limiar configurado (padrão 10ms = 10000us) — inestimável para achar os culpados da latência. Defina o limiar ao seu SLO (ex.: 5ms). Comandos lentos comuns: KEYS, SMEMBERS em sets enormes, HGETALL em hashes enormes, SORT em dados grandes. slowlog-max-len limita o log (padrão 128). Defina o limiar como 0 para registrar tudo (só depuração — alto custo).
# configure slow log (threshold in microseconds)
CONFIG SET slowlog-log-slower-than 10000 # 10ms (10000 us)
CONFIG SET slowlog-max-len 128 # keep last 128 entries
# view slow commands
SLOWLOG GET # last 10 (default)
SLOWLOG GET 5 # last 5
SLOWLOG GET 0 # all entries
# each entry:
# 1) id unique ID
# 2) timestamp Unix time
# 3) duration microseconds
# 4) command the command and args
# 5) client address:port
# 6) client name if set
# slowlog length
SLOWLOG LEN
# reset (clear all entries)
SLOWLOG RESET
# set threshold to 0 to log ALL commands (debugging)
# set to -1 to disable
CONFIG SET slowlog-log-slower-than 0MONITOR
MONITOR transmite cada comando de cada cliente em tempo real — ferramenta de depuração poderosa, mas com ENORME impacto de desempenho (aproximadamente corta o rendimento pela metade). NUNCA use MONITOR em produção, a menos que absolutamente necessário e só brevemente. É perfeito para staging: conecte o MONITOR, reproduza o problema, veja exatamente que comandos seu app envia. Para produção, use SLOWLOG, LATENCY MONITOR ou INFO commandstats em vez disso.
# MONITOR: real-time log of ALL commands (debugging only!)
MONITOR
# every command from every client is printed:
# 1700000000.123456 [0 10.0.0.1:12345] "SET" "key" "value"
# 1700000000.123567 [0 10.0.0.1:12345] "GET" "key"
# to stop monitoring, send any non-MONITOR command or disconnect
# press Ctrl+C in redis-cli
# WARNING: MONITOR has a HUGE performance impact
# it roughly halves throughput — use only for debugging
# use cases:
# - debugging what commands an app is sending
# - auditing command patterns
# - finding the source of unexpected writes
# safer alternatives for production:
# - SLOWLOG (only slow commands)
# - LATENCY MONITOR (specific events)
# - COMMANDSTATS in INFO (command frequency)
# MONITOR is best used in a staging/dev environmentMonitoramento LATENCY
LATENCY MONITOR acompanha eventos de latência (defina um limiar, ex.: 100ms). LATENCY DOCTOR analisa eventos recentes e sugere correções — um ótimo ponto de partida para diagnóstico. Eventos comuns: 'command' (comandos lentos), 'fork' (atraso de bifurcação do BGSAVE), 'expire-cycle' (varredura de expiração), 'aof-write' (atraso de fsync do AOF). LATENCY GRAPH mostra uma linha do tempo ASCII. Defina o limiar ao seu SLO e monitore regularmente.
# enable latency monitoring (threshold in ms)
CONFIG SET latency-monitor-threshold 100 # 100ms
# view latency events
LATENCY HISTORY event-name
LATENCY LATEST # most recent events
LATENCY HISTORY command
LATENCY HISTORY expire-cycle
# ASCII art graph of an event
LATENCY GRAPH command
# human-readable diagnosis and recommendations
LATENCY DOCTOR
# reset latency data
LATENCY RESET
LATENCY RESET event-name
# common events to monitor:
# command slow commands
# fast-command slow O(1) commands
# expire-cycle expiration cycle taking too long
# fork BGSAVE/BGREWRITEAOF fork taking too long
# aof-write AOF write delays
# unlink async delete delays
# check current threshold
CONFIG GET latency-monitor-thresholdCluster
CLUSTER INFO
CLUSTER INFO dá um resumo rápido de saúde: cluster_state deve ser 'ok' (cada um dos 16384 slots cobertos), cluster_slots_ok deve igualar 16384. cluster_known_nodes é a contagem total de nós; cluster_size é o número de primários. Se cluster_state for 'fail', alguns slots estão indisponíveis (provavelmente um primário e sua réplica ambos fora). Verifique de qualquer nó — a informação é de o cluster inteiro.
# cluster-wide health
CLUSTER INFO
# key fields:
# cluster_state:ok # ok or fail
# cluster_slots_assigned:16384 # total slots
# cluster_slots_ok:16384 # slots covered
# cluster_known_nodes:6 # total nodes
# cluster_size:3 # number of primaries
# cluster_current_epoch:7
# cluster_my_epoch:1
# cluster_state:ok means all slots are covered
# cluster_state:fail means some slots are unavailable
# check from any node in the cluster
redis-cli -p 7000 CLUSTER INFO
# other cluster commands require being in cluster mode
# (redis-server --cluster-enabled yes)CLUSTER NODES
CLUSTER NODES é a visão definitiva da topologia — uma linha por nó com ID, endereço, papel (mestre/escravo), o mestre que segue (para réplicas) e intervalos de slots. Procure flags 'fail' ou 'fail?' indicando nós insalubres. Os intervalos de slots mostram qual primário possui quais slots de hash (0-16383). CLUSTER SHARDS (7.0+) agrupa nós por shard (primário + suas réplicas).
# view the full cluster topology
CLUSTER NODES
# each line is a node:
# <id> <addr:port@cport> <flags> <master> <ping-sent> <pong-recv> <epoch> <link> <slots>
# flags include:
# M = master (primary)
# S = slave (replica)
# mymaster = the node this replica follows
# fail? = suspected down
# fail = confirmed down
# handshake = new node joining
# nofailover = failover disabled
# example output:
# 1a2b... 127.0.0.1:7000@17000 myself,master - 0 0 1 connected 0-5460
# 3c4d... 127.0.0.1:7001@17001 master - 0 0 2 connected 5461-10922
# 5e6f... 127.0.0.1:7002@17002 master - 0 0 3 connected 10923-16383
# 7g8h... 127.0.0.1:7003@17003 slave 1a2b... 0 0 4 connected
# count nodes by type
CLUSTER NODES | grep -c master
CLUSTER NODES | grep -c slave
# Redis 7.0+: shard view
CLUSTER SHARDSCLUSTER KEYSLOT e COUNTKEYSINSLOT
CLUSTER KEYSLOT mostra a qual slot uma chave mapeia (CRC16 % 16384). Hash tags ({...}) forçam chaves relacionadas ao mesmo slot — essencial para operações multi-chave (MGET, transações, scripts Lua) num cluster. Use redis-cli -c (modo cluster) para seguir redirecionamentos MOVED automaticamente. CLUSTER GETKEYSINSLOT recupera chaves num slot (usado durante o resharding).
# get the hash slot for a key
CLUSTER KEYSLOT mykey # e.g., 1234
# CRC16(key) % 16384
# count keys in a specific slot (on the owning node)
CLUSTER COUNTKEYSINSLOT 1234
# get keys in a slot (must be run on the slot's owning node)
CLUSTER GETKEYSINSLOT 1234 10 # up to 10 keys
# in a cluster, keys must be on the same slot for multi-key ops
# use hash tags to force keys to the same slot:
SET {user:1}:profile "alice"
SET {user:1}:cart "items"
# both map to the same slot (the part inside {})
# CLUSTER KEYSLOT {user:1}:profile
# CLUSTER KEYSLOT {user:1}:cart
# same result -> same slot -> same shard
# if you access a key on the wrong node, you get a MOVED redirect:
# (error) MOVED 1234 127.0.0.1:7000
# redis-cli -c follows redirects automaticallyHash Tags
Hash tags ({...}) forçam chaves ao mesmo slot, habilitando operações multi-chave num cluster. Mas use-as com juízo — abusar de uma tag (ex.: {users}:1, {users}:2) cria um hotspot num shard. Projete as hash tags em torno dos padrões de acesso: agrupe chaves acessadas juntas (os dados de um usuário, os itens de um pedido), mas mantenha chaves não relacionadas separadas. Este é o desafio central de modelagem de dados em cluster.
# hash tags: the substring inside {} determines the slot
# {user:1}:profile and {user:1}:cart share a slot
# enabling multi-key operations in a cluster:
MSET {user:1}:name "Alice" {user:1}:age 30 # OK (same slot)
MSET user:1:name "Alice" user:2:age 30 # CROSSSLOT error
# transactions across keys (must be same slot)
WATCH {order:1}:items
MULTI
HINCRBY {order:1}:items product:1 1
HINCRBY {order:1}:total 10
EXEC
# Lua scripts accessing multiple keys (all keys must share a slot)
EVAL "..." 2 {user:1}:a {user:1}:b
# design hash tags carefully:
# - too broad -> hotspots (one shard overloaded)
# e.g., {users}:1, {users}:2 -> all on one shard (bad!)
# - too narrow -> can't do multi-key ops
# e.g., user:1:a, user:1:b -> different slots (can't MGET)
# good: {user:1}:* groups one user's data on one shard
# bad: {all-users}:* puts everyone on one shardCLUSTER FAILOVER
O failover do cluster é automático quando um primário fica inalcançável além de cluster-node-timeout (padrão 15s). Failover manual é para manutenção (atualizações sem indisponibilidade): FAILOVER é gracioso (espera a sincronização de replicação), FORCE pula a sincronização (mais rápido, leve risco de perda de dados), TAKEOVER contorna o consenso (só emergências, arrisca split-brain). Após o failover, o velho primário vira réplica quando retorna. Sempre rode com réplicas em produção.
# when a primary fails, its replica is promoted automatically
# manual failover (for maintenance), run on the REPLICA:
redis-cli -p 7001 CLUSTER FAILOVER # graceful (waits for sync)
redis-cli -p 7001 CLUSTER FAILOVER FORCE # without primary agreement (faster)
redis-cli -p 7001 CLUSTER FAILOVER TAKEOVER # force, may split brain (emergency)
# graceful failover steps:
# 1. replica stops syncing from master
# 2. master stops accepting writes
# 3. replica catches up on replication offset
# 4. replica is promoted to master
# 5. cluster is updated with new master info
# 6. old master becomes a replica when it returns
# CLUSTER RESET resets a node (HARD removes all data)
CLUSTER RESET HARD
CLUSTER RESET SOFT
# check failover status
CLUSTER INFO | grep cluster_state
# rolling upgrade pattern:
# for each replica: CLUSTER FAILOVER (becomes master), upgrade old masterFerramenta redis-cli --cluster
A ferramenta redis-cli --cluster cuida de operações complexas de cluster: criação, resharding, rebalanceamento, adição/remoção de nós, checagens de saúde e reparos. --cluster check é sua referência para verificar a saúde do cluster após mudanças. --cluster fix repara automaticamente problemas menores (slots órfãos etc.). --cluster call roda um comando em cada um dos nós. Use estes em vez de comandos CLUSTER manuais para tarefas operacionais.
# create a cluster (6 nodes: 3 primaries + 3 replicas)
redis-cli --cluster create \
host1:7000 host2:7000 host3:7000 \
host1:7001 host2:7001 host3:7001 \
--cluster-replicas 1
# check cluster health
redis-cli --cluster check host1:7000
# repair issues
redis-cli --cluster fix host1:7000
# reshard (move slots between nodes)
redis-cli --cluster reshard host1:7000
# prompts for: how many slots, target node, source nodes
# rebalance slots across all nodes
redis-cli --cluster rebalance host1:7000
# add a new node
redis-cli --cluster add-node newhost:7000 host1:7000
# add a replica
redis-cli --cluster add-node newhost:7001 host1:7000 \
--cluster-slave --cluster-master-id <nodeId>
# remove a node (migrates its slots first)
redis-cli --cluster del-node host1:7000 <nodeId>
# call a command on all nodes
redis-cli --cluster call host1:7000 INFO serverSentinel (HA)
Setup do Sentinel
Sentinel fornece HA sem sharding: monitora um primário, promove uma réplica em falha e reconfigura clientes. Quorum (o último número) é quantos sentinels precisam concordar que um primário caiu — defina (N/2)+1 para N sentinels. Implante 3 sentinels em máquinas separadas para tolerância a falhas. down-after-milliseconds deve ser > jitter de rede; baixo demais causa failovers falsos.
# Sentinel monitors a primary + replicas, handles failover
# sentinel.conf (port 26379):
sentinel monitor mymaster 192.168.1.10 6379 2
# name, host, port, quorum (number of sentinels to agree on failure)
sentinel down-after-milliseconds mymaster 30000 # 30s to declare down
sentinel failover-timeout mymaster 180000 # 3min failover timeout
sentinel parallel-syncs mymaster 1 # replicas to resync in parallel
# start a sentinel:
redis-sentinel /etc/redis/sentinel.conf
# or:
redis-server /etc/redis/sentinel.conf --sentinel
# deploy at least 3 sentinels (odd number) for quorum
# sentinels communicate with each other and the Redis nodes
# connect to a sentinel to find the current primary:
redis-cli -p 26379 SENTINEL get-master-addr-by-name mymaster
# sentinel auto-discovers other sentinels and replicasSENTINEL masters e réplicas
SENTINEL masters lista cada um dos primários monitorados; SENTINEL master <nome> dá detalhes (incluindo num-slaves e num-other-sentinels). SENTINEL replicas mostra as réplicas; SENTINEL sentinels mostra os sentinels pares. ckquorum verifica se você tem sentinels suficientes para um quorum — rode isto no monitoramento. Todas as principais bibliotecas cliente Redis suportam Sentinel nativamente (consultam os sentinels para achar o primário atual).
# query sentinel state
redis-cli -p 26379 SENTINEL masters # all monitored primaries
redis-cli -p 26379 SENTINEL master mymaster # details of one primary
# fields: name, ip, port, runid, role, ...
# num-slaves, num-other-sentinels
# quorum, down-after-milliseconds
# failover-timeout, parallel-syncs
# list replicas of a master
redis-cli -p 26379 SENTINEL replicas mymaster
# list other sentinels monitoring the same master
redis-cli -p 26379 SENTINEL sentinels mymaster
# count monitoring sentinels (should be >= quorum)
redis-cli -p 26379 SENTINEL sentinels mymaster | grep -c name
# check the number of OK sentinels
SENTINEL ckquorum mymaster
# "OK 3 usable Sentinels. Quorum and failover authorization can be reached"
# or "NOQUORUM" warning (not enough sentinels)SENTINEL get-master-addr-by-name
SENTINEL get-master-addr-by-name retorna o IP e a porta do primário atual — clientes chamam isto para descobrir o primário e depois conectar a ele. No failover, os sentinels retornam o endereço do novo primário. Clientes devem assinar os eventos +switch-master para saber dos failovers imediatamente. Este padrão de descoberta está embutido no modo Sentinel de todas as principais bibliotecas cliente Redis.
# find the current primary address
redis-cli -p 26379 SENTINEL get-master-addr-by-name mymaster
# 1) "192.168.1.10"
# 2) "6379"
# clients use this to discover the current primary
# on failover, the sentinel returns the new primary's address
# clients should connect to sentinels, NOT directly to the primary
# libraries: redis-py, jedis, ioredis all support sentinel mode
# example client connection (pseudo-code):
# 1. connect to a sentinel
# 2. SENTINEL get-master-addr-by-name mymaster
# 3. connect to the returned primary
# 4. on connection error, repeat from step 1
# monitor for failover events
redis-cli -p 26379 SUBSCRIBE +switch-master
# publishes: mymaster 192.168.1.10 6379 192.168.1.11 6379
# other events:
redis-cli -p 26379 SUBSCRIBE +failover-state
redis-cli -p 26379 SUBSCRIBE +sdown
redis-cli -p 26379 SUBSCRIBE +odownSENTINEL failover
SENTINEL failover aciona um failover manual (para atualizações rolando/manutenção). O failover automático ocorre quando um primário fica fora por mais que down-after-milliseconds. O failover é automático, mas causa breve interrupção de escrita (segundos). O líder sentinel eleito escolhe a réplica mais atualizada para promover. Quando o velho primário retorna, vira réplica — escritas que ele aceitou durante a partição de rede se PERDEM (risco de split-brain).
# force a manual failover (for maintenance)
SENTINEL failover mymaster
# triggers failover: promotes a replica to primary
# the failover process:
# 1. sentinels mark primary SDOWN (subjectively down)
# 2. quorum agrees -> ODOWN (objectively down)
# 3. a sentinel is elected leader
# 4. leader picks the best replica (most up-to-date)
# 5. promotes the replica: REPLICAOF NO ONE
# 6. reconfigures other replicas to follow the new primary
# 7. updates sentinel configs with the new primary address
# 8. clients reconnect via sentinel discovery
# during failover, writes fail briefly (seconds)
# reads from replicas continue (if the app uses them)
# the old primary, when it returns, is reconfigured as a replica
# of the new primary (its writes during partition are lost)
# monitor failover events:
redis-cli -p 26379 SUBSCRIBE +switch-master
redis-cli -p 26379 SUBSCRIBE +failover-*Quorum e Monitoramento do Sentinel
Quorum é o número de sentinels que precisam concordar que um primário caiu antes de acionar o failover — defina a maioria (N/2+1) para N sentinels. ckquorum verifica se você tem o suficiente. down-after-milliseconds deve ser > jitter de rede (30s é seguro). failover-timeout limita a duração do failover. parallel-syncs controla quantas réplicas sincronizam de novo simultaneamente (1 = seguro, mas lento). Sentinels atualizam a config sozinhos em mudanças de topologia.
# quorum: number of sentinels that must agree a master is down
# set in sentinel monitor command:
sentinel monitor mymaster 192.168.1.10 6379 2
# ^ quorum = 2
# for 3 sentinels: quorum = 2 (majority)
# for 5 sentinels: quorum = 3 (majority)
# check quorum status
SENTINEL ckquorum mymaster
# "OK 3 usable Sentinels" or "NOQUORUM"
# tune down-after-milliseconds (time before declaring down)
sentinel down-after-milliseconds mymaster 30000 # 30s default
# tune failover-timeout (max time for failover to complete)
sentinel failover-timeout mymaster 180000 # 3min default
# parallel-syncs: how many replicas resync simultaneously
sentinel parallel-syncs mymaster 1 # 1 at a time (safe, slow)
# view sentinel configuration
SENTINEL masters
SENTINEL master mymaster
# reset a master's state (clears discovered replicas/sentinels)
SENTINEL reset mymaster
# Sentinel automatically updates its config file when topology changesMonitoramento
Comando MONITOR
MONITOR transmite cada comando de cada cliente em tempo real. O formato de saída é: timestamp [db endereço_do_cliente] "comando" "args". Inestimável para depurar que comandos um app realmente envia. Mas aproximadamente corta o rendimento pela metade — use só em staging/dev ou para depuração breve de produção. Filtre com grep por padrões específicos. Para monitoramento de produção, use SLOWLOG, INFO commandstats ou LATENCY MONITOR.
# MONITOR: real-time log of ALL commands (debugging only!)
MONITOR
# every command from every client is printed:
# 1700000000.123456 [0 10.0.0.1:12345] "SET" "key" "value"
# 1700000000.123567 [0 10.0.0.1:12345] "GET" "key"
# format: <unix_time> [<db> <addr>] "<cmd>" "<arg>" ...
# the [0 ...] shows which database and client
# to stop monitoring: Ctrl+C or send any command
# filter for specific patterns (in another terminal):
redis-cli MONITOR | grep "SET"
redis-cli MONITOR | grep "10.0.0.1"
redis-cli MONITOR | grep -E "(SET|DEL)"
# WARNING: MONITOR roughly halves throughput
# use only for debugging, never in production
# safer alternatives:
# - SLOWLOG (only slow commands)
# - INFO commandstats (command frequency)
# - LATENCY MONITOR (latency events)Monitoramento LATENCY
LATENCY MONITOR acompanha picos de latência por tipo de evento. Defina um limiar (ex.: 100ms) e o Redis registra os eventos que o excedem. LATENCY DOCTOR analisa eventos recentes e sugere correções — um ótimo ponto de partida para diagnóstico. LATENCY GRAPH mostra uma linha do tempo ASCII. Culpados comuns: 'fork' (BGSAVE em datasets grandes), 'expire-cycle' (expiração em massa), 'aof-fsync-always' (fsync do AOF). Defina o limiar ao seu SLO e monitore regularmente.
# enable latency monitoring (threshold in ms)
CONFIG SET latency-monitor-threshold 100 # 100ms
# view recent latency events
LATENCY LATEST
# event, timestamp, last latency, max latency
# history of an event
LATENCY HISTORY command
LATENCY HISTORY expire-cycle
LATENCY HISTORY fork
# ASCII art graph
LATENCY GRAPH command
# human-readable diagnosis and recommendations
LATENCY DOCTOR
# reset latency data
LATENCY RESET
LATENCY RESET command
# common events:
# command slow commands (over threshold)
# fast-command slow O(1)/O(log N) commands
# expire-cycle key expiration sweep too slow
# fork BGSAVE/BGREWRITEAOF fork delay
# aof-fsync-always AOF fsync delay
# unlink async delete delay
# check threshold
CONFIG GET latency-monitor-thresholdMEMORY DOCTOR e STATS
MEMORY USAGE reporta bytes de uma chave (SAMPLES 0 para precisão total). MEMORY STATS dá estatísticas detalhadas do alocador. MEMORY DOCTOR fornece diagnóstico automatizado (procura fragmentação, chaves grandes etc.). Vigie mem_fragmentation_ratio: >1.5 desperdiça memória (fragmentação), <1 significa que o Redis está trocando para disco (catastrófico para a latência). MEMORY PURGE tenta devolver memória ao SO. A desfragmentação ativa (4.0+) recupera automaticamente memória fragmentada.
# MEMORY USAGE: bytes used by a single key
MEMORY USAGE mykey
MEMORY USAGE bigset SAMPLES 0 # exact (default samples for large keys)
# MEMORY STATS: detailed allocator stats
MEMORY STATS
# MEMORY DOCTOR: automated memory diagnosis
MEMORY DOCTOR
# MEMORY MALLOC-STATS: low-level allocator stats (jememalloc)
MEMORY MALLOC-STATS
# check total memory used
INFO memory | grep used_memory_human
# key metrics to watch:
# used_memory logical bytes used
# used_memory_rss RSS from OS (real footprint)
# used_memory_peak peak usage
# mem_fragmentation_ratio >1.5 = fragmentation, <1 = swapping (bad!)
# MEMORY PURGE: attempt to free memory back to OS
MEMORY PURGE
# active defragmentation (4.0+)
CONFIG SET activedefrag yesComandos DEBUG
Comandos DEBUG são para diagnóstico e teste — use com cuidado. DEBUG SLEEP testa como seu app trata latência (bloqueia o servidor). DEBUG OBJECT revela a codificação interna e o refcount de uma chave. DEBUG RELOAD salva, limpa e recarrega o dataset (útil para testar a persistência). São poderosos, mas perigosos — restrinja com ACLs em produção (a categoria -@admin ou -@dangerous). Nunca rode DEBUG num primário de produção sem entender o impacto.
# DEBUG SLEEP: block the server for N seconds (testing only!)
DEBUG SLEEP 2 # blocks for 2 seconds (testing latency)
# DEBUG OBJECT: raw internal info about a key
DEBUG OBJECT mykey
# Value at:0x7f... refcount:1 encoding:embstr serializedlength:12 ...
# DEBUG SET-ACTIVE-EXPIRE: toggle expiration sweeps
DEBUG SET-ACTIVE-EXPIRE 0 # disable expiration sweeps (debugging)
DEBUG SET-ACTIVE-EXPIRE 1 # re-enable
# DEBUG JMAP: memory map (jemalloc)
DEBUG JMAP
# DEBUG CHANGE-REPL-ID: change replication ID (advanced)
DEBUG CHANGE-REPL-ID
# DEBUG RELOAD: save RDB, flush, reload from RDB (testing)
DEBUG RELOAD
# DEBUG LOADAOF: reload from AOF (testing)
DEBUG LOADAOF
# WARNING: DEBUG commands can be dangerous
# use ACL to restrict them in production:
# ACL SETUSER default -@adminredis-cli --latency
redis-cli --latency mede continuamente o tempo de ida e volta — essencial para estabelecer a linha de base do desempenho de rede. --latency-history registra estatísticas móveis a cada 15s (use -i para mudar). --latency-dist mostra um histograma (visualiza jitter e latência de cauda). Para modo cluster, verifique a latência de cada nó separadamente. Estabeleça uma linha de base e depois monitore por picos. Latência >1ms no localhost indica um problema (CPU, pressão de memória ou comandos lentos).
# continuous latency measurement (round-trip time)
redis-cli --latency
# output: min: 0, max: 1, avg: 0.27 (3421 samples)
# latency history (rolling, every N seconds)
redis-cli --latency-history
# default interval: 15 seconds
# output: min: 0, max: 2, avg: 0.31 (1500 samples) -- 15.01 seconds
# custom interval (1 second)
redis-cli --latency-history -i 1
# latency distribution (histogram)
redis-cli --latency-dist
# shows a visual histogram of latency distribution
# latency to a remote host
redis-cli -h remote-host --latency
# use cases:
# - baseline your network latency
# - detect network issues (jitter, spikes)
# - compare latency before/after config changes
# - monitor latency over time with --latency-history
# for cluster mode, check latency to each node:
redis-cli -h node1 -p 7000 --latency &
redis-cli -h node2 -p 7000 --latency &redis-cli --stat
redis-cli --stat é como 'top' para Redis — mostra um resumo atualizável de chaves, memória, clientes, clientes bloqueados, requisições/seg e conexões. O (+N) ao lado das requisições mostra o delta desde a última amostra. Use para checagens rápidas de saúde e para notar anomalias (memória crescendo, clientes vazando, taxa de requisições explodindo). A coluna 'child' mostra se um filho BGSAVE/BGREWRITEAOF está rodando.
# --stat: continuous server stats (like top for Redis)
redis-cli --stat
# output (refreshes every second):
# ------- data ------ --------------------- load -------------------- - child -
# keys mem clients blocked requests connections
# 1000 1.50M 50 0 12345 (+12) 1000
# --stat shows:
# keys total keys in the db
# mem memory usage
# clients connected clients
# blocked blocked clients (BLPOP, etc.)
# requests total requests (+N since last sample)
# connections total connections since start
# child child process info (BGSAVE/BGREWRITEAOF)
# custom interval (every 5 seconds)
redis-cli --stat -i 5
# monitor a remote server
redis-cli -h host --stat
# use cases:
# - quick health check (are clients/memory/keys growing?)
# - spot traffic spikes (requests/second)
# - monitor during load tests
# - detect connection leaks (clients increasing steadily)
# combine with --no-raw for machine-readable outputSegurança
AUTH (Senha Legada)
AUTH é a autenticação de senha única legada (pré-Redis 6). No Redis 6+, use usuários ACL (AUTH usuario senha). A flag -a expõe a senha no histórico do shell — prefira a variável de ambiente REDISCLI_AUTH. Sempre use senhas fortes (64+ caracteres aleatórios). Em produção, combine AUTH com TLS, restrições de rede (bind/firewall) e menor privilégio baseado em ACL, para defesa em profundidade.
# set a password (simple, legacy)
CONFIG SET requirepass "strongpassword"
# authenticate (legacy, before Redis 6)
AUTH "strongpassword"
# OK
# authenticate as a specific user (Redis 6+ ACL)
AUTH appuser "secretpassword"
# OK
# connect with password via CLI
redis-cli -a "strongpassword"
redis-cli -a "strongpassword" --no-auth-warning # suppress warning
# safer: use environment variable
export REDISCLI_AUTH="strongpassword"
redis-cli # reads REDISCLI_AUTH automatically
# remove password
CONFIG SET requirepass ""
# AUTH returns ERR if the password is wrong
# after AUTH, all commands work normallyACL SETUSER
ACLs do Redis 6+ substituem o modelo de senha única — crie usuários com permissões delimitadas. A sintaxe: on (habilitado), >senha, ~padrao (padrões de chave), +comando/-comando, +@categoria/-@categoria (ex.: +@read, -@dangerous). Sempre crie um usuário de menor privilégio para cada app. O usuário padrão sempre existe — defina uma senha forte ou restrinja-o. Salve as ACLs num arquivo (ACL SAVE) para persistência.
# Redis 6+: ACL system with users and permissions
# create a user with limited access
ACL SETUSER appuser on >secretpassword ~app:* +get +set +del -@dangerous
# on = enabled
# >password = set password
# ~pattern = key patterns this user can access
# +command = allowed commands
# -command = denied commands
# +@category / -@category = allow/deny command categories
# categories: @read, @write, @admin, @dangerous, @keyspace, @connection, etc.
# create a read-only user
ACL SETUSER readonly on >pass ~* +@read -@dangerous
# create an admin user
ACL SETUSER admin on >adminpass ~* +@all
# create a user for a specific app (restricted keys)
ACL SETUSER app1 on >pass ~app1:* +@read +@write +@connection -@dangerous
# the default user (always exists)
ACL SETUSER default on >defaultpass ~* +@all -@dangerousACL LIST e GETUSER
ACL LIST mostra cada um dos usuários em formato compacto de regras. ACL GETUSER dá permissões detalhadas de um usuário (incluindo senhas hasheadas, comandos permitidos/negados, padrões de chave). ACL WHOAMI retorna o usuário atual. ACL LOG (7.0+) registra comandos negados e falhas de auth — útil para auditoria de segurança. ACL SAVE/LOAD gerenciam o arquivo ACL para persistência entre reinícios.
# list all users (compact rules)
ACL LIST
# 1) "user default on nopass ~* +@all"
# 2) "user appuser on #abc123... ~app:* +get +set +del -@dangerous"
# view a user's detailed permissions
ACL GETUSER appuser
# flags, passwords, commands, keys, channels, selectors
# view current user
ACL WHOAMI
# "appuser"
# view all users (just names, 7.0+)
ACL USERS
# delete a user
ACL DELUSER appuser
# save ACLs to a file (persists across restarts)
ACL SAVE
# reload ACLs from file
ACL LOAD
# aclfile in redis.conf:
# aclfile /etc/redis/users.acl
# view current user's rules
ACL LOG # security audit log (7.0+)
ACL LOG RESET # clear the audit logACL WHOAMI e DELUSER
ACL WHOAMI identifica o usuário atual. ACL DELUSER remove um usuário (e desconecta suas conexões ativas). Definir um usuário como 'off' o desativa temporariamente sem deletar suas regras — útil para suspender acesso. ACL LOG registra eventos de segurança (comandos negados, auth falha) — monitore-o por atividade suspeita. Rotacione senhas regularmente com ACL SETUSER >novasenha.
# get the current authenticated user
ACL WHOAMI
# "appuser"
# switch user (re-authenticate)
AUTH adminuser "adminpass"
ACL WHOAMI
# "adminuser"
# delete a user (disconnects their clients)
ACL DELUSER tempuser
# temporarily disable a user (keeps the rules, blocks login)
ACL SETUSER appuser off
# the user cannot authenticate, but their rules are preserved
# re-enable:
ACL SETUSER appuser on
# rotate a user's password
ACL SETUSER appuser >newpassword
# remove a user's password
ACL SETUSER appuser <secretpassword # remove this password
# or remove all passwords:
ACL SETUSER appuser resetpass
# view the audit log (denied commands, auth failures)
ACL LOG
ACL LOG COUNT 5 # last 5 entries
ACL LOG RESET # clear the logrename-command (Desabilitar Comandos)
rename-command (no redis.conf) desabilita ou renomeia comandos perigosos — defina "" para desabilitar, ou uma string para renomear. Exige reinício (não alterável em runtime). No Redis 6+, prefira ACLs (-flushall, -@dangerous), que são alteráveis em runtime e por usuário. Comandos que valem restringir: FLUSHALL/FLUSHDB (perda de dados), KEYS (bloqueia o servidor), CONFIG (segurança), DEBUG (pode derrubar), SHUTDOWN (para o servidor).
# rename or disable dangerous commands (in redis.conf)
rename-command FLUSHALL ""
rename-command FLUSHDB ""
rename-command CONFIG "CONFIG_9f8a7b"
rename-command KEYS ""
rename-command DEBUG ""
rename-command SHUTDOWN "SHUTDOWN_7x9y"
# "" completely disables the command (returns error)
# a string renames it (must use the new name)
# Redis 6+: prefer ACLs instead of rename-command
# ACL SETUSER default -flushall -config -keys -@dangerous
# view available commands (after rename/restrictions)
COMMAND
# note: rename-command requires a restart (not changeable at runtime)
# ACLs are runtime-changeable and more flexible
# dangerous commands to restrict:
# FLUSHALL, FLUSHDB - delete all data
# KEYS - blocks server
# CONFIG - can change security settings
# DEBUG - can crash the server
# SHUTDOWN - stops the server
# MONITOR - performance impactCriptografia TLS/SSL
TLS criptografa dados em trânsito — essencial em produção, especialmente em redes não confiáveis. Redis 6+ suporta TLS nativamente. mTLS (tls-auth-clients yes) exige que clientes apresentem um certificado, fornecendo autenticação mútua sem senhas. Para cluster/sentinel, habilite TLS também na comunicação entre nós. Porta 0 desativa texto puro; durante a migração, rode ambas as portas temporariamente. Sempre use certificados devidamente assinados por CA em produção.
# enable TLS in redis.conf (Redis 6+)
port 0 # disable plain-text port
tls-port 6379
tls-cert-file /etc/redis/redis.crt
tls-key-file /etc/redis/redis.key
tls-ca-cert-file /etc/redis/ca.crt
# connect with TLS
redis-cli --tls --cert client.crt --key client.key \
--cacert ca.crt -h host -p 6379
# mutual TLS (mTLS) for client authentication
tls-auth-clients yes # require client certs
tls-auth-clients no # don't require (default)
tls-auth-clients optional # verify if provided
# TLS for cluster and replication
tls-cluster yes # TLS between cluster nodes
tls-replication yes # TLS between primary/replica
# mix TLS and plain text (transition period)
# port 6380
# tls-port 6379
# generate self-signed certs for testing:
# openssl req -x509 -newkey rsa:4096 -keyout redis.key \
# -out redis.crt -days 365 -nodesImportação e Exportação de Dados
redis-cli --rdb (Backup)
redis-cli --rdb executa um backup online — transmite o RDB para um arquivo sem tocar no filesystem do servidor diretamente. É não bloqueante (usa a bifurcação em segundo plano do BGSAVE) e seguro para produção. Combinado com SSH, você pode fazer backup de um Redis remoto num arquivo local. Verifique os backups com redis-check-rdb. Agende backups regulares via cron. Sempre teste os procedimentos de restauração — um backup não testado não é um backup.
# dump the RDB snapshot to a file (online backup)
redis-cli --rdb /backup/dump.rdb
# Output: RDB file written to /backup/dump.rdb
# dump RDB to a remote host's file (via SSH):
ssh remote-host "redis-cli --rdb /tmp/dump.rdb"
# the --rdb flag:
# - connects to Redis and requests a BGSAVE
# - streams the RDB to the specified file
# - non-blocking (uses the background fork)
# - safe to run on a production server
# verify the RDB file
redis-check-rdb /backup/dump.rdb
# restore: stop Redis, replace dump.rdb, restart
redis-cli SHUTDOWN
cp /backup/dump.rdb /var/lib/redis/dump.rdb
redis-server /etc/redis/redis.conf
# schedule regular backups:
# 0 2 * * * redis-cli --rdb /backup/dump-$(date +\%F).rdbredis-cli --pipe (Inserção em Massa)
redis-cli --pipe é a forma mais rápida de carregar dados em massa no Redis — transmite RESP cru e não espera respostas até o fim. Gere RESP com printf ou um script. --pipe reporta erros e o total de respostas. Para cargas mais simples/pequenas, conectar comandos de texto por pipe (echo | redis-cli) funciona, mas é mais lento. Sempre faça benchmark: --pipe pode carregar milhões de chaves em minutos. Fique de olho na memória durante cargas grandes.
# --pipe: bulk load raw RESP data (fastest method)
# generate RESP and pipe it:
# example: bulk SET commands (bash)
for i in $(seq 1 100000); do
printf '*3\r\n$3\r\nSET\r\n$%d\r\nkey:%d\r\n$%d\r\nvalue%d\r\n' \
$((4 + ${#i})) $i $((5 + ${#i})) $i
done | redis-cli --pipe
# simpler text mode (slower but easier):
for i in $(seq 1 100000); do
echo "SET key:$i value$i"
done | redis-cli
# --pipe mode output:
# All data transferred. Waiting for the last reply...
# Last reply received from server.
# errors: 0, replies: 100000
# prepare RESP from a CSV/data file:
# (each line: key,value)
while IFS=, read -r key value; do
printf '*3\r\n$3\r\nSET\r\n$%d\r\n%s\r\n$%d\r\n%s\r\n' \
${#key} "$key" ${#value} "$value"
done < data.csv | redis-cli --pipeDUMP e RESTORE
DUMP serializa o valor de uma chave num blob binário (inclui tipo e valor, mas não TTL — especifique o TTL no RESTORE em milissegundos). RESTORE desserializa numa chave, funcionando entre instâncias Redis diferentes (ótimo para migrações). O formato serializado é específico de versão — um blob do Redis 4.x pode não carregar na 7.x; sempre verifique a compatibilidade. Para cópias dentro da instância, prefira o comando COPY nativo (6.2+) a DUMP+RESTORE.
# DUMP: serialize a key's value (binary blob)
DUMP mykey
# returns a serialized blob (binary, includes type + value + TTL info)
# RESTORE: deserialize into a key
RESTORE newkey 0 <serialized_blob>
# 0 = no TTL (milliseconds); set a TTL otherwise
RESTORE newkey 3600000 <blob> # 1 hour TTL
RESTORE newkey 0 <blob> REPLACE # overwrite if exists
# copy a key (6.2+ does this natively with COPY)
# manual copy via DUMP + RESTORE:
SET source "value"
blob = DUMP source
RESTORE dest 0 blob
# DUMP/RESTORE preserve the type but NOT the TTL
# (TTL must be specified in RESTORE)
# DUMP/RESTORE work across different Redis instances
# (migrate data between servers)
# note: serialized format is version-specific
# a blob from Redis 4.x may not load in 7.x — verify compatibility
# use COPY (6.2+) instead for in-instance copies:
COPY source dest # copy without TTL
COPY source dest REPLACE # overwrite destination
COPY source dest DB 1 # copy to another database
COPY source dest REPLACE DB 1 # bothMIGRATE (Mover entre Servidores)
MIGRATE move (ou copia) atomicamente uma chave entre instâncias Redis — a chave nunca está nos dois lugares ao mesmo tempo (atômico). É o bloco de construção do resharding do cluster. COPY mantém a chave de origem; o padrão a deleta. REPLACE sobrescreve uma chave de destino existente. Para múltiplas chaves, passe uma string vazia como chave e liste-as com KEYS. Defina o timeout alto o bastante para valores grandes. MIGRATE é bloqueante nas duas pontas durante a transferência.
# MIGRATE: atomically move a key from one Redis to another
# syntax: MIGRATE host port key|"" dest-db timeout [COPY] [REPLACE]
# [AUTH password] [KEYS key1 key2 ...]
# move a single key (default: deletes from source after copy)
MIGRATE 192.168.1.20 6379 mykey 0 5000
# host, port, key, dest-db, timeout-ms
# copy without deleting from source
MIGRATE 192.168.1.20 6379 mykey 0 5000 COPY
# overwrite if the key exists on destination
MIGRATE 192.168.1.20 6379 mykey 0 5000 REPLACE
# migrate multiple keys (pass "" as the key, then KEYS ...)
MIGRATE 192.168.1.20 6379 "" 0 5000 KEYS key1 key2 key3
# authenticate with the destination
MIGRATE 192.168.1.20 6379 mykey 0 5000 AUTH destpassword
# MIGRATE is atomic: the key appears on exactly one instance at any moment
# timeout is in milliseconds — large keys need longer timeouts
# returns NOKEY if the key doesn't exist on sourceCOPY (Cópia na Instância)
COPY (6.2+) duplica uma chave dentro da mesma instância atomicamente — muito mais simples que DUMP+RESTORE. NÃO copia o TTL por padrão (use EXPIRE depois). COPY funciona entre bancos com a opção DB. REPLACE sobrescreve um destino existente. Para cópias entre instâncias, use MIGRATE (que é atômico pela rede). COPY é o substituto moderno do padrão DUMP+RESTORE para duplicação na instância.
# COPY: duplicate a key within the same instance (6.2+)
COPY source dest # copy value (no TTL by default)
COPY source dest REPLACE # overwrite destination if it exists
COPY source dest DB 1 # copy to another database
COPY source dest REPLACE DB 1 # both options
# before COPY existed, you needed DUMP + RESTORE:
SET src "hello"
blob = DUMP src
RESTORE dst 0 blob
# COPY preserves the type (string, list, hash, ...)
SET mystr "hello"
COPY mystr mystr_copy
TYPE mystr_copy # "string"
# COPY does NOT copy TTL by default — use after EXPIRE if needed
SET temp "data" EX 3600
COPY temp temp_copy
TTL temp_copy # -1 (no TTL)
EXPIRE temp_copy 3600 # set TTL manually
# COPY is atomic and never blocks (unlike DUMP on huge keys)redis-check-rdb e redis-check-aof
redis-check-rdb e redis-check-aof verificam a integridade dos arquivos de persistência — sempre rode-os nos backups antes de restaurar. redis-check-aof --fix recupera de um AOF truncado removendo a cauda incompleta (pede confirmação). Redis 7 usa um AOF multi-partes (base + incrementais) — verifique o arquivo manifest. Estas ferramentas são somente leitura, exceto --fix, tornando-as seguras de rodar a qualquer momento. Valide os backups religiosamente — um backup não verificado não é um backup.
# verify the integrity of an RDB file (offline, safe)
redis-check-rdb /var/lib/redis/dump.rdb
# outputs: [offset] Checksum OK | CRC error | file truncated
# verify an AOF file
redis-check-aof /var/lib/redis/appendonly.aof
# outputs: AOF analyzed: size=... ok_up_to=... ok_up_to_line=...
# fix a truncated AOF (interactive prompt)
redis-check-aof --fix /var/lib/redis/appendonly.aof
# Redis 7 multi-part AOF: check the manifest
redis-check-aof --manifest /var/lib/redis/appendonlydir/appendonly.aof.manifest
# truncate an RDB to a specific offset (recovery)
redis-check-rdb --fix /var/lib/redis/dump.rdb
# use cases:
# - verify a backup before restore
# - diagnose corruption after a crash
# - recover from a truncated AOF (removes the incomplete tail)
# - validate files copied across servers
# always run these checks BEFORE replacing production data filesTestes de Desempenho
Básico do redis-benchmark
redis-benchmark é a ferramenta de teste de carga embutida do Redis — simula clientes concorrentes e reporta rendimento (requisições/seg) e percentis de latência. -t seleciona testes (PING, SET, GET, INCR etc.); -n define a contagem de requisições; -d define o tamanho do payload. Sempre faça benchmark em hardware equivalente à produção, para estabelecer a linha de base do desempenho. Os 50 clientes paralelos padrão são um começo — ajuste -c para casar com sua carga real. Rode benchmarks antes e depois de mudanças de config para medir o impacto.
# redis-benchmark: built-in performance benchmarking tool
# runs commands against a Redis server and reports throughput/latency
# default benchmark (50 parallel clients, 100000 requests)
redis-benchmark
# default commands: PING, SET, GET, INCR, LPUSH, RPUSH, LPOP, RPOP,
# SADD, HSET, SPOP, ZADD, ZPOPMIN, LRANGE_100, LRANGE_300, ...
# run a specific command only
redis-benchmark -t set,get -n 100000
# -t = test (comma-separated commands)
# -n = number of requests
# test a specific command with custom data
redis-benchmark -t set -n 100000 -d 100
# -d = data size in bytes (default 3)
# output example:
# ====== SET ======
# 100000 requests completed in 0.85 seconds
# 50 parallel clients
# 3 bytes payload
# keep alive: 1
# 98.90% <= 1 milliseconds
# 100.00% <= 1 milliseconds
# 117647.05 requests per second
# run against a remote server with auth
redis-benchmark -h host -p 6379 -a password -t set,get -n 100000Ajuste de Pipeline e Concorrência
As duas maiores alavancas de rendimento são -c (concorrência) e -P (tamanho do pipeline). -c aumenta os clientes paralelos (mais requisições em andamento); -P agrupa comandos por ida e volta (menos custo de rede). Combinados, podem empurrar o rendimento 10-20x. Benchmarks de cliente único (-c 1) medem latência pura; benchmarks multi-cliente medem rendimento. Payloads maiores (-d) deslocam o gargalo para a banda de rede. Sempre ajuste -c/-P para casar com o comportamento real da sua biblioteca cliente.
# -c = number of parallel connections (clients)
redis-benchmark -t set -n 100000 -c 50 # default: 50 clients
redis-benchmark -t set -n 100000 -c 200 # 200 concurrent clients
redis-benchmark -t set -n 100000 -c 1 # single client (latency focus)
# -P = pipeline size (commands per round-trip)
redis-benchmark -t set -n 100000 -P 1 # no pipelining (baseline)
redis-benchmark -t set -n 100000 -P 16 # pipeline 16 commands
redis-benchmark -t set -n 100000 -P 100 # pipeline 100 commands
# combine -c and -P for max throughput
redis-benchmark -t set -n 100000 -c 50 -P 16
# typical results (localhost, small values):
# -c 1 -P 1 -> ~100k req/s (latency-bound)
# -c 50 -P 1 -> ~600k req/s (concurrency)
# -c 50 -P 16 -> ~2M req/s (pipelining)
# test with a larger payload (network-bound)
redis-benchmark -t set -n 100000 -d 1024 # 1KB values
redis-benchmark -t set -n 100000 -d 65536 # 64KB valuesPercentis de Latência e Saída CSV
Sempre olhe os percentis de latência (P50, P99, P99.9), não só as médias — as médias escondem picos de latência de cauda que prejudicam a experiência do usuário. Um P99 5x pior que o P50 indica jitter (GC, rede ou comandos lentos). --csv produz resultados legíveis por máquina, para acompanhar tendências ao longo do tempo. Salve benchmarks antes e depois de mudanças de config para medir o impacto objetivamente. Acompanhe a latência P99 e as requisições/seg juntas — otimizar uma à custa da outra é uma armadilha comum.
# --csv: CSV output (easy to parse / log)
redis-benchmark -t set,get -n 100000 --csv
# output: "test","rps","avg_latency_ms","min_latency_ms",...
# "SET","117647.05","0.284","0.144"
# "GET","125000.00","0.272","0.136"
# --precision: set decimal places for latency
redis-benchmark -t set -n 100000 --precision 4
# latency percentiles (Redis 6+):
# the default output shows "X% <= Y milliseconds" lines
# ====== SET ======
# 50.00% <= 0.239 milliseconds
# 99.00% <= 0.511 milliseconds
# 99.90% <= 1.023 milliseconds
# 100.00% <= 1.519 milliseconds
# focus on tail latency (P99, P99.9) — average hides outliers
# P99 > 5x P50 indicates jitter or GC pauses
# save results to a file for comparison
redis-benchmark -t set,get -n 100000 --csv > bench-$(date +%F).csv
# compare two runs (before/after a config change)
diff bench-2025-01-01.csv bench-2025-01-02.csvBenchmark de Cluster e Lua
O modo --cluster distribui chaves pelos slots do cluster — essencial para benchmarks realistas de cluster (benchmarks de nó único ignoram o custo de roteamento entre slots). -r define o tamanho do keyspace aleatório (use um valor grande para evitar que cada um dos ops batam numa chave, o que infla os números via cache em memória). --eval faz benchmark de scripts Lua. --threads (Redis 6+) usa múltiplas threads de benchmark — útil quando uma única thread não gera carga suficiente para saturar o servidor. Sempre use -r para números realistas.
# benchmark a Redis Cluster (redis-benchmark supports cluster mode)
redis-benchmark --cluster -h node1 -p 7000 -t set,get -n 100000
# automatically distributes keys across cluster slots
# cluster mode with multiple nodes
redis-benchmark --cluster -h node1 -p 7000 -h node2 -p 7000 \
-t set,get -n 100000 -c 50
# benchmark a Lua script (--eval)
redis-benchmark -n 100000 eval "return redis.call('SET', KEYS[1], ARGV[1])" 0 mykey hello
# note: key and args are positional after the script
# benchmark with random keys (--random-data + keyspace length)
redis-benchmark -t set -n 100000 -r 1000000
# -r 1000000 = random keys from a 1M keyspace (SET key:RAND_INT value)
# avoids hitting the same key (tests real-world distribution)
# use a random payload (not the same bytes each time)
redis-benchmark -t set -n 100000 -r 1000000 -d 100 --random-data
# only run the benchmark for a fixed time (seconds)
redis-benchmark -t set --threads 4 -n 100000
# --threads (6+) uses multiple threads (default 1, doesn't help single-core)--idle e Aquecimento
--idle mede o custo puro de conexão/rede só com PINGs — a linha de base que você não consegue superar. Sempre aqueça o servidor antes de medir (caches frios subestimam o desempenho): rode um benchmark de descarte primeiro, depois o medido. --loop roda continuamente (útil para testes de carga sustentada). --seed torna o keyspace aleatório reproduzível — essencial para comparações A/B. --dbnum seleciona o banco (use um banco separado para não poluir dados de produção durante os benchmarks).
# --idle: only send PINGs (no commands) — measure pure connection overhead
redis-benchmark -t ping -n 100000 --idle
# useful for measuring connection / network baseline latency
# --dbnum: select a specific database
redis-benchmark -t set -n 100000 --dbnum 1
# --clients: same as -c (alias)
redis-benchmark -t set -n 100000 --clients 100
# warm up the server before measuring (avoid cold-start bias)
redis-benchmark -t set -n 10000 # warmup run (discard results)
redis-benchmark -t set -n 100000 # measured run
# --loop: run the benchmark forever (Ctrl+C to stop)
redis-benchmark -t set -n 100000 --loop
# --seed: reproducible random keys (same -r sequence every run)
redis-benchmark -t set -n 100000 -r 1000000 --seed 42
# benchmark with a specific client socket buffer
redis-benchmark -t set -n 100000 --numdatadb 1Interpretação e Armadilhas de Benchmark
Armadilhas de benchmark inflam números irrealisticamente: (1) benchmarks só no localhost ignoram a latência de rede; (2) sem -r, cada um dos ops batem numa chave (inflado por cache); (3) payloads minúsculos não estressam memória/rede; (4) ignorar o custo de persistência (o fsync do AOF pode cortar o rendimento 2-5x); (5) uma única thread de benchmark não satura um servidor multicore. Um benchmark realista usa -r (chaves aleatórias), -d (payload realista), --threads (cliente multithread) e testa com persistência e rede equivalentes à produção. Sempre divulgue os parâmetros do benchmark ao compartilhar números.
# COMMON PITFALL #1: benchmarking localhost only
# localhost numbers don't reflect real network latency
# always test over your production network path
# COMMON PITFALL #2: all keys the same (no -r)
# redis-benchmark -t set -n 100000
# -> all SETs hit "key:0" — inflated by in-memory caching
# FIX: use -r to randomize keys
redis-benchmark -t set -n 100000 -r 1000000
# COMMON PITFALL #3: tiny payloads only
# 3-byte values don't reflect real memory/network pressure
# test with realistic sizes
redis-benchmark -t set -n 100000 -d 256 -r 1000000
# COMMON PITFALL #4: ignoring persistence overhead
# benchmark with AOF on vs off to see the durability cost:
redis-benchmark -t set -n 100000 # with current persistence settings
# (then) CONFIG SET appendonly no
redis-benchmark -t set -n 100000 # without AOF — compare
# COMMON PITFALL #5: single-threaded benchmark client
# one benchmark thread may not generate enough load
redis-benchmark -t set -n 100000 --threads 4 -c 100
# GOOD BENCHMARK (realistic):
redis-benchmark -t set,get -n 1000000 -c 50 -P 16 -r 1000000 -d 100 --threads 4 --csvSnippets de Redis CLI relacionados
Copy-paste ready code for common tasks.
Conexão: URLs, TLS, AUTH & SELECT
Conectar a instâncias standalone, TLS, autenticadas ou índices de DB não padrão.
Modo interativo, HELP & inspeção
Navegar o REPL, descobrir comandos e introspectar o servidor.
MULTI / EXEC / WATCH (Transações)
Enfileirar comandos atomicamente e usar lock otimista com WATCH.
Pub/Sub: SUBSCRIBE, PUBLISH & PSUBSCRIBE
Messaging fan-out com canais e assinaturas por padrão.
MONITOR, SLOWLOG & depuração de latência
Observar cada comando em tempo real e encontrar consultas lentas.
EVAL, Lua & estatísticas de Function (Scripting no servidor)
Executar scripts Lua atômicos no servidor; carregar e chamar funções.
Persistência RDB / AOF & backup
Disparar snapshots, gerenciar reescrita de AOF e capturar um backup seguro.
Usuários ACL & operações de cluster
Gerenciar usuários ACL, ferramentas redis-check e resharding do cluster.
Was this helpful?