# Code Reference — Redis

_11 pages_

---
# Redis (/docs/redis)



# Redis [#redis]

Cache, data structures, pub/sub.

Browse the sidebar for every cheat sheet in this section.

## Sections [#sections]

*All notes are listed in the sidebar.*


---

# CLI Basics (/docs/redis/cli-basics)



# CLI Basics [#cli-basics]

*Redis · Reference cheat sheet*

***

## 📋 Overview [#-overview]

`redis-cli` is the standard admin and debugging client: run commands, monitor traffic, check latency, and inspect keys safely with `SCAN`.

## 🔧 Core concepts [#-core-concepts]

| Command / flag                   | Purpose                        |
| -------------------------------- | ------------------------------ |
| `redis-cli`                      | Interactive REPL               |
| `redis-cli -u redis://host:6379` | URL connect                    |
| `redis-cli CMD …`                | One-shot command               |
| `INFO`                           | Sections of server info        |
| `MONITOR`                        | Stream commands (prod caution) |
| `SCAN`                           | Iterate keys safely            |
| `--latency`                      | Latency sampler                |

| Key inspection     | Notes                |
| ------------------ | -------------------- |
| `TYPE key`         | Data structure       |
| `EXISTS key`       | 0/1                  |
| `MEMORY USAGE key` | Bytes (if available) |
| `OBJECT ENCODING`  | Internal encoding    |

## 💡 Examples [#-examples]

**Connect and ping:**

```shellscript
redis-cli -h 127.0.0.1 -p 6379 PING
```

**Scan keys by prefix:**

```shellscript
redis-cli --scan --pattern 'user:*'
```

**Info memory:**

```shellscript
redis-cli INFO memory
```

## ⚠️ Pitfalls [#️-pitfalls]

* `KEYS *` blocks — never on busy production instances.
* `MONITOR` is expensive and leaks command data (including values).
* Auth: use `AUTH` / ACL users — don't put passwords in shell history casually.

## 🔗 Related [#-related]

* [getting\_started.md](/docs/redis/getting-started)
* [strings.md](/docs/redis/strings)
* [expiry\_ttl.md](/docs/redis/expiry-ttl)
* [persistence.md](/docs/redis/persistence)


---

# Expiry & TTL (/docs/redis/expiry-ttl)



# Expiry & TTL [#expiry--ttl]

*Redis · Reference cheat sheet*

***

## 📋 Overview [#-overview]

Keys can expire automatically. TTL powers caches, sessions, and ephemeral locks. Expiry is per key (not per hash field).

## 🔧 Core concepts [#-core-concepts]

| Command              | Role                                          |
| -------------------- | --------------------------------------------- |
| `EXPIRE key seconds` | Set TTL                                       |
| `PEXPIRE`            | TTL in ms                                     |
| `TTL` / `PTTL`       | Remaining time (`-1` no expire, `-2` missing) |
| `PERSIST`            | Remove expiry                                 |
| `SET … EX`           | Set value + TTL atomically                    |
| `EXPIREAT`           | Expire at unix time                           |

| Eviction (when maxmemory) | Examples                  |
| ------------------------- | ------------------------- |
| `volatile-lru`            | Evict expiring keys LRU   |
| `allkeys-lru`             | Evict any key LRU         |
| `noeviction`              | Errors on write when full |

## 💡 Examples [#-examples]

**Session TTL:**

```shellscript
SET sess:abc123 '{"userId":42}' EX 1800
TTL sess:abc123
```

**Refresh TTL:**

```shellscript
EXPIRE sess:abc123 1800
```

**Lock with auto-expiry:**

```shellscript
SET lock:migrate 1 NX EX 60
```

## ⚠️ Pitfalls [#️-pitfalls]

* Expired keys may still appear briefly until lazy/active expiration removes them.
* Writing a key with `SET` without TTL removes any previous expiry unless using keep-ttl options.
* Relying on TTL for correctness without handling miss paths causes subtle bugs.

