Learn Labs
Foundations

Keys & redis-cli

Key naming, SCAN vs KEYS, inspecting keys, and command complexity

Everything in Redis is a key pointing to a value of some type. There are no tables and no schemas; the key names are your schema. This lesson covers naming them, finding them, and inspecting them safely.

Key naming

Use colon-separated namespaces, from general to specific:

app:product:1001              # hash: one product
app:category:peripherals      # set: product IDs in a category
cache:product:1001            # string: cached JSON, has a TTL
session:7f3a9c...             # hash: one web session
rate:fixed:user-42:179178     # string: a rate-limit window counter
lb:weekly                     # sorted set: a leaderboard

Conventions that pay off:

  • Prefix by purpose (cache:, session:). It makes ACLs possible (the app user is restricted to these prefixes), and lets you find and measure each kind of data.
  • Keep keys short but readable. Every key name is stored in memory; u:42 vs user:profile:42 matters at 100 million keys, not at 10,000.
  • Include the ID last, so SCAN MATCH app:product:* finds a whole family.
  • In Redis Cluster, use hash tags like {user:42}:cart to keep related keys on one node. See Redis Cluster.

Keys are binary-safe up to 512 MB. Don't come anywhere near that.

Seed some data

docker compose -f compose_prod.yaml run --rm labs python seed.py
docker exec -it redis redis-cli --user app --pass app123

Finding keys: SCAN, never KEYS

127.0.0.1:6379> SCAN 0 MATCH app:product:* COUNT 100
1) "0"                       # next cursor; "0" means the iteration is complete
2) 1) "app:product:1003"
 2) "app:product:1001"
 ...

SCAN walks the keyspace incrementally: each call does a bounded amount of work and returns a cursor for the next call. COUNT is a hint of how much work per call, not how many results. Keep calling until the cursor comes back as 0.

KEYS pattern does the same thing in one blocking O(N) call. On a production instance with millions of keys it freezes Redis for seconds. The app user here can't run it at all, because KEYS is in the @dangerous ACL category.

Inspecting a key

TYPE app:product:1001hashEXISTS app:product:10011OBJECT ENCODING app:product:1001listpack (small compact form)MEMORY USAGE app:product:1001bytes, including overheadTTL cache:product:1seconds left; -1 = no TTL; -2 = doesn't existOBJECT FREQ / OBJECT IDLETIMEaccess frequency (LFU) or idle seconds (LRU)DBSIZEnumber of keys in the current database

Generic key commands

DEL k1 k2delete; frees memory on the main threadUNLINK k1 k2delete; frees memory in a background thread (use for big keys)RENAME old newoverwrites 'new' if it existsCOPY src dstduplicate a keyEXPIRE k 60TTL in seconds (also PEXPIRE ms, EXPIREAT timestamp)PERSIST kremove the TTLTOUCH kupdate last-access time without reading

Complexity is the API

Redis documentation lists the time complexity of every command. It matters more here than in most databases, because one slow command blocks every client:

CommandComplexitySafe on a huge key?
GET, SET, HGET, SADD, SISMEMBERO(1)Yes
ZADD, ZRANK, ZINCRBYO(log N)Yes
LRANGE k 0 9, ZRANGE k 0 9O(log N + M) for M returnedYes, if M is small
HGETALL, SMEMBERS, LRANGE k 0 -1O(N)No
DEL on a big hash/set/zsetO(N)No; use UNLINK
KEYS, FLUSHALL (sync)O(N) over the keyspaceNever in production
SUNION, SINTER, ZUNIONSTOREDepends on input sizesCareful

A useful habit: before using a command in code, check its complexity and ask "how big can N get?"

redis-cli tricks

redis-cli --user default --pass redis123 --bigkeys     # biggest key of each type (uses SCAN)
redis-cli ... --memkeys                                 # keys using the most memory
redis-cli ... --latency                                 # continuous PING latency
redis-cli ... --stat                                    # live ops/s, memory, clients
redis-cli ... --scan --pattern 'cache:*' | head         # SCAN from the shell
redis-cli ... -r 5 -i 1 INFO stats | grep ops_per_sec   # repeat a command
redis-cli ... --eval script.lua key1 , arg1             # run a Lua file

Lab

  1. Run seed.py, then use SCAN to list every app:* key.
  2. For each key, run TYPE and OBJECT ENCODING. Which types appear?
  3. Run redis-cli --bigkeys (as default). Which key is biggest?
  4. As the app user, try KEYS *. Read the error.
  5. Find the TTL of a cache:product:* key after running cache_aside.py. Run TTL a few times and watch it count down.

On this page