## 🔗 Related [#-related]

* [strings.md](/docs/redis/strings)
* [persistence.md](/docs/redis/persistence)
* [getting\_started.md](/docs/redis/getting-started)
* [cli\_basics.md](/docs/redis/cli-basics)


---

# Getting Started with Redis (/docs/redis/getting-started)



# Getting Started with Redis [#getting-started-with-redis]

*Redis · Reference cheat sheet*

***

## 📋 Overview [#-overview]

Redis is an in-memory data structure server used for caching, sessions, queues, rate limits, and pub/sub. Data structures are first-class (strings, hashes, lists, sets, sorted sets).

## 🔧 Core concepts [#-core-concepts]

| Idea                              | Meaning                                   |
| --------------------------------- | ----------------------------------------- |
| Key                               | String name for a value                   |
| TTL                               | Optional expiry on keys                   |
| Single-threaded command execution | Commands are atomic per command           |
| Persistence                       | Optional RDB/AOF durability               |
| DB index                          | Logical keyspaces `0–15` (default config) |

| Command     | Purpose               |
| ----------- | --------------------- |
| `redis-cli` | Interactive client    |
| `PING`      | Health check → `PONG` |
| `INFO`      | Server stats          |
| `SELECT n`  | Switch DB index       |

## 💡 Examples [#-examples]

**Run Redis (Docker):**

```shellscript
docker run --rm -p 6379:6379 redis:7-alpine
```

**First commands:**

```shellscript
redis-cli
> PING
PONG
> SET greeting "hello"
OK
> GET greeting
"hello"
```

**From Node sketch:**

```js
import { createClient } from "redis";
const client = createClient({ url: "redis://127.0.0.1:6379" });
await client.connect();
await client.set("greeting", "hello");
```

## ⚠️ Pitfalls [#️-pitfalls]

* Memory is finite — without eviction policy + TTLs, Redis can OOM.
* Treating Redis as the only source of truth without persistence/HA is risky.
* Key naming collisions across features — use prefixes (`app:session:`).

## 🔗 Related [#-related]

* [strings.md](/docs/redis/strings)
* [expiry\_ttl.md](/docs/redis/expiry-ttl)
* [cli\_basics.md](/docs/redis/cli-basics)
* [Comparisons/redis\_vs\_postgres.md](/docs/redis/../comparisons/redis-vs-postgres)


---

# Glossary (/docs/redis/glossary)



# Glossary [#glossary]

*Redis · Reference cheat sheet*

***

## 📋 Overview [#-overview]

Alphabetical glossary of Redis data structures, durability, and client terms.

## 🔧 Core concepts [#-core-concepts]

| Term       | Definition                                            |
| ---------- | ----------------------------------------------------- |
| AOF        | Append-only file persistence log of write operations. |
| Eviction   | Removing keys under `maxmemory` per policy.           |
| Hash       | Field-value map stored at a single key.               |
| Keyspace   | The set of keys in a selected logical database.       |
| List       | Ordered sequence supporting push/pop at ends.         |
| Pub/Sub    | Fire-and-forget channel messaging.                    |
| RDB        | Snapshot persistence format.                          |
| Replica    | Read copy of a primary for HA/scale-out reads.        |
| Set        | Unordered collection of unique members.               |
| Sorted set | Unique members ordered by score.                      |
| Stream     | Append-only log with consumer groups.                 |
| TTL        | Time-to-live before a key expires.                    |
| `SCAN`     | Cursor-based incremental iteration.                   |

## 💡 Examples [#-examples]

**Type check:**

```shellscript
TYPE session:abc
TTL session:abc
```

**Logical DB:**

```shellscript
SELECT 0
```

## ⚠️ Pitfalls [#️-pitfalls]

* “Persistent Redis” still needs backup/HA design — persistence ≠ full DR plan.
* Mixing cache and primary data on one instance without key discipline causes pain.

## 🔗 Related [#-related]

* [getting\_started.md](/docs/redis/getting-started)
* [persistence.md](/docs/redis/persistence)
* [expiry\_ttl.md](/docs/redis/expiry-ttl)
* [README.md](/docs/redis)


---

# Hashes (/docs/redis/hashes)



# Hashes [#hashes]

*Redis · Reference cheat sheet*

***

## 📋 Overview [#-overview]

Hashes map field → value under one key. Ideal for objects (user profiles, config bags) without serializing a whole JSON blob for every field update.

## 🔧 Core concepts [#-core-concepts]

| Command                | Role                    |
| ---------------------- | ----------------------- |
| `HSET key field value` | Set field               |
| `HGET key field`       | Get field               |
| `HGETALL key`          | All fields              |
| `HMGET`                | Multiple fields         |
| `HDEL`                 | Delete fields           |
| `HEXISTS`              | Field exists?           |
| `HINCRBY`              | Increment integer field |
| `HKEYS` / `HVALS`      | List fields/values      |

| When hash vs string JSON | Prefer hash when                 |
| ------------------------ | -------------------------------- |
| Partial updates          | Frequent single-field writes     |
| Memory                   | Many small fields (with caveats) |
| Atomic field incr        | `HINCRBY`                        |

## 💡 Examples [#-examples]

**User object:**

```shellscript
HSET user:42 name Ada email ada@example.com
HGET user:42 email
HGETALL user:42
```

**Increment field:**

```shellscript
HINCRBY user:42 login_count 1
```

**Delete field:**

```shellscript
HDEL user:42 email
```

## ⚠️ Pitfalls [#️-pitfalls]

* `HGETALL` on huge hashes is expensive — prefer `HSCAN`.
* Nested structures aren't native — store JSON in a field or use separate keys.
* TTL is on the whole hash key, not per field.

## 🔗 Related [#-related]

* [strings.md](/docs/redis/strings)
* [lists\_sets.md](/docs/redis/lists-sets)
* [expiry\_ttl.md](/docs/redis/expiry-ttl)
* [getting\_started.md](/docs/redis/getting-started)


---

# Lists & Sets (/docs/redis/lists-sets)



# Lists & Sets [#lists--sets]

*Redis · Reference cheat sheet*

***

## 📋 Overview [#-overview]

Lists are ordered sequences (queues, timelines). Sets are unordered unique collections (tags, membership). Both are foundational for queues and relationships.

## 🔧 Core concepts [#-core-concepts]

| List commands     | Role            |
| ----------------- | --------------- |
| `LPUSH` / `RPUSH` | Push left/right |
| `LPOP` / `RPOP`   | Pop left/right  |
| `LRANGE`          | Slice           |
| `LLEN`            | Length          |
| `BLPOP` / `BRPOP` | Blocking pop    |

| Set commands                  | Role               |
| ----------------------------- | ------------------ |
| `SADD` / `SREM`               | Add/remove members |
| `SISMEMBER`                   | Membership test    |
| `SMEMBERS`                    | All members        |
| `SINTER` / `SUNION` / `SDIFF` | Set algebra        |
| `SCARD`                       | Count              |

## 💡 Examples [#-examples]

**Simple queue:**

```shellscript
LPUSH jobs '{"id":1}'
BRPOP jobs 5
```

**Tags set:**

```shellscript
SADD post:9:tags redis cache
SISMEMBER post:9:tags redis
SINTER user:1:tags user:2:tags
```

**Recent items (list trim):**

```shellscript
LPUSH feed:42 itemA
LTRIM feed:42 0 99
```

## ⚠️ Pitfalls [#️-pitfalls]

* `SMEMBERS` / large `LRANGE` can block — use `SSCAN` / limit ranges.
* Lists allow duplicates; sets do not — pick the right structure.
* Blocking pops need careful timeouts in app servers to avoid stuck workers.

## 🔗 Related [#-related]

* [sorted\_sets.md](/docs/redis/sorted-sets)
* [hashes.md](/docs/redis/hashes)
* [pubsub.md](/docs/redis/pubsub)
* [strings.md](/docs/redis/strings)


---

# Persistence (/docs/redis/persistence)



# Persistence [#persistence]

*Redis · Reference cheat sheet*

***

## 📋 Overview [#-overview]

Redis can persist in-memory data via RDB snapshots, AOF logs, or both. Persistence improves durability but is not a substitute for backups and replication strategy.

## 🔧 Core concepts [#-core-concepts]

| Mode           | How                               |
| -------------- | --------------------------------- |
| RDB            | Point-in-time `.rdb` snapshots    |
| AOF            | Append-only log of write commands |
| RDB+AOF        | Common hybrid                     |
| No persistence | Pure cache (accept data loss)     |

| Knob          | Meaning                      |
| ------------- | ---------------------------- |
| `save`        | RDB schedule                 |
| `appendonly`  | Enable AOF                   |
| `appendfsync` | `always` / `everysec` / `no` |
| Replica       | Continuity via replication   |

## 💡 Examples [#-examples]

**Check persistence config:**

```shellscript
redis-cli CONFIG GET save
redis-cli CONFIG GET appendonly
```

**Manual save:**

```shellscript
BGSAVE
LASTSAVE
```

**AOF rewrite:**

```shellscript
BGREWRITEAOF
```

## ⚠️ Pitfalls [#️-pitfalls]

* `appendfsync always` is safest and slowest — usually `everysec` is the compromise.
* Forking for `BGSAVE` on large datasets needs free memory headroom.
* Restoring from outdated RDB after a crash still loses recent writes if AOF is off.

## 🔗 Related [#-related]

* [getting\_started.md](/docs/redis/getting-started)
* [expiry\_ttl.md](/docs/redis/expiry-ttl)
* [cli\_basics.md](/docs/redis/cli-basics)
* [Comparisons/redis\_vs\_postgres.md](/docs/redis/../comparisons/redis-vs-postgres)


---

# Pub/Sub (/docs/redis/pubsub)



# Pub/Sub [#pubsub]

*Redis · Reference cheat sheet*

***

## 📋 Overview [#-overview]

Pub/Sub broadcasts messages to subscribers on channels. Fire-and-forget: if no subscriber is listening, messages are not queued (unlike Streams/lists).

## 🔧 Core concepts [#-core-concepts]

| Command                   | Role                        |
| ------------------------- | --------------------------- |
| `PUBLISH channel message` | Send message                |
| `SUBSCRIBE channel…`      | Subscribe (enters sub mode) |
| `PSUBSCRIBE pattern`      | Pattern subscribe           |
| `UNSUBSCRIBE`             | Leave channels              |
| `PUBSUB CHANNELS`         | List active channels        |

| vs alternatives | When                                   |
| --------------- | -------------------------------------- |
| Pub/Sub         | Live fan-out, presence                 |
| Lists           | Work queues with persistence in memory |
| Streams         | Consumer groups, replay                |

## 💡 Examples [#-examples]

**Publisher:**

```shellscript
PUBLISH news:alerts "deploy started"
```

**Subscriber (blocks):**

```shellscript
SUBSCRIBE news:alerts
```

**Pattern:**

```shellscript
PSUBSCRIBE news:*
```

## ⚠️ Pitfalls [#️-pitfalls]

* Subscribers must be connected at publish time — no backlog.
* A connection in subscribe mode cannot run normal commands until unsubscribed.
* For reliable messaging, prefer Streams or an external broker.

## 🔗 Related [#-related]

* [lists\_sets.md](/docs/redis/lists-sets)
* [getting\_started.md](/docs/redis/getting-started)
* [cli\_basics.md](/docs/redis/cli-basics)
* [persistence.md](/docs/redis/persistence)


---

# Sorted Sets (/docs/redis/sorted-sets)



# Sorted Sets [#sorted-sets]

*Redis · Reference cheat sheet*

***

## 📋 Overview [#-overview]

Sorted sets (ZSETs) store unique members with a floating-point score. Ideal for leaderboards, time indexes, and range queries by score or rank.

## 🔧 Core concepts [#-core-concepts]

| Command                 | Role               |
| ----------------------- | ------------------ |
| `ZADD key score member` | Add/update         |
| `ZRANGE`                | By rank (low→high) |
| `ZREVRANGE`             | By rank high→low   |
| `ZRANGEBYSCORE`         | By score range     |
| `ZRANK` / `ZREVRANK`    | Rank of member     |
| `ZSCORE`                | Score of member    |
| `ZINCRBY`               | Increment score    |
| `ZREM`                  | Remove member      |
| `ZCARD` / `ZCOUNT`      | Counts             |

| Use case    | Score idea     |
| ----------- | -------------- |
| Leaderboard | Points         |
| Schedule    | Unix timestamp |
| Rate window | Event time     |

## 💡 Examples [#-examples]

**Leaderboard:**

```shellscript
ZADD lb:game 100 alice 250 bob 180 cara
ZREVRANGE lb:game 0 2 WITHSCORES
ZINCRBY lb:game 20 alice
```

**Due jobs by time:**

```shellscript
ZADD queue:due 1735689600 job:1
ZRANGEBYSCORE queue:due -inf +inf LIMIT 0 10
```

## ⚠️ Pitfalls [#️-pitfalls]

* Members are unique — re-`ZADD` updates the score.
* Large ranges without `LIMIT` can return huge payloads.
* Lexicographical commands (`ZRANGEBYLEX`) require same score — easy to misuse.

## 🔗 Related [#-related]

* [lists\_sets.md](/docs/redis/lists-sets)
* [expiry\_ttl.md](/docs/redis/expiry-ttl)
* [cli\_basics.md](/docs/redis/cli-basics)
* [getting\_started.md](/docs/redis/getting-started)


---

# Strings (/docs/redis/strings)



# Strings [#strings]

*Redis · Reference cheat sheet*

***

## 📋 Overview [#-overview]

Strings are the simplest Redis values: text, integers (for counters), or binary blobs (up to 512 MB theoretically; keep small in practice).

## 🔧 Core concepts [#-core-concepts]

| Command                    | Role              |
| -------------------------- | ----------------- |
| `SET key value`            | Set string        |
| `GET key`                  | Get string        |
| `MSET` / `MGET`            | Multi set/get     |
| `SETNX`                    | Set if not exists |
| `INCR` / `DECR`            | Integer increment |
| `APPEND`                   | Append to string  |
| `GETRANGE` / `SETRANGE`    | Substring ops     |
| `SET key value EX seconds` | Set with TTL      |

| Option          | Meaning                          |
| --------------- | -------------------------------- |
| `EX` / `PX`     | Expire seconds / ms              |
| `NX` / `XX`     | Only if missing / only if exists |
| `GET` (SET GET) | Return old value (Redis 6.2+)    |

## 💡 Examples [#-examples]

**Cache entry:**

```shellscript
SET user:42:profile '{"name":"Ada"}' EX 3600
GET user:42:profile
```

**Counter:**

```shellscript
INCR page:home:views
GET page:home:views
```

**Lock-style NX:**

```shellscript
SET lock:job1 1 NX EX 30
```

## ⚠️ Pitfalls [#️-pitfalls]

* `INCR` fails if the value is not an integer string.
* Huge strings block peers longer during ops — split or use other structures.
* `KEYS *` in production is dangerous — use `SCAN`.

## 🔗 Related [#-related]

* [hashes.md](/docs/redis/hashes)
* [expiry\_ttl.md](/docs/redis/expiry-ttl)
* [cli\_basics.md](/docs/redis/cli-basics)
* [getting\_started.md](/docs/redis/getting-started)